The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent): collapse sanitizer field walks and cache-marker counting (pass 4)
Tekniumc629274efc05
diff --git a/agent/message_sanitization.py b/agent/message_sanitization.pyindex 93c2c859cc5..d5e2b847cdf 100644--- a/agent/message_sanitization.py+++ b/agent/message_sanitization.py@@ -80,25 +80,22 @@ def _sanitize_messages(messages: list, fix: Callable[[str], str], *, deep: bool)if not isinstance(msg, dict):continuecontent = msg.get("content")- if isinstance(content, str):- found |= _fix_str_field(msg, "content", fix)- elif isinstance(content, list):+ if isinstance(content, list):for part in content:if isinstance(part, dict):found |= _fix_str_field(part, "text", fix)+ else:+ found |= _fix_str_field(msg, "content", fix)found |= _fix_str_field(msg, "name", fix)tool_calls = msg.get("tool_calls")- if isinstance(tool_calls, list):- for tc in tool_calls:- if not isinstance(tc, dict):- continue- if deep:- found |= _fix_str_field(tc, "id", fix)- fn = tc.get("function")- if isinstance(fn, dict):- if deep:- found |= _fix_str_field(fn, "name", fix)- found |= _fix_str_field(fn, "arguments", fix)+ for tc in tool_calls if isinstance(tool_calls, list) else ():+ if not isinstance(tc, dict):+ continue+ fn = tc.get("function")+ fn_fields = [(fn, "name"), (fn, "arguments")] if isinstance(fn, dict) else []+ for container, key in [(tc, "id")] + fn_fields:+ if deep or key == "arguments":+ found |= _fix_str_field(container, key, fix)for key, value in list(msg.items()):if key in _MESSAGE_CORE_KEYS:continue@@ -140,20 +137,15 @@ def _escape_invalid_chars_in_json_strings(raw: str) -> str:out: list[str] = []in_string = Falsei = 0- n = len(raw)- while i < n:+ while i < len(raw):ch = raw[i]- if in_string and ch == "\\" and i + 1 < n:+ if in_string and ch == "\\" and i + 1 < len(raw):out.append(raw[i:i + 2])i += 2continueif ch == '"':in_string = not in_string- out.append(ch)- elif in_string and ord(ch) < 0x20:- out.append(f"\\u{ord(ch):04x}")- else:- out.append(ch)+ out.append(f"\\u{ord(ch):04x}" if in_string and ord(ch) < 0x20 else ch)i += 1return "".join(out)diff --git a/agent/prompt_caching.py b/agent/prompt_caching.pyindex 8398d6543d0..e4c41b4a1a3 100644--- a/agent/prompt_caching.py+++ b/agent/prompt_caching.py@@ -202,36 +202,26 @@ def strip_anthropic_cache_control(api_messages: List[Dict[str, Any]]) -> List[Dicontent = msg.get("content")if not isinstance(content, list):continue+ role = msg.get("role")# The skill split is the only decoration marking the FIRST part of a user message,# so the shape alone identifies it even after the prefix registry evicted the entry.skill_split_shape = (- msg.get("role") == "user"- and len(content) == 2- and isinstance(content[0], dict)- and isinstance(content[1], dict)- and "cache_control" in content[0]- and "cache_control" not in content[1]+ role == "user" and len(content) == 2+ and all(isinstance(p, dict) for p in content)+ and "cache_control" in content[0] and "cache_control" not in content[1])if _has_part_marker(content):- content = [+ content = msg["content"] = [{k: v for k, v in part.items() if k != "cache_control"}- if isinstance(part, dict) and "cache_control" in part- else part+ if isinstance(part, dict) and "cache_control" in part else partfor part in content]- msg["content"] = content- decoration_shape = content and all(- isinstance(part, dict)- and part.get("type", "text") == "text"- and isinstance(part.get("text"), str)- and set(part.keys()) <= {"type", "text"}+ plain_text_parts = content and all(+ isinstance(part, dict) and part.get("type", "text") == "text"+ and isinstance(part.get("text"), str) and set(part.keys()) <= {"type", "text"}for part in content- ) and (- len(content) == 1- or (msg.get("role") == "system" and len(content) == 2)- or skill_split_shape)- if decoration_shape:+ if plain_text_parts and (len(content) == 1 or (role == "system" and len(content) == 2) or skill_split_shape):msg["content"] = "".join(part["text"] for part in content)return api_messages@@ -247,16 +237,11 @@ def strip_anthropic_tool_cache_control(tools: List[Dict[str, Any]] | None) -> Lidef _count_cache_markers(messages: List[Dict[str, Any]], tools: List[Dict[str, Any]]) -> int:"""Count the wire-visible cache markers in a request-local plan."""- count = 0- for message in messages:- if not isinstance(message, dict):- continue- count += "cache_control" in message- if isinstance(message.get("content"), list):- count += sum(- 1 for part in message["content"] if isinstance(part, dict) and "cache_control" in part- )- return count + sum(1 for tool in tools if isinstance(tool, dict) and "cache_control" in tool)+ def _marked(items: Any) -> int:+ return sum(1 for item in items if isinstance(item, dict) and "cache_control" in item)++ parts = [p for m in messages if isinstance(m, dict) and isinstance(m.get("content"), list) for p in m["content"]]+ return _marked(messages) + _marked(parts) + _marked(tools)def _completed_transaction_endpoint_indexes(messages: List[Dict[str, Any]], *, native_anthropic: bool) -> List[int]:@@ -264,10 +249,7 @@ def _completed_transaction_endpoint_indexes(messages: List[Dict[str, Any]], *, ndef _tool_run_end(start: int) -> int:end = start- while end < len(messages):- result = messages[end]- if not isinstance(result, dict) or result.get("role") != "tool":- break+ while end < len(messages) and isinstance(messages[end], dict) and messages[end].get("role") == "tool":end += 1return end