The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): coerce invalid stored tool-call names on every outbound request
teknium17154ac036ce3
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex 3df039c99dd..479409312df 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -17,7 +17,7 @@ from pathlib import Pathfrom typing import Any, Dict, List, Optional, Tuplefrom hermes_cli.timeouts import get_provider_request_timeoutfrom agent.message_sanitization import (- _FULL_ARGS_LOG_BOUND, coalesce_tool_call_id, tool_call_id_variants, tool_result_id_variants+ _FULL_ARGS_LOG_BOUND, coalesce_tool_call_id, coerce_tool_name, tool_call_id_variants, tool_result_id_variants)from agent.prompt_builder import STEER_DISPLAY_KIND, steer_user_rowfrom agent.tool_dispatch_helpers import _trajectory_normalize_msg, make_tool_result_message@@ -2684,34 +2684,40 @@ def _drop_empty_tool_calls_arrays(messages: List[Dict[str, Any]]) -> List[Dict[sreturn normalized-def _repair_nameless_tool_calls(messages: List[Dict[str, Any]]) -> None:- """Rename empty/missing ``function.name`` to a sentinel (in place): dropping would unpair the- anti-priming result the dispatch loop keeps for empty-name calls, and Responses adapters- 400 on nameless calls."""- sentinel = "invalid_tool_call"+def _repair_invalid_tool_call_names(messages: List[Dict[str, Any]]) -> None:+ """Coerce every ``function.name`` to the provider-safe ``^[A-Za-z0-9_-]{1,64}$``. An empty/missing+ name becomes the ``invalid_tool_call`` sentinel (dropping would unpair the anti-priming result the+ dispatch loop keeps for it); an invalid one (``multi_tool_use.parallel``, a shell command a weak+ fallback model put in ``name``) is coerced deterministically, because one such stored turn 400s+ every later request on a strict endpoint and pins the session to the fallback model (#51944).+ Dict tool calls are rewritten copy-on-write so a shallow per-call copy never edits persisted+ history; tool results follow via ``_realign_tool_result_names``."""for msg in messages:if msg.get("role") != "assistant":continue- for tc in msg.get("tool_calls") or []:+ tcs = msg.get("tool_calls") or []+ for idx, tc in enumerate(tcs):if isinstance(tc, dict):fn = tc.get("function")name = fn.get("name") if isinstance(fn, dict) else getattr(fn, "name", None)else:fn = getattr(tc, "function", None)name = getattr(fn, "name", None) if fn else None- if isinstance(name, str) and name.strip():+ coerced = coerce_tool_name(name)+ if coerced == name:continue_ra().logger.warning(- "Pre-call sanitizer: repairing tool_call with empty function.name -> %r (id=%s)",- sentinel, _ra().AIAgent._get_tool_call_id_static(tc),+ "Pre-call sanitizer: repairing tool_call with invalid function.name %r -> %r (id=%s)",+ (name or "")[:80], coerced, _ra().AIAgent._get_tool_call_id_static(tc),)- if isinstance(fn, dict):- fn["name"] = sentinel+ if isinstance(tc, dict):+ if tcs is msg.get("tool_calls"):+ tcs = msg["tool_calls"] = list(tcs)+ fn = {**fn, "name": coerced} if isinstance(fn, dict) else {"name": coerced, "arguments": "{}"}+ tcs[idx] = {**tc, "function": fn}elif fn is not None and hasattr(fn, "name"):with contextlib.suppress(Exception):- fn.name = sentinel- elif isinstance(tc, dict):- tc["function"] = {"name": sentinel, "arguments": "{}"}+ fn.name = coerceddef _drop_results_without_ids(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:@@ -2932,7 +2938,7 @@ def sanitize_api_messages(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]messages = _drop_invalid_roles(messages)messages = repair_empty_non_final_messages(messages)messages = _drop_empty_tool_calls_arrays(messages)- _repair_nameless_tool_calls(messages)+ _repair_invalid_tool_call_names(messages)messages = _drop_results_without_ids(messages)messages = _pair_tool_calls_positionally(messages)messages = _dedupe_tool_call_ids(messages)diff --git a/agent/codex_responses_adapter.py b/agent/codex_responses_adapter.pyindex 9f259f12aad..7ee92bf3c97 100644--- a/agent/codex_responses_adapter.py+++ b/agent/codex_responses_adapter.py@@ -12,7 +12,7 @@ import uuidfrom types import SimpleNamespacefrom typing import Any, Callable, Dict, Iterator, List, NamedTuple, Optional, TypeGuard-from agent.message_sanitization import deterministic_call_id+from agent.message_sanitization import coerce_tool_name, deterministic_call_idfrom agent.prompt_builder import DEFAULT_AGENT_IDENTITYfrom hermes_cli.route_identity import normalize_route_base_url@@ -102,7 +102,6 @@ _RESPONSE_MESSAGE_STATUSES = {"completed", "incomplete", "in_progress"}# input[].id / function names longer than this are a non-retryable 400 ("string too# long"). Codex message ids can run 400+ chars; Hermes ``msg_...`` ids stay under the cap._MAX_RESPONSES_ITEM_ID_LENGTH = 64-_VALID_RESPONSES_FN_NAME_RE = re.compile(r"[a-zA-Z0-9_-]{1,64}")# Provider-executed built-in tools: declared by ``type`` alone, run server-side,# reported via the ``*_call`` output items below; preflight passes them through.@@ -288,18 +287,6 @@ def _clamp_responses_call_id(call_id: str) -> str:return f"call_{hashlib.sha256(call_id.encode('utf-8', errors='replace')).hexdigest()[:32]}"-def _sanitize_replayed_fn_name(name: str) -> str:- """Coerce a *replayed* ``function_call.name`` to ``^[a-zA-Z0-9_-]{1,64}$`` (an invalid stored- name 400s every later turn). Invalid runs collapse to ``_``; all-invalid → "fn". Apply ONLY to- replayed items, never live tool definitions (schema names must match the dispatch registry)."""- if not isinstance(name, str):- return "fn"- if _VALID_RESPONSES_FN_NAME_RE.fullmatch(name):- return name- coerced = re.sub(r"_+", "_", re.sub(r"[^A-Za-z0-9_-]", "_", name.strip())).strip("_")- return coerced[:64] or "fn"--def _canonical_call_id_from_fc(response_item_id: Any) -> Optional[str]:"""Map an ``fc_…`` item id to its canonical ``call_<suffix>``. Both sides of a replayedpair must derive the SAME call_id, or an oversized pair clamps to two surrogates."""@@ -520,7 +507,7 @@ def _replay_tool_call_items(replayed.append({"type": "function_call","call_id": wire_ids.for_call(call_id) if wire_ids else _clamp_responses_call_id(call_id),- "name": _sanitize_replayed_fn_name(fn_name), "arguments": _coerce_arguments(arguments),+ "name": coerce_tool_name(fn_name, fallback="fn"), "arguments": _coerce_arguments(arguments),})return replayed@@ -768,7 +755,7 @@ def _preflight_function_call(item: Dict[str, Any], idx: int, ctx: _PreflightCtx)if not _nonblank(name):raise ValueError(f"Codex Responses input[{idx}] function_call is missing name.")return {- "type": "function_call", "call_id": call_id.strip(), "name": _sanitize_replayed_fn_name(name),+ "type": "function_call", "call_id": call_id.strip(), "name": coerce_tool_name(name, fallback="fn"),"arguments": ctx.sanitize_text(_coerce_arguments(item.get("arguments", "{}"))),}diff --git a/agent/message_sanitization.py b/agent/message_sanitization.pyindex 4575937a368..628b048bf3a 100644--- a/agent/message_sanitization.py+++ b/agent/message_sanitization.py@@ -29,6 +29,25 @@ def _sanitize_surrogates(text: str) -> str:return _SURROGATE_RE.sub('\ufffd', text)+# OpenAI / Anthropic / Responses all bound ``function.name`` to this; one poisoned stored name+# (``multi_tool_use.parallel``, a shell command a weak model put in ``name``) 400s every later+# request on a strict endpoint (#51944).+_VALID_TOOL_NAME_RE = re.compile(r"[A-Za-z0-9_-]{1,64}")+++def coerce_tool_name(name: Any, fallback: str = "invalid_tool_call") -> str:+ """Coerce a *replayed* tool/function name to ``^[A-Za-z0-9_-]{1,64}$``. Valid names are returned+ as-is (identity — prompt-cache safe); invalid runs collapse to ``_`` and the result is cut at 64;+ empty/all-invalid → ``fallback``. Deterministic, so the same stored name always renders the same+ bytes. Never apply to live tool definitions (schema names must match the dispatch registry)."""+ if not isinstance(name, str):+ return fallback+ if _VALID_TOOL_NAME_RE.fullmatch(name):+ return name+ coerced = re.sub(r"_+", "_", re.sub(r"[^A-Za-z0-9_-]", "_", name.strip())).strip("_")+ return coerced[:64] or fallback++def _strip_non_ascii(text: str) -> str:"""Drop non-ASCII characters — last resort for ASCII-only system encodings (LANG=C)."""return text.encode('ascii', errors='ignore').decode('ascii')@@ -326,6 +345,7 @@ def _looks_like_image_content_rejection(error_body: str) -> bool:__all__ = ["_SURROGATE_RE", "close_interrupted_tool_sequence","_sanitize_surrogates", "_sanitize_structure_surrogates", "_sanitize_messages_surrogates",+ "coerce_tool_name","_escape_invalid_chars_in_json_strings", "_repair_tool_call_arguments","_strip_non_ascii", "_sanitize_messages_non_ascii", "_sanitize_tools_non_ascii","_strip_images_from_messages", "_sanitize_structure_non_ascii", "sanitize_outbound_kwargs",diff --git a/tests/agent/test_agent_guardrails.py b/tests/agent/test_agent_guardrails.pyindex e94363089f7..6dbcda3d135 100644--- a/tests/agent/test_agent_guardrails.py+++ b/tests/agent/test_agent_guardrails.py@@ -106,6 +106,22 @@ class TestSanitizeApiMessages:def test_empty_list_is_safe(self):assert AIAgent._sanitize_api_messages([]) == []+ def test_invalid_tool_call_names_coerced_copy_on_write(self):+ """Invalid stored ``function.name`` values are coerced to ``^[A-Za-z0-9_-]{1,64}$`` on the+ per-call copy only (#51944): a shallow copy of the history row — the iteration-limit summary+ path's shape — must leave the persisted dict untouched, valid names must be byte-identical+ (prompt-cache prefix), and the result's wire name follows the coerced call name."""+ stored_call = {"id": "c1", "function": {"name": "multi_tool_use.parallel", "arguments": "{}"}}+ stored = {"role": "assistant", "tool_calls": [stored_call, assistant_dict_call("c2", "terminal")]}+ out = AIAgent._sanitize_api_messages(+ [dict(stored), {**tool_result("c1"), "name": "multi_tool_use.parallel"}, tool_result("c2")]+ )+ names = [tc["function"]["name"] for tc in out[0]["tool_calls"]]+ assert names == ["multi_tool_use_parallel", "terminal"]+ assert out[0]["tool_calls"][1] is stored["tool_calls"][1]+ assert stored_call["function"]["name"] == "multi_tool_use.parallel"+ assert out[1]["name"] == "multi_tool_use_parallel"+def test_sdk_object_tool_calls(self):tc_obj = types.SimpleNamespace(id="c6", function=types.SimpleNamespace(diff --git a/tests/agent/test_codex_responses_adapter.py b/tests/agent/test_codex_responses_adapter.pyindex 95aceb80c12..390c5effd6b 100644--- a/tests/agent/test_codex_responses_adapter.py+++ b/tests/agent/test_codex_responses_adapter.py@@ -2,11 +2,11 @@ from types import SimpleNamespaceimport pytest+from agent.message_sanitization import coerce_tool_namefrom agent.codex_responses_adapter import (_chat_content_to_responses_parts,_chat_messages_to_responses_input,_classify_responses_issuer,- _sanitize_replayed_fn_name,_format_responses_error,_normalize_codex_response,_neutralize_harmony_tokens,@@ -493,27 +493,27 @@ def test_chat_messages_to_responses_input_keeps_short_call_id():assert output["call_id"] == "call_abc123"-def test_sanitize_replayed_fn_name_valid_passthrough():+def test_coerce_tool_name_valid_passthrough():"""Valid names pass through unchanged (identity — cache-prefix safe)."""for name in ("web_search", "exec-command", "a1_B2-c3", "x" * 64):- assert _sanitize_replayed_fn_name(name) == name+ assert coerce_tool_name(name) == name-def test_sanitize_replayed_fn_name_coerces_invalid_chars():- assert _sanitize_replayed_fn_name("exec.command") == "exec_command"- assert _sanitize_replayed_fn_name("run shell cmd") == "run_shell_cmd"- assert _sanitize_replayed_fn_name("weird..__name") == "weird_name"- assert _sanitize_replayed_fn_name(" tool! ") == "tool"+def test_coerce_tool_name_coerces_invalid_chars():+ assert coerce_tool_name("exec.command") == "exec_command"+ assert coerce_tool_name("run shell cmd") == "run_shell_cmd"+ assert coerce_tool_name("weird..__name") == "weird_name"+ assert coerce_tool_name(" tool! ") == "tool"-def test_sanitize_replayed_fn_name_degenerate_inputs():+def test_coerce_tool_name_degenerate_inputs():"""All-invalid / non-string names degrade to a placeholder, never empty —an empty name would trade the API 400 for a preflight ValueError."""- assert _sanitize_replayed_fn_name("") == "fn"- assert _sanitize_replayed_fn_name("...") == "fn"- assert _sanitize_replayed_fn_name("日本語") == "fn"- assert _sanitize_replayed_fn_name(None) == "fn"- assert len(_sanitize_replayed_fn_name("a." * 100)) <= 64+ assert coerce_tool_name("", fallback="fn") == "fn"+ assert coerce_tool_name("...", fallback="fn") == "fn"+ assert coerce_tool_name("日本語", fallback="fn") == "fn"+ assert coerce_tool_name(None, fallback="fn") == "fn"+ assert len(coerce_tool_name("a." * 100)) <= 64def test_chat_messages_to_responses_input_sanitizes_replayed_fn_name():diff --git a/tests/agent/test_run_agent.py b/tests/agent/test_run_agent.pyindex b020a21a458..b90e5805c4e 100644--- a/tests/agent/test_run_agent.py+++ b/tests/agent/test_run_agent.py@@ -4243,6 +4243,47 @@ class TestRunConversation:for m in replayed)+ def test_invalid_stored_tool_call_names_are_coerced_on_the_wire(self, agent):+ """A stored ``multi_tool_use.parallel`` / shell-command / empty function.name must reach the+ provider as ``^[A-Za-z0-9_-]{1,64}$`` on every request, and the persisted history must keep+ the original bytes (#51944)."""+ self._setup_agent(agent)+ long_name = 'gbrain query "x" 2>/dev/null | head -40; ' + "y" * 340+ history = [+ {"role": "user", "content": "do two things"},+ {"role": "assistant", "content": None, "tool_calls": [+ {"id": "c1", "type": "function", "function": {"name": "multi_tool_use.parallel", "arguments": "{}"}},+ {"id": "c2", "type": "function", "function": {"name": long_name, "arguments": "{}"}},+ {"id": "c3", "type": "function", "function": {"name": "", "arguments": "{}"}},+ ]},+ {"role": "tool", "tool_call_id": "c1", "name": "multi_tool_use.parallel", "content": "r1"},+ {"role": "tool", "tool_call_id": "c2", "name": long_name, "content": "r2"},+ {"role": "tool", "tool_call_id": "c3", "name": "", "content": "r3"},+ {"role": "assistant", "content": "done"},+ ]+ requests = []++ def _fake_api_call(api_kwargs):+ requests.append(api_kwargs)+ return _mock_response(content="ok", finish_reason="stop")++ with (+ patch.object(agent, "_interruptible_api_call", side_effect=_fake_api_call),+ patch.object(agent, "_persist_session"),+ patch.object(agent, "_save_trajectory"),+ patch.object(agent, "_cleanup_task_resources"),+ ):+ agent.run_conversation("continue", conversation_history=history)++ wire_names = [+ tc["function"]["name"]+ for m in requests[0]["messages"] if m.get("role") == "assistant"+ for tc in (m.get("tool_calls") or [])+ ]+ assert wire_names == ["multi_tool_use_parallel", 'gbrain_query_x_2_dev_null_head_-40_yyyyyyyyyyyyyyyyyyyyyyyyyyyyy', "invalid_tool_call"]+ assert all(len(n) <= 64 and n.replace("_", "").replace("-", "").isalnum() for n in wire_names)+ assert [tc["function"]["name"] for tc in history[1]["tool_calls"]] == ["multi_tool_use.parallel", long_name, ""]+def test_nous_401_refreshes_after_remint_and_retries(self, agent):self._setup_agent(agent)agent.provider = "nous"