The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): preserve tool results across ID variants
joaomarcos5496d5995ab7
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex 52f790148bb..d0842493ee6 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -33,7 +33,12 @@ from pathlib import Pathfrom typing import Any, Dict, List, Optional, Tuplefrom hermes_cli.timeouts import get_provider_request_timeout-from agent.message_sanitization import _FULL_ARGS_LOG_BOUND+from agent.message_sanitization import (+ _FULL_ARGS_LOG_BOUND,+ coalesce_tool_call_id,+ tool_call_id_variants,+ tool_result_id_variants,+)from agent.prompt_builder import format_steer_markerfrom agent.tool_dispatch_helpers import _trajectory_normalize_msg, make_tool_result_messagefrom agent.trajectory import convert_scratchpad_to_think@@ -413,7 +418,10 @@ def sanitize_tool_call_arguments(candidate = messages[scan_index]if not isinstance(candidate, dict) or candidate.get("role") != "tool":break- if candidate.get("tool_call_id") == tool_call_id:+ if (+ tool_result_id_variants(candidate.get("tool_call_id"))+ & tool_call_id_variants(tool_call)+ ):existing_tool_msg = candidatebreakscan_index += 1@@ -688,28 +696,18 @@ def repair_message_sequence(agent, messages: List[Dict]) -> int:continuecollapsed.append(msg)- # Pass 1: drop stray tool messages that don't follow a known- # assistant tool_call_id. Uses a rolling set of known ids refreshed- # on each assistant message.- #- # Both ``id`` AND ``call_id`` are registered for every assistant- # tool_call. In the Codex Responses API format the two differ- # (``id`` = ``fc_...`` response-item id, ``call_id`` = ``call_...``- # the function-call id), and a tool result's ``tool_call_id`` may be- # matched against *either* depending on which code path built it- # (the OpenAI-compatible path stores ``tc.id``; codex paths store- # ``call_id``). Registering only ``id`` — as this pass did before —- # made a valid tool result look orphaned whenever the assistant- # tool_call carried a distinct ``call_id`` (or only ``call_id``); the- # pass then dropped it, leaving the assistant tool_call unanswered and- # producing an HTTP 400 on strict providers (DeepSeek, Kimi). Matching- # on the *superset* of both keys achieves the same tolerance as- # ``_get_tool_call_id_static``'s ``call_id || id`` — a match set must- # accept every legitimate reference, not just the canonical one (#58168).- known_tool_ids: set = set()- # Maps every registered id variant back to the full variant set of the- # tool_call it came from, so consuming one variant consumes its siblings.- tool_id_siblings: Dict[str, set] = {}+ # Pass 1: drop stray tool messages that don't follow a known assistant+ # tool call. A Responses call can have several equivalent spellings+ # (call_id, id, response_item_id, or a composite ``call|item`` id), so+ # consume the whole alias group when one spelling is matched. Otherwise a+ # duplicate result keyed on the sibling alias would survive and be replayed+ # to strict providers (#66974). Alias expansion lives in+ # ``agent.message_sanitization.tool_call_id_variants`` /+ # ``tool_result_id_variants`` (single policy owner) — which also handles+ # SDK tool_call objects, preserving the #91768 dict-or-object tolerance.+ known_tool_ids: Dict[str, int] = {}+ matched_tool_groups: set = set()+ next_tool_group = 0filtered: List[Dict] = []for msg in collapsed:if not isinstance(msg, dict):@@ -717,45 +715,35 @@ def repair_message_sequence(agent, messages: List[Dict]) -> int:continuerole = msg.get("role")if role == "assistant":- known_tool_ids = set()- tool_id_siblings = {}+ known_tool_ids = {}+ matched_tool_groups = set()for tc in (msg.get("tool_calls") or []):- # Mirror ``_get_tool_call_id_static``'s dict-or-object- # tolerance: SDK tool_call objects (e.g. an unserialized- # ``ChatCompletionMessageToolCall``) reach this pass on- # host-fed / pre-serialization histories just as often as- # plain dicts. Skipping non-dict entries left- # ``known_tool_ids`` empty for such messages, so the- # following legitimate ``tool`` result was misclassified- # as orphaned and silently dropped.- variants = set()- for key in ("id", "call_id"):- tc_id = tc.get(key) if isinstance(tc, dict) else getattr(tc, key, None)- if tc_id:- variants.add(tc_id)+ variants = tool_call_id_variants(tc)+ if not variants:+ continue+ group_id = next_tool_group+ next_tool_group += 1for tc_id in variants:- known_tool_ids.add(tc_id)- tool_id_siblings[tc_id] = variants+ known_tool_ids.setdefault(tc_id, group_id)filtered.append(msg)elif role == "tool":- tc_id = msg.get("tool_call_id")- if tc_id and tc_id in known_tool_ids:+ result_variants = tool_result_id_variants(msg.get("tool_call_id"))+ candidate_groups = {+ known_tool_ids[tc_id]+ for tc_id in result_variants+ if tc_id in known_tool_ids+ and known_tool_ids[tc_id] not in matched_tool_groups+ }+ if not result_variants:+ filtered.append(msg)+ elif candidate_groups:+ # Consume the whole alias group so a SECOND result replaying+ # any sibling spelling falls into the drop branch below —+ # strict providers reject duplicate tool_call_ids with HTTP+ # 400 (#58327, #66974). Credit: #55436.+ group_id = min(candidate_groups)filtered.append(msg)- # Consume the id so a SECOND tool result carrying the same- # tool_call_id (duplicate from a retry/crash/session-resume- # glitch) falls into the drop branch below instead of being- # replayed — strict providers (DeepSeek) reject a duplicate- # tool_call_id with HTTP 400 (#58327). Credit: #55436.- #- # Consume EVERY variant of the matched call, not just the one- # this result referenced. A Codex/Responses tool_call registers- # both ``id`` (``fc_...``) and ``call_id`` (``call_...``) above- # (#58168), so discarding only the matched key leaves its- # sibling live — and a duplicate result keyed on that sibling- # sails straight through this guard, re-creating the very 400- # the consume step exists to prevent.- for sibling in tool_id_siblings.get(tc_id, {tc_id}):- known_tool_ids.discard(sibling)+ matched_tool_groups.add(group_id)else:repairs += 1else:@@ -763,7 +751,8 @@ def repair_message_sequence(agent, messages: List[Dict]) -> int:# A user turn closes the tool-result run; subsequent# tool messages without a fresh assistant tool_call# are orphans.- known_tool_ids = set()+ known_tool_ids = {}+ matched_tool_groups = set()filtered.append(msg)# Pass 2: merge consecutive user messages. Preserves all user input@@ -3482,21 +3471,12 @@ def repair_tool_call(agent, tool_name: str) -> str | 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.+ Thin forwarder — the policy owner is+ ``agent.message_sanitization.tool_call_id_variants`` (handles ``id``,+ ``call_id``, ``response_item_id``, and composite ``call|item`` spellings).+ Kept for backward compatibility with existing importers."""- 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+ return set(tool_call_id_variants(tc))# Placeholder substituted for an empty non-final message that would otherwise@@ -3734,74 +3714,83 @@ def sanitize_api_messages(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]elif isinstance(tc, dict):tc["function"] = {"name": _EMPTY_NAME_SENTINEL, "arguments": "{}"}- surviving_call_ids: set = set()+ assistant_call_variants: List[tuple[Any, frozenset[str]]] = []+ surviving_call_ids: set[str] = set()for msg in messages:- if msg.get("role") == "assistant":- for tc in msg.get("tool_calls") or []:- # 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()- for msg in messages:- if msg.get("role") == "tool":- cid = (msg.get("tool_call_id") or "").strip()- if cid:- result_call_ids.add(cid)-- # 1. Drop tool results with no matching assistant call- orphaned_results = result_call_ids - surviving_call_ids- if orphaned_results:- messages = [- m for m in messages- if not (m.get("role") == "tool" and (m.get("tool_call_id") or "").strip() in orphaned_results)+ if msg.get("role") != "assistant":+ continue+ for tc in msg.get("tool_calls") or []:+ # A tool_call may carry SEVERAL equivalent id spellings (``id``+ # fc_..., ``call_id`` call_..., ``response_item_id``, or a+ # composite ``call|item`` bridge id). ``_get_tool_call_id_static``+ # returns only the preferred one, but a tool result keyed on any+ # OTHER spelling would then look orphaned and get dropped ++ # replaced with a bogus "[Result unavailable]" stub — silently+ # eating a perfectly valid tool result (#55626, #63000). Register+ # EVERY variant so a result matching any of them survives.+ variants = tool_call_id_variants(tc)+ if variants:+ assistant_call_variants.append((tc, variants))+ surviving_call_ids.update(variants)++ result_entries = [+ (msg, tool_result_id_variants(msg.get("tool_call_id")))+ for msg in messages+ if msg.get("role") == "tool"+ ]++ # 1. Drop tool results whose complete alias set matches no assistant call.+ orphaned_result_objects = {+ id(msg)+ for msg, variants in result_entries+ if variants and not (variants & surviving_call_ids)+ }+ if orphaned_result_objects:+ messages = [m for m in messages if id(m) not in orphaned_result_objects]+ result_entries = [+ (msg, variants)+ for msg, variants in result_entries+ if id(msg) not in orphaned_result_objects]_ra().logger.debug("Pre-call sanitizer: removed %d orphaned tool result(s)",- len(orphaned_results),+ len(orphaned_result_objects),)- # 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:+ # 2. Inject one stub per assistant call with no result on ANY alias.+ surviving_result_variants = [+ variants for _, variants in result_entries if variants+ ]+ missing_tool_calls = [+ tc+ for tc, variants in assistant_call_variants+ if not any(variants & result_variants for result_variants in surviving_result_variants)+ ]+ if missing_tool_calls:+ missing_tool_call_objects = {id(tc) for tc in missing_tool_calls}+ 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 []:+ if id(tc) not in missing_tool_call_objects:+ continue+ cid = coalesce_tool_call_id(tc)+ if not cid:+ variants = tool_call_id_variants(tc)+ cid = sorted(variants)[0] if variants else ""+ 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,+ })messages = patched_ra().logger.debug("Pre-call sanitizer: added %d stub tool result(s)",- stub_count,+ len(missing_tool_calls),)# 3. Deduplicate tool_call_ids. Strict providers (DeepSeek) reject a@@ -3824,16 +3813,19 @@ def sanitize_api_messages(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]# semantics keep both protections intact: a re-emitted result still# answers no pending call and is still dropped, while a genuine new call# that reuses the id re-arms that id first.+ # Variant-group tracking: answering or deduping one spelling consumes+ # its siblings too. A Codex/Responses tool_call registers ``id``+ # (fc_...), ``call_id`` (call_...), ``response_item_id``, and composite+ # spellings (#55626/#58168/#63000); tracking only the coalesced id here+ # made a result keyed on any OTHER variant look like it answered no+ # outstanding call, so this pass deleted the very result step 2's+ # variant-aware matching had just preserved (issue #93251 — whole+ # parallel batches vanished).seen_assistant_call_ids: set = set()outstanding_call_ids: set = set()- # Variant → full variant-set of the tool_call it belongs to, so answering- # or deduping one variant consumes its siblings too. A Codex/Responses- # tool_call registers BOTH ``id`` (fc_...) and ``call_id`` (call_...)- # (#55626/#58168); tracking only the coalesced id here made a result- # keyed on the OTHER variant look like it answered no outstanding call,- # so this pass deleted the very result step 2's variant-aware matching- # had just preserved (issue #93251 — whole parallel batches vanished).- dedup_id_siblings: Dict[str, set] = {}+ outstanding_groups: Dict[int, frozenset] = {}+ variant_to_group: Dict[str, int] = {}+ next_group_id = 0deduped: List[Dict[str, Any]] = []removed_dupes = 0for msg in messages:@@ -3841,14 +3833,18 @@ def sanitize_api_messages(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]if role == "assistant" and msg.get("tool_calls"):kept_tcs = []for tc in msg.get("tool_calls") or []:- variants = _tool_call_id_variants(tc)+ variants = tool_call_id_variants(tc)if variants and variants & seen_assistant_call_ids:removed_dupes += 1continue- for cid in variants:- seen_assistant_call_ids.add(cid)- outstanding_call_ids.add(cid)- dedup_id_siblings[cid] = variants+ if variants:+ group_id = next_group_id+ next_group_id += 1+ outstanding_groups[group_id] = variants+ for variant in variants:+ seen_assistant_call_ids.add(variant)+ outstanding_call_ids.add(variant)+ variant_to_group.setdefault(variant, group_id)kept_tcs.append(tc)if kept_tcs:msg = {**msg, "tool_calls": kept_tcs}@@ -3856,18 +3852,28 @@ def sanitize_api_messages(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]msg = {k: v for k, v in msg.items() if k != "tool_calls"}deduped.append(msg)elif role == "tool":- cid = (msg.get("tool_call_id") or "").strip()- if cid and cid not in outstanding_call_ids:+ result_variants = tool_result_id_variants(msg.get("tool_call_id"))+ candidate_groups = {+ variant_to_group[variant]+ for variant in result_variants+ if variant in variant_to_group+ and variant in outstanding_call_ids+ }+ if result_variants and not candidate_groups:removed_dupes += 1continue- if cid:+ if candidate_groups:# Answered: consume EVERY variant of the matched call so a- # second result replaying either sibling is still caught- # above, and the ids are re-armable by the next assistant- # call that reuses them.- for sibling in dedup_id_siblings.get(cid, {cid}):- outstanding_call_ids.discard(sibling)- seen_assistant_call_ids.discard(sibling)+ # second result replaying any sibling spelling is still+ # caught above, and the ids are re-armable by the next+ # assistant call that reuses them.+ group_id = min(candidate_groups)+ group_variants = outstanding_groups.pop(group_id, frozenset())+ for variant in group_variants:+ outstanding_call_ids.discard(variant)+ seen_assistant_call_ids.discard(variant)+ if variant_to_group.get(variant) == group_id:+ variant_to_group.pop(variant, None)deduped.append(msg)else:deduped.append(msg)diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex 2a9e0b16a2c..9f6be7562ed 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -5699,22 +5699,14 @@ This compaction should PRIORITISE preserving all information related to the focudef _tool_call_id_variants(tc) -> set:"""Return every id variant a tool result might reference *tc* by.- A tool result's ``tool_call_id`` may be keyed on either ``id`` or- ``call_id`` depending on which code path built it — in the Codex- Responses API format they are distinct (``id`` is the ``fc_...``- response-item id, ``call_id`` is the ``call_...`` function-call id).- Matching on a single value (the old ``call_id || id`` precedence)- misclassified a genuinely matching pair as orphaned whenever the- result used the field that precedence didn't pick, dropping BOTH the- valid result and its tool_call. Registering the superset of both ids- is the same fix #58168 applied to ``repair_message_sequence``'s- known-id set.+ Thin forwarder — the policy owner is+ ``agent.message_sanitization.tool_call_id_variants``, which also+ expands ``response_item_id`` and composite ``call|item`` bridge+ spellings (#63000), so the compressor's pairing tolerance matches+ the pre-call sanitizer's exactly and the two can never drift."""- if isinstance(tc, dict):- get = tc.get- else:- get = lambda key: getattr(tc, key, None)- return {v for v in (get("id"), get("call_id")) if v}+ from agent.message_sanitization import tool_call_id_variants+ return set(tool_call_id_variants(tc))def _sanitize_tool_pairs(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:"""Fix orphaned tool_call / tool_result pairs after compression.diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex 24ebd0edbb7..200ddd22168 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -51,6 +51,7 @@ from agent.runtime_cwd import resolve_agent_cwdfrom agent.message_sanitization import (close_interrupted_tool_sequence,_repair_tool_call_arguments,+ coalesce_tool_call_id,_sanitize_messages_non_ascii,_sanitize_messages_surrogates,_sanitize_structure_non_ascii,@@ -7083,7 +7084,7 @@ def run_conversation(append_message(messages, {"role": "tool","name": tc.function.name,- "tool_call_id": tc.id,+ "tool_call_id": coalesce_tool_call_id(tc),"content": content,})continue@@ -7187,7 +7188,7 @@ def run_conversation(append_message(messages, {"role": "tool","name": tc.function.name,- "tool_call_id": tc.id,+ "tool_call_id": coalesce_tool_call_id(tc),"content": tool_result,})continue@@ -7335,7 +7336,7 @@ def run_conversation(append_message(messages, {"role": "tool","name": tc.function.name,- "tool_call_id": tc.id,+ "tool_call_id": coalesce_tool_call_id(tc),"content": _invalid_tool_name_error_content(tc.function.name, agent.valid_tool_names),diff --git a/agent/message_sanitization.py b/agent/message_sanitization.pyindex e68715cf394..fed524f2ae1 100644--- a/agent/message_sanitization.py+++ b/agent/message_sanitization.py@@ -493,6 +493,8 @@ __all__ = [# call_id policy owners (F4 consolidation)"deterministic_call_id","coalesce_tool_call_id",+ "tool_call_id_variants",+ "tool_result_id_variants","uniquify_tool_call_ids",# reasoning_content policy owners (F4 consolidation)"reasoning_echo_family",@@ -536,16 +538,72 @@ def deterministic_call_id(fn_name: str, arguments: str, index: int = 0) -> str:return f"call_{digest}"+def _expand_tool_id_variants(values: tuple[Any, ...]) -> frozenset[str]:+ """Return every wire spelling of one or more tool-call identifiers.++ Responses bridges may expose the pairing id and response-item id+ separately, or encode both as ``call_id|response_item_id``. The values+ are aliases for one call, not distinct calls. Keeping the expansion in+ the shared policy module prevents the repair and pre-send paths from+ drifting apart again.+ """+ variants: set[str] = set()+ for raw in values:+ if not isinstance(raw, str):+ continue+ value = raw.strip()+ if not value:+ continue+ variants.add(value)+ if "|" in value:+ for part in value.split("|"):+ part = part.strip()+ if part:+ variants.add(part)+ return frozenset(variants)+++def tool_call_id_variants(tc: Any) -> frozenset[str]:+ """Return all pairing-id variants carried by a tool-call entry."""+ if isinstance(tc, dict):+ values = (+ tc.get("call_id"),+ tc.get("id"),+ tc.get("response_item_id"),+ )+ else:+ values = (+ getattr(tc, "call_id", None),+ getattr(tc, "id", None),+ getattr(tc, "response_item_id", None),+ )+ return _expand_tool_id_variants(values)+++def tool_result_id_variants(tool_call_id: Any) -> frozenset[str]:+ """Return all matching variants for a role=tool ``tool_call_id``."""+ return _expand_tool_id_variants((tool_call_id,))++def coalesce_tool_call_id(tc: Any) -> str:"""Extract the effective call ID from a tool_call entry (dict or object).- Single owner for the ``call_id or id`` coalescing rule: Codex Responses- tool calls carry ``call_id`` (authoritative pairing key), Chat- Completions ones carry ``id`` only. Returns ``""`` when neither is set.+ Single owner for the canonical pairing rule: Codex Responses tool calls+ carry ``call_id`` (authoritative pairing key), Chat Completions ones carry+ ``id`` only, and bridge ids may encode ``call_id|response_item_id``.+ Returns ``""`` when neither pairing field is set."""if isinstance(tc, dict):- return (tc.get("call_id", "") or tc.get("id", "") or "").strip()- return (getattr(tc, "call_id", "") or getattr(tc, "id", "") or "").strip()+ values = (tc.get("call_id"), tc.get("id"))+ else:+ values = (getattr(tc, "call_id", None), getattr(tc, "id", None))+ for raw in values:+ if not isinstance(raw, str):+ continue+ value = raw.strip()+ if value:+ return value.split("|", 1)[0].strip() or value+ return ""def uniquify_tool_call_ids(tool_calls: list) -> list:diff --git a/agent/tool_dispatch_helpers.py b/agent/tool_dispatch_helpers.pyindex 0c4259b6565..70a04b82303 100644--- a/agent/tool_dispatch_helpers.py+++ b/agent/tool_dispatch_helpers.py@@ -531,6 +531,13 @@ def _trajectory_normalize_msg(msg: Dict[str, Any]) -> Dict[str, Any]:return msg+def _normalize_tool_call_id(tool_call_id: Any) -> Any:+ """Normalize a composite bridge id to its canonical call-id half."""+ if isinstance(tool_call_id, str) and "|" in tool_call_id:+ return tool_call_id.split("|", 1)[0].strip()+ return tool_call_id++def make_tool_result_message(name: str,content: Any,@@ -557,6 +564,10 @@ def make_tool_result_message(The outer list itself is rebuilt rather than returned by identity, socallers should compare by value, not by ``is``."""+ # Keep the constructor safe for every caller, including replay recovery+ # paths that do not go through the live executor's canonical-id helper.+ tool_call_id = _normalize_tool_call_id(tool_call_id)+# Order matters: detect provider-side elision on the RAW content and# append the notice first, THEN wrap — so the notice lives inside the# untrusted block next to the data it describes, appended exactly oncediff --git a/agent/tool_executor.py b/agent/tool_executor.pyindex b01a9dc47ed..1209749e473 100644--- a/agent/tool_executor.py+++ b/agent/tool_executor.py@@ -32,6 +32,7 @@ from agent.display import (redact_tool_args_for_display as _redact_tool_args_for_display,_detect_tool_failure,)+from agent.message_sanitization import coalesce_tool_call_idfrom agent.tool_dispatch_helpers import (_NEVER_PARALLEL_TOOLS,_is_destructive_command,@@ -55,6 +56,11 @@ from tools.budget_config import BudgetConfig, DEFAULT_BUDGET, budget_for_contextlogger = logging.getLogger(__name__)+def _pairing_tool_call_id(tool_call: Any) -> str:+ """Return the canonical id used by the persisted assistant message."""+ return coalesce_tool_call_id(tool_call)++def _record_persisted_path_for_stub(agent, tool_call_id: str, function_result) -> None:"""Tell the stall guards where a persisted result's full content lives.@@ -1100,10 +1106,11 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effef"[Tool execution cancelled — {tc.function.name} was skipped ""due to user interrupt]")+ tool_call_id = _pairing_tool_call_id(tc)messages.append(make_tool_result_message(tc.function.name,cancelled_result,- tc.id,+ tool_call_id,effect_disposition="none",))_emit_terminal_post_tool_call(@@ -1112,7 +1119,7 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effefunction_args={},result=cancelled_result,effective_task_id=effective_task_id,- tool_call_id=getattr(tc, "id", "") or "",+ tool_call_id=tool_call_id,status="cancelled",error_type="user_interrupt",error_message="Tool execution skipped due to user interrupt",@@ -1322,6 +1329,7 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effe# ContextVars are propagated by propagate_context_to_thread() at the# submit site below (GHSA-qg5c-hvr5-hjgr, #13617).start = time.time()+ tool_call_id = _pairing_tool_call_id(tool_call)blocked = Falsedispatched = Falsestart_advanced = False@@ -1351,7 +1359,7 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effefunction_name,next_args,effective_task_id,- tool_call.id,+ tool_call_id,messages=messages,pre_tool_block_checked=True,skip_tool_request_middleware=True,@@ -1364,7 +1372,7 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effefunction_name=function_name,function_args=function_args,effective_task_id=effective_task_id,- tool_call_id=getattr(tool_call, "id", "") or "",+ tool_call_id=tool_call_id,execute=_execute,scope_block=scope_block,display_index=index + 1,@@ -1398,7 +1406,7 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effefunction_name=function_name,function_args=function_args,effective_task_id=effective_task_id,- tool_call_id=getattr(tool_call, "id", "") or "",+ tool_call_id=tool_call_id,start_time=start,middleware_trace=list(middleware_trace),)@@ -1425,7 +1433,7 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effefunction_args=function_args,result=result,effective_task_id=effective_task_id,- tool_call_id=getattr(tool_call, "id", "") or "",+ tool_call_id=tool_call_id,duration_ms=int(duration * 1000),middleware_trace=list(middleware_trace),)@@ -1676,6 +1684,7 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effeparsed_calls):r = results[i]+ tool_call_id = _pairing_tool_call_id(tc)blocked = Falseis_error = Trueprogress_function_name = name@@ -1694,7 +1703,7 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effefunction_args=args,result=function_result,effective_task_id=effective_task_id,- tool_call_id=getattr(tc, "id", "") or "",+ tool_call_id=tool_call_id,duration_ms=int((timeout_s or 0.0) * 1000),status="timeout",error_type="tool_timeout",@@ -1712,7 +1721,7 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effefunction_args=args,result=function_result,effective_task_id=effective_task_id,- tool_call_id=getattr(tc, "id", "") or "",+ tool_call_id=tool_call_id,status="cancelled",error_type="keyboard_interrupt",error_message="Tool execution cancelled by user interrupt",@@ -1726,7 +1735,7 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effefunction_args=args,result=function_result,effective_task_id=effective_task_id,- tool_call_id=getattr(tc, "id", "") or "",+ tool_call_id=tool_call_id,status="error",error_type="thread_missing_result",error_message=function_result,@@ -1745,7 +1754,7 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effefunction_args=function_args,result=function_result,effective_task_id=effective_task_id,- tool_call_id=getattr(tc, "id", "") or "",+ tool_call_id=tool_call_id,status="error",error_type="invalid_tool_arguments",error_message="Tool arguments must be a valid JSON object",@@ -1760,7 +1769,7 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effefunction_args,function_result,failed=is_error,- tool_call_id=getattr(tc, "id", "") or "",+ tool_call_id=tool_call_id,)if is_error:@@ -1791,11 +1800,11 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effefunction_result = maybe_persist_tool_result(content=function_result,tool_name=name,- tool_use_id=tc.id,+ tool_use_id=tool_call_id,env=get_active_env(effective_task_id),config=_tool_budget,) if not _is_multimodal_tool_result(function_result) else function_result- _record_persisted_path_for_stub(agent, tc.id, function_result)+ _record_persisted_path_for_stub(agent, tool_call_id, function_result)subdir_hints = agent._subdirectory_hints.check_tool_call(name, args)if subdir_hints:@@ -1818,7 +1827,7 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effetool_message = make_tool_result_message(name,_tool_content,- tc.id,+ tool_call_id,effect_disposition=effect_disposition,)messages.append(tool_message)@@ -1862,7 +1871,7 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effetry:display_args = _redact_tool_args_for_display(name, args) or argsagent.tool_complete_callback(- tc.id, name, display_args, display_function_result,+ tool_call_id, name, display_args, display_function_result,)except Exception as cb_err:logging.debug("Tool complete callback error: %s", cb_err)@@ -1878,7 +1887,7 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effename,None,None,- tool_call_id=tc.id,+ tool_call_id=tool_call_id,risk_metadata=risk_metadata,)except Exception as cb_err:@@ -1917,7 +1926,7 @@ def _append_cancelled_tool_results(messages: list, tool_calls, *, reason: str) -messages.append(make_tool_result_message(name,f"[Tool execution cancelled — {name} was skipped due to {reason}]",- getattr(tc, "id", "") or "",+ _pairing_tool_call_id(tc),effect_disposition="none",))@@ -1938,6 +1947,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effereturn _run_sequential_tool_execution_middleware(agent, **kwargs)for i, tool_call in enumerate(assistant_message.tool_calls, 1):+ tool_call_id = _pairing_tool_call_id(tool_call)if getattr(agent, "_incremental_persistence_failed", False):return# SAFETY: check interrupt BEFORE starting each tool.@@ -1956,7 +1966,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effemessages.append(make_tool_result_message(skipped_name,cancelled_result,- skipped_tc.id,+ _pairing_tool_call_id(skipped_tc),effect_disposition="none",))_emit_terminal_post_tool_call(@@ -1990,7 +2000,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_args=function_args,result=malformed_args_result,effective_task_id=effective_task_id,- tool_call_id=getattr(tool_call, "id", "") or "",+ tool_call_id=tool_call_id,status="error",error_type="invalid_tool_arguments",error_message="Tool arguments must be a valid JSON object",@@ -1999,7 +2009,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effemake_tool_result_message(function_name,malformed_args_result,- tool_call.id,+ tool_call_id,))if not _flush_session_db_after_tool_progress(@@ -2066,7 +2076,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_name=function_name,function_args=function_args,effective_task_id=effective_task_id,- tool_call_id=getattr(tool_call, "id", "") or "",+ tool_call_id=tool_call_id,execute=_execute,scope_block=_ts_scope_block,display_index=i,@@ -2091,7 +2101,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_name=function_name,function_args=function_args,effective_task_id=effective_task_id,- tool_call_id=getattr(tool_call, "id", "") or "",+ tool_call_id=tool_call_id,execute=_execute,scope_block=_ts_scope_block,display_index=i,@@ -2123,7 +2133,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_name=function_name,function_args=function_args,effective_task_id=effective_task_id,- tool_call_id=getattr(tool_call, "id", "") or "",+ tool_call_id=tool_call_id,execute=_execute,scope_block=_ts_scope_block,display_index=i,@@ -2153,7 +2163,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effenext_args,build_metadata=lambda: agent._build_memory_write_metadata(task_id=effective_task_id,- tool_call_id=getattr(tool_call, "id", None),+ tool_call_id=tool_call_id,),)return result@@ -2162,7 +2172,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_name=function_name,function_args=function_args,effective_task_id=effective_task_id,- tool_call_id=getattr(tool_call, "id", "") or "",+ tool_call_id=tool_call_id,execute=_execute,scope_block=_ts_scope_block,display_index=i,@@ -2185,7 +2195,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_name=function_name,function_args=function_args,effective_task_id=effective_task_id,- tool_call_id=getattr(tool_call, "id", "") or "",+ tool_call_id=tool_call_id,execute=_execute,scope_block=_ts_scope_block,display_index=i,@@ -2206,7 +2216,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_name=function_name,function_args=function_args,effective_task_id=effective_task_id,- tool_call_id=getattr(tool_call, "id", "") or "",+ tool_call_id=tool_call_id,execute=_execute,scope_block=_ts_scope_block,display_index=i,@@ -2227,7 +2237,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_name=function_name,function_args=function_args,effective_task_id=effective_task_id,- tool_call_id=getattr(tool_call, "id", "") or "",+ tool_call_id=tool_call_id,execute=_execute,scope_block=_ts_scope_block,display_index=i,@@ -2255,7 +2265,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_name=function_name,function_args=function_args,effective_task_id=effective_task_id,- tool_call_id=getattr(tool_call, "id", "") or "",+ tool_call_id=tool_call_id,execute=_execute,scope_block=_ts_scope_block,display_index=i,@@ -2278,7 +2288,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_name=function_name,function_args=function_args,effective_task_id=effective_task_id,- tool_call_id=getattr(tool_call, "id", "") or "",+ tool_call_id=tool_call_id,execute=_execute,scope_block=_ts_scope_block,display_index=i,@@ -2297,7 +2307,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_name=function_name,function_args=function_args,effective_task_id=effective_task_id,- tool_call_id=getattr(tool_call, "id", "") or "",+ tool_call_id=tool_call_id,execute=_execute,scope_block=_ts_scope_block,display_index=i,@@ -2324,7 +2334,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_name=function_name,function_args=function_args,effective_task_id=effective_task_id,- tool_call_id=getattr(tool_call, "id", "") or "",+ tool_call_id=tool_call_id,execute=_execute,scope_block=_ts_scope_block,display_index=i,@@ -2383,7 +2393,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_name=function_name,function_args=function_args,effective_task_id=effective_task_id,- tool_call_id=getattr(tool_call, "id", "") or "",+ tool_call_id=tool_call_id,execute=_execute,scope_block=_ts_scope_block,display_index=i,@@ -2416,7 +2426,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_name=function_name,function_args=function_args,effective_task_id=effective_task_id,- tool_call_id=getattr(tool_call, "id", "") or "",+ tool_call_id=tool_call_id,execute=_execute,scope_block=_ts_scope_block,display_index=i,@@ -2452,7 +2462,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_name=function_name,function_args=function_args,effective_task_id=effective_task_id,- tool_call_id=getattr(tool_call, "id", "") or "",+ tool_call_id=tool_call_id,execute=_execute,scope_block=_ts_scope_block,display_index=i,@@ -2487,7 +2497,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_name,next_args,effective_task_id,- tool_call_id=tool_call.id,+ tool_call_id=tool_call_id,session_id=agent.session_id or "",turn_id=getattr(agent, "_current_turn_id", "") or "",api_request_id=getattr(agent, "_current_api_request_id", "")@@ -2517,7 +2527,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_name=function_name,function_args=function_args,effective_task_id=effective_task_id,- tool_call_id=getattr(tool_call, "id", "") or "",+ tool_call_id=tool_call_id,execute=_execute,scope_block=_ts_scope_block,display_index=i,@@ -2531,7 +2541,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_name=function_name,function_args=function_args,effective_task_id=effective_task_id,- tool_call_id=getattr(tool_call, "id", "") or "",+ tool_call_id=tool_call_id,start_time=tool_start_time,middleware_trace=list(middleware_trace),)@@ -2569,7 +2579,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_name,next_args,effective_task_id,- tool_call_id=tool_call.id,+ tool_call_id=tool_call_id,session_id=agent.session_id or "",turn_id=getattr(agent, "_current_turn_id", "") or "",api_request_id=getattr(agent, "_current_api_request_id", "")@@ -2599,7 +2609,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_name=function_name,function_args=function_args,effective_task_id=effective_task_id,- tool_call_id=getattr(tool_call, "id", "") or "",+ tool_call_id=tool_call_id,execute=_execute,scope_block=_ts_scope_block,display_index=i,@@ -2612,7 +2622,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_name=function_name,function_args=function_args,effective_task_id=effective_task_id,- tool_call_id=getattr(tool_call, "id", "") or "",+ tool_call_id=tool_call_id,start_time=tool_start_time,middleware_trace=list(middleware_trace),)@@ -2667,7 +2677,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_args=function_args,result=function_result,effective_task_id=effective_task_id,- tool_call_id=getattr(tool_call, "id", "") or "",+ tool_call_id=tool_call_id,duration_ms=int(tool_duration * 1000),middleware_trace=list(middleware_trace),)@@ -2677,7 +2687,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_args,function_result,failed=_is_error_result,- tool_call_id=getattr(tool_call, "id", "") or "",+ tool_call_id=tool_call_id,)result_preview = function_result if agent.verbose_logging else (function_result[:200] if len(function_result) > 200 else function_result@@ -2712,11 +2722,11 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_result = maybe_persist_tool_result(content=function_result,tool_name=function_name,- tool_use_id=tool_call.id,+ tool_use_id=tool_call_id,env=get_active_env(effective_task_id),config=_tool_budget,) if not _is_multimodal_tool_result(function_result) else function_result- _record_persisted_path_for_stub(agent, tool_call.id, function_result)+ _record_persisted_path_for_stub(agent, tool_call_id, function_result)# Discover subdirectory context files from tool argumentssubdir_hints = agent._subdirectory_hints.check_tool_call(function_name, function_args)@@ -2732,7 +2742,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effetool_message = make_tool_result_message(function_name,_tool_content,- tool_call.id,+ tool_call_id,effect_disposition="unknown" if _execution_timed_out else None,)messages.append(tool_message)@@ -2763,7 +2773,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effeor function_args)agent.tool_complete_callback(- tool_call.id,+ tool_call_id,function_name,display_args,display_function_result,@@ -2782,7 +2792,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_name,None,None,- tool_call_id=tool_call.id,+ tool_call_id=tool_call_id,risk_metadata=risk_metadata,)except Exception as cb_err:@@ -2805,7 +2815,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effemessages.append(make_tool_result_message(skipped_name,f"[Tool execution skipped — {skipped_name} was not started. User sent a new message]",- skipped_tc.id,+ _pairing_tool_call_id(skipped_tc),effect_disposition="none",))if not _flush_session_db_after_tool_progress(diff --git a/tests/agent/test_tool_dispatch_helpers.py b/tests/agent/test_tool_dispatch_helpers.pyindex c56c362d369..223730d45b0 100644--- a/tests/agent/test_tool_dispatch_helpers.py+++ b/tests/agent/test_tool_dispatch_helpers.py@@ -142,6 +142,11 @@ class TestMakeToolResultMessage:assert msg["timestamp"] == 123.5+ def test_composite_tool_call_id_is_normalized_at_constructor_boundary(self):+ msg = make_tool_result_message("terminal", "ok", "call_abc|fc_def")++ assert msg["tool_call_id"] == "call_abc"+def test_high_risk_message_content_wrapped(self):msg = make_tool_result_message("web_extract", SAMPLE_LONG_TEXT, "call_2")assert msg["role"] == "tool"diff --git a/tests/run_agent/test_message_sequence_repair.py b/tests/run_agent/test_message_sequence_repair.pyindex 461e9104874..690e57f6b90 100644--- a/tests/run_agent/test_message_sequence_repair.py+++ b/tests/run_agent/test_message_sequence_repair.py@@ -169,6 +169,166 @@ def test_repair_keeps_tool_matching_only_call_id():+def test_repair_keeps_tool_result_keyed_by_response_item_id():+ """The normalized call id must still pair the raw Responses item id."""+ from agent.agent_runtime_helpers import repair_message_sequence++ messages = [+ {"role": "user", "content": "do it"},+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [{+ "id": "call_ABC",+ "call_id": "call_ABC",+ "response_item_id": "fc_123",+ "type": "function",+ "function": {"name": "x", "arguments": "{}"},+ }],+ },+ {"role": "tool", "tool_call_id": "fc_123", "content": "result"},+ ]++ repairs = repair_message_sequence(_bare_agent(), messages)++ assert repairs == 0+ assert messages[-1]["content"] == "result"+++def test_coalesce_tool_call_id_uses_call_half_of_composite_id():+ """Raw bridge ids must use their canonical call half for tool results."""+ from agent.message_sanitization import coalesce_tool_call_id++ assert coalesce_tool_call_id({"id": "call_ABC|fc_123"}) == "call_ABC"+++def test_sanitize_keeps_parallel_results_keyed_by_responses_id_variant():+ """A valid parallel Responses batch must not become all unavailable stubs.++ Responses/Codex calls can expose a response-item ``id`` (``fc_*``) and a+ distinct pairing ``call_id`` (``call_*``). The execution path may key the+ real result with either variant, but the pre-send sanitizer must recognize+ both as the same assistant call. This is the minimal reproduction of the+ reported all-results loss for a larger parallel batch.+ """+ from agent.agent_runtime_helpers import sanitize_api_messages++ batch_size = 8+ messages = [+ {"role": "user", "content": "run the independent calls"},+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": f"fc_{i}",+ "call_id": f"call_{i}",+ "type": "function",+ "function": {"name": "read_file", "arguments": "{}"},+ }+ for i in range(batch_size)+ ],+ },+ *[+ {+ "role": "tool",+ "tool_call_id": f"fc_{i}",+ "content": f"real-result-{i}",+ }+ for i in range(batch_size)+ ],+ ]++ out = sanitize_api_messages(messages)++ results = [msg for msg in out if msg.get("role") == "tool"]+ assert [msg["tool_call_id"] for msg in results] == [+ f"fc_{i}" for i in range(batch_size)+ ]+ assert [msg["content"] for msg in results] == [+ f"real-result-{i}" for i in range(batch_size)+ ]+++def test_repair_keeps_two_parallel_calls_answered_by_mixed_variants():+ """Consuming one alias group must not orphan a different parallel call."""+ from agent.agent_runtime_helpers import repair_message_sequence++ messages = [+ {"role": "user", "content": "do both"},+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": "call_1",+ "call_id": "call_1",+ "response_item_id": "fc_1",+ "type": "function",+ "function": {"name": "x", "arguments": "{}"},+ },+ {+ "id": "call_2",+ "call_id": "call_2",+ "response_item_id": "fc_2",+ "type": "function",+ "function": {"name": "y", "arguments": "{}"},+ },+ ],+ },+ {"role": "tool", "tool_call_id": "call_1", "content": "r1"},+ {"role": "tool", "tool_call_id": "fc_2", "content": "r2"},+ ]++ repairs = repair_message_sequence(_bare_agent(), messages)++ assert repairs == 0+ assert [m["content"] for m in messages if m.get("role") == "tool"] == [+ "r1", "r2"+ ]+++def test_sanitize_consumes_all_responses_id_variants_for_duplicate_result():+ """A sibling-id replay must not replace the first real result."""+ from agent.agent_runtime_helpers import sanitize_api_messages++ messages = [+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [{+ "id": "call_ABC",+ "call_id": "call_ABC",+ "response_item_id": "fc_123",+ "type": "function",+ "function": {"name": "x", "arguments": "{}"},+ }],+ },+ {"role": "tool", "tool_call_id": "fc_123", "content": "real"},+ {"role": "tool", "tool_call_id": "call_ABC", "content": "replayed"},+ ]++ out = sanitize_api_messages(messages)++ assert [msg["content"] for msg in out if msg.get("role") == "tool"] == [+ "real"+ ]+++def test_tool_executor_uses_canonical_responses_pairing_id():+ """The executor must emit the id used by the normalized assistant turn."""+ from types import SimpleNamespace++ from agent.tool_executor import _pairing_tool_call_id++ assert _pairing_tool_call_id(+ SimpleNamespace(id="fc_123", call_id="call_ABC")+ ) == "call_ABC"+ assert _pairing_tool_call_id(+ SimpleNamespace(id="call_ABC|fc_123")+ ) == "call_ABC"++# ── repair_message_sequence_with_cursor (#44837) ───────────────────────────from agent.agent_runtime_helpers import repair_message_sequence_with_cursor