The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): stop empty-transcript sanitizer from warning on every send (#96870)
HexLab9820fd5d0b25b2
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex 58cc307fff8..c4018d20afb 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -3856,6 +3856,13 @@ def _tool_call_id_variants(tc: Any) -> set:# consistently whether the empty turn was caught at write time or send time._INTERRUPTED_PLACEHOLDER = "[response interrupted]"+# Repeated heals of the same poisoned transcript used to WARNING on every+# send (#96870). Escalate once per session window, then stay quiet.+_EMPTY_HEAL_ESCALATE_AFTER = 5+_EMPTY_HEAL_WINDOW_S = 600.0+_empty_heal_log_state: Dict[str, Dict[str, Any]] = {}+_empty_heal_log_lock = threading.Lock()+def _msg_has_payload(msg: Dict[str, Any]) -> bool:"""True if ``msg`` carries anything the API treats as non-empty content.@@ -3905,6 +3912,80 @@ def _msg_has_payload(msg: Dict[str, Any]) -> bool:return False+def fill_empty_non_final_wire_payload(+ msg: Dict[str, Any], *, is_final: bool+) -> bool:+ """Write the interrupted placeholder onto an empty non-final wire copy.++ Used by the send-time projection so ``repair_empty_non_final_messages``+ does not re-heal the same row on every call (#88955 hidden placeholders,+ #96870 stream-death / host-fed empties). Pass the per-call copy only —+ durable history must not be mutated. Returns True when *msg* was filled.+ """+ if is_final or not isinstance(msg, dict):+ return False+ if msg.get("role") not in ("user", "assistant"):+ return False+ if _msg_has_payload(msg):+ return False+ msg["content"] = _INTERRUPTED_PLACEHOLDER+ return True+++def _session_id_for_heal_log() -> str:+ try:+ from hermes_logging import _session_context++ return str(getattr(_session_context, "session_id", None) or "")+ except Exception:+ return ""+++def _log_empty_non_final_heal(healed: int) -> None:+ """WARNING on the first heals in a window; one ERROR at the threshold.++ Further heals in the same session window stay silent so a poisoned+ transcript cannot flood ``errors.log`` (dozens of identical WARNINGs+ per hour with no user-visible signal — #96870).+ """+ key = _session_id_for_heal_log() or "-"+ now = time.monotonic()+ with _empty_heal_log_lock:+ state = _empty_heal_log_state.get(key)+ if state is None or (now - state["window_start"]) > _EMPTY_HEAL_WINDOW_S:+ state = {"count": 0, "window_start": now, "escalated": False}+ _empty_heal_log_state[key] = state+ state["count"] += 1+ count = state["count"]+ if count >= _EMPTY_HEAL_ESCALATE_AFTER and not state["escalated"]:+ state["escalated"] = True+ level = "error"+ elif state["escalated"]:+ level = "silent"+ else:+ level = "warning"++ if level == "silent":+ return+ if level == "error":+ _ra().logger.error(+ "Pre-call sanitizer: healed %d empty non-final message(s) "+ "(%d heals in this session window). The transcript is being "+ "repaired on every send; /new drops the poisoned turns.",+ healed,+ count,+ )+ return+ _ra().logger.warning(+ "Pre-call sanitizer: healed %d empty non-final message(s) by "+ "substituting placeholder content — an empty-content turn was in "+ "the transcript and would 400 the request ('messages must have "+ "non-empty content' / INVALID_REQUEST_BODY). Self-recovering the "+ "poisoned transcript in memory; no restart needed.",+ healed,+ )++def repair_empty_non_final_messages(messages: List[Dict[str, Any]],) -> List[Dict[str, Any]]:@@ -3961,14 +4042,7 @@ def repair_empty_non_final_messages(repaired.append(msg)if healed:- _ra().logger.warning(- "Pre-call sanitizer: healed %d empty non-final message(s) by "- "substituting placeholder content — an empty-content turn was in "- "the transcript and would 400 the request ('messages must have "- "non-empty content' / INVALID_REQUEST_BODY). Self-recovering the "- "poisoned transcript in memory; no restart needed.",- healed,- )+ _log_empty_non_final_heal(healed)return repairedreturn messagesdiff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex 4158e973040..7cb1346f387 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -2323,7 +2323,10 @@ def run_conversation(# repair_message_sequence_with_cursor also recomputes the SessionDB# flush cursor (_last_flushed_db_idx) when repair compacts the list,# so the turn-end flush doesn't skip the assistant/tool chain (#44837).- from agent.agent_runtime_helpers import repair_message_sequence_with_cursor+ from agent.agent_runtime_helpers import (+ fill_empty_non_final_wire_payload,+ repair_message_sequence_with_cursor,+ )repaired_seq = repair_message_sequence_with_cursor(agent, messages)if repaired_seq > 0:request_logger.info(@@ -2353,29 +2356,9 @@ def run_conversation(# from every outgoing copy so strict OpenAI-compatible backends# don't reject the request after a model switch or resumed typed# event row enters the live history.- _display_kind = api_msg.pop("display_kind", None)+ api_msg.pop("display_kind", None)api_msg.pop("display_metadata", None)- # Legacy hidden redirect placeholders (#88955): rows persisted- # BEFORE the writer-side api_content stamp in- # _apply_active_turn_redirect are content="" with no sidecar.- # Once display_kind is stripped the pre-call sanitizer- # (repair_empty_non_final_messages) would re-heal such a row on- # every call forever, since the durable transcript is never- # mutated. Give the wire copy the same neutral payload here so- # old sessions converge too. Never the interrupt scaffold —- # replaying scaffold bytes as assistant text is #81841.- if (- _display_kind == "hidden"- and api_msg.get("role") == "assistant"- and not _api_content- and not (api_msg.get("content") or "").strip()- and not api_msg.get("tool_calls")- ):- from agent.agent_runtime_helpers import _INTERRUPTED_PLACEHOLDER-- api_msg["content"] = _INTERRUPTED_PLACEHOLDER-# Durable row identity stamped by _rows_to_conversation so the# desktop can address a specific persisted message (reactions).# Bookkeeping, never a provider field — only the chat-completions@@ -2432,6 +2415,16 @@ def run_conversation(# Remove finish_reason - not accepted by strict APIs (e.g. Mistral)if "finish_reason" in api_msg:api_msg.pop("finish_reason")+ # Empty non-final user/assistant turns (#88955 hidden placeholders+ # and #96870 stream-death / host-fed empties): once display_kind+ # and api_content are stripped, the pre-call sanitizer would+ # re-heal the wire copy on every send and flood errors.log.+ # Fill the WIRE copy here so the sanitizer has nothing to do.+ # Durable history is not mutated. After reasoning copy so a+ # thinking-only turn keeps its payload and is not rewritten.+ fill_empty_non_final_wire_payload(+ api_msg, is_final=(idx == len(messages) - 1)+ )# _thinking_prefill survives here intentionally: the drop pass below# needs it. The transport strips all underscore keys before the wire.# Strip length-continuation marks; not every transport drops underscore keys.