Skip to content

The agent that grows with you

perf(agent): skip surrogate regex for ASCII text

Riccardo Vecchi36c2f05a0017
diff --git a/agent/message_sanitization.py b/agent/message_sanitization.py
index 48bd81cb55d..294937fbc91 100644
--- a/agent/message_sanitization.py
+++ b/agent/message_sanitization.py
@@ -28,6 +28,10 @@ _MESSAGE_CORE_KEYS = frozenset({"content", "name", "tool_calls", "role"})
def _sanitize_surrogates(text: str) -> str:
"""Replace lone surrogate code points with U+FFFD; no-op when none present."""
+ # ``str.isascii`` is an O(1) flag check; surrogates are never ASCII, so the
+ # regex scan only runs for the (rare) non-ASCII leaf.
+ if text.isascii():
+ return text
return _SURROGATE_RE.sub('\ufffd', text)
@@ -52,6 +56,8 @@ def coerce_tool_name(name: Any, fallback: str = "invalid_tool_call") -> str:
def _strip_non_ascii(text: str) -> str:
"""Drop non-ASCII characters — last resort for ASCII-only system encodings (LANG=C)."""
+ if text.isascii():
+ return text
return text.encode('ascii', errors='ignore').decode('ascii')