agent-zero icon indicating copy to clipboard operation
agent-zero copied to clipboard

DirtyJson decodes \uXXXX surrogate pairs as lone surrogates, crashing tool execution with UnicodeEncodeError

Open King0James0 opened this issue 4 months ago • 2 comments

Describe the bug

helpers/dirty_json.py decodes each \uXXXX escape independently (chr(int(unicode_char, 16))) with no UTF-16 surrogate-pair combining. Every tool envelope is parsed through this path (extract_tools.json_parse_dirty -> DirtyJson.parse_string; strict json.loads is never tried first), so whenever a model writes an emoji or any non-BMP character in its legal JSON escape form — e.g. \ud83c\udf78 for U+1F378 — the parsed Python string contains two lone surrogate code points instead of one character.

Python strings tolerate lone surrogates, but UTF-8 does not. The poisoned string then raises at the first .encode("utf-8") downstream:

  • code_execution_tool -> tty_session.send -> data.encode(self.encoding) fails with UnicodeEncodeError: 'utf-8' codec can't encode characters in position N-N+1: surrogates not allowed, surfacing as the red "Critical error occurred, retrying..." and a wasted loop iteration;
  • the same poison crashes print_style HTML log writes — #1384 reported this exact traceback and was closed stale; the surrogates come from the parse, not from the log writer.

The error is intermittent from the user's point of view because it only fires when the model happens to escape-encode the emoji rather than emit it as literal UTF-8, which makes it look like a flaky infrastructure problem.

Reproduction

from helpers.dirty_json import DirtyJson

payload = '{"tool_name": "code_execution_tool", "tool_args": {"code": "print(\\ud83c\\udf78)"}}'
parsed = DirtyJson.parse_string(payload)
code = parsed["tool_args"]["code"]
print([hex(ord(c)) for c in code if 0xD800 <= ord(c) <= 0xDFFF])  # ['0xd83c', '0xdf78']
code.encode("utf-8")  # UnicodeEncodeError: surrogates not allowed

json.loads on the same payload returns one U+1F378 character and encodes fine.

Expected behavior

Surrogate-pair escapes decode to the real character (matching json.loads), and the parser never emits a string that cannot be UTF-8-encoded.

Fix

PR incoming: combine high+low surrogate escape pairs into the real code point; replace any remaining unpaired surrogate with U+FFFD so the parsed string is always encodable. BMP escapes and invalid-hex handling unchanged.

King0James0 avatar Jul 16 '26 22:07 King0James0

The DirtyJson → lone-surrogate class (#1773) also crashes a second, independent site that #1774 (which fixes the source) will not catch on its own, because the poisoned string can already be persisted in chat history / re-materialized at parse time:

Site: plugins/_context_window/helpers/usage.py → _cached_tokens()

# before
 digest = hashlib.sha256(text.encode("utf-8")).hexdigest()

text here is history.output_text(...) — the joined chat history. If any message in history contains a lone surrogate (e.g. \uDDFA), prompt preparation dies with:

agent.py:422 monologue -> prepare_prompt
  plugins/_context_window/.../prepare_prompt/end/_90_store_context_usage.py -> usage.finalize()
    usage._output_tokens -> usage._cached_tokens
      hashlib.sha256(text.encode("utf-8"))
UnicodeEncodeError: 'utf-8' codec can't encode character '\uddfa' in position 179856: surrogates not allowed

This is a hard crash of the entire turn (worse than the tool-execution retry in #1773), and it happens even when the model being called is healthy — it is purely the history-text encode.

Repro (model-free):

text = "normal " + chr(0xDDFA) + " trailing"  # valid JSON lone-escape, json.loads yields the same
import hashlib; hashlib.sha256(text.encode("utf-8"))  # UnicodeEncodeError

Proposed defensive fix (hash site):

def _safe_text(text: str) -> str:
    try:
        text.encode("utf-8")
        return text
    except UnicodeEncodeError:
        return text.encode("utf-8", errors="surrogatepass").decode("utf-8", errors="replace")

# in _cached_tokens:
    text = _safe_text(text)
    digest = hashlib.sha256(text.encode("utf-8")).hexdigest()

This keeps valid text byte-identical (fast path, token cache unaffected) and neutralizes lone surrogates for both the digest and the token count.

Why both fixes matter: #1774 stops new lone surrogates at the parse source. This site should still be robust because (a) older/persisted history may already contain them, and (b) a hash/telemetry helper should never be able to kill a turn. Recommend merging the _context_window guard alongside #1774.

Environment: Agent Zero v2.11, Docker, bundled _context_window plugin.

nico7master avatar Sep 15 '26 16:09 nico7master

Fixed in #1992, which is now merged into ready. It fixes the character decoding that caused these errors.

3clyp50 avatar Nov 10 '26 16:11 3clyp50