From 7a67c2edafdd5a1dd0d561fa21d9d60f00cfb147 Mon Sep 17 00:00:00 2001 From: Justin Beckwith Date: Mon, 28 Sep 2026 08:39:10 -0700 Subject: [PATCH 1/2] fix: escape terminal controls in result diagnostics --- src/agents/util/_pretty_print.py | 10 ++++- tests/test_pretty_print.py | 71 ++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+), 2 deletions(-) diff --git a/src/agents/util/_pretty_print.py b/src/agents/util/_pretty_print.py index 4c869f3a84..ff82908c17 100644 --- a/src/agents/util/_pretty_print.py +++ b/src/agents/util/_pretty_print.py @@ -1,3 +1,4 @@ +import re from typing import TYPE_CHECKING from pydantic import BaseModel @@ -12,6 +13,11 @@ def _indent(text: str, indent_level: int) -> str: return "\n".join(f"{indent_string}{line}" for line in text.splitlines()) +def _escape_terminal_controls(text: str) -> str: + """Escape C0, DEL, and C1 controls, preserving tabs and diagnostic line breaks.""" + return re.sub(r"[\x00-\x08\x0b-\x1f\x7f-\x9f]", lambda m: f"\\x{ord(m[0]):02x}", text) + + def _final_output_str(result: "RunResultBase") -> str: if result.final_output is None: return "None" @@ -36,7 +42,7 @@ def pretty_print_result(result: "RunResult") -> str: output += f"\n- {len(result.output_guardrail_results)} output guardrail result(s)" output += "\n(See `RunResult` for more details)" - return output + return _escape_terminal_controls(output) def pretty_print_run_error_details(result: "RunErrorDetails") -> str: @@ -68,4 +74,4 @@ def pretty_print_run_result_streaming(result: "RunResultStreaming") -> str: output += f"\n- {len(result.input_guardrail_results)} input guardrail result(s)" output += f"\n- {len(result.output_guardrail_results)} output guardrail result(s)" output += "\n(See `RunResultStreaming` for more details)" - return output + return _escape_terminal_controls(output) diff --git a/tests/test_pretty_print.py b/tests/test_pretty_print.py index cc2df86a98..290185c07a 100644 --- a/tests/test_pretty_print.py +++ b/tests/test_pretty_print.py @@ -1,4 +1,5 @@ import json +from dataclasses import dataclass import pytest from inline_snapshot import snapshot @@ -120,6 +121,76 @@ class Foo(BaseModel): bar: str +@dataclass +class TextOutput: + text: str + + def __str__(self) -> str: + return self.text + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streaming", [False, True]) +@pytest.mark.parametrize("output_kind", ["text", "model", "dataclass"]) +async def test_result_str_escapes_terminal_controls(streaming, output_kind): + payload = "Hello\x1b[2J\x1b]0;title\x07\x08\x00\x7f\x9b31m\x9d0;title\x9c" + escaped = r"Hello\x1b[2J\x1b]0;title\x07\x08\x00\x7f\x9b31m\x9d0;title\x9c" + model = ScriptedModel() + if output_kind == "model": + output_type = Foo + response = Foo(bar=payload).model_dump_json() + elif output_kind == "dataclass": + output_type = TextOutput + response = json.dumps({_WRAPPER_DICT_KEY: {"text": payload}}) + else: + output_type = None + response = payload + model.enqueue([get_text_message(response)]) + agent = Agent(name="agent\x1b[2J\x9b31m", model=model, output_type=output_type) + + if streaming: + result = Runner.run_streamed(agent, input="Hello") + async for _ in result.stream_events(): + pass + else: + result = await Runner.run(agent, input="Hello") + + rendered = str(result) + assert r'Agent(name="agent\x1b[2J\x9b31m", ...)' in rendered + if output_kind == "model": + assert result.final_output.bar == payload + # JSON already escapes C0 controls; the diagnostic printer must also escape C1. + assert r"\u001b[2J" in rendered + assert r"\x9b31m\x9d0;title\x9c" in rendered + elif output_kind == "dataclass": + assert result.final_output.text == payload + assert escaped in rendered + else: + assert result.final_output == payload + assert escaped in rendered + assert agent.name == "agent\x1b[2J\x9b31m" + assert all(char >= " " or char in "\n\t" for char in rendered) + assert not any("\x7f" <= char <= "\x9f" for char in rendered) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streaming", [False, True]) +async def test_result_str_preserves_readable_multiline_output(streaming): + payload = "Hello, 世界 👋\r\n\tCafé\n\nlast line" + model = ScriptedModel() + model.enqueue([get_text_message(payload)]) + agent = Agent(name="test_agent", model=model) + if streaming: + result = Runner.run_streamed(agent, input="Hello") + async for _ in result.stream_events(): + pass + else: + result = await Runner.run(agent, input="Hello") + + assert " Hello, 世界 👋\n \tCafé\n \n last line\n- 1 new item(s)" in str(result) + assert result.final_output == payload + + @pytest.mark.asyncio async def test_pretty_run_result_structured_output(): model = ScriptedModel() From a860f9a5358b276eee378b332e702ae97b5a6394 Mon Sep 17 00:00:00 2001 From: Justin Beckwith Date: Mon, 28 Sep 2026 09:13:49 -0700 Subject: [PATCH 2/2] fix: escape result controls before line splitting --- src/agents/util/_pretty_print.py | 2 ++ tests/test_pretty_print.py | 9 +++++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/agents/util/_pretty_print.py b/src/agents/util/_pretty_print.py index ff82908c17..5760aaad1f 100644 --- a/src/agents/util/_pretty_print.py +++ b/src/agents/util/_pretty_print.py @@ -9,6 +9,8 @@ def _indent(text: str, indent_level: int) -> str: + # Normalize ordinary CRLF breaks before escaping controls that splitlines consumes. + text = _escape_terminal_controls(text.replace("\r\n", "\n")) indent_string = " " * indent_level return "\n".join(f"{indent_string}{line}" for line in text.splitlines()) diff --git a/tests/test_pretty_print.py b/tests/test_pretty_print.py index 290185c07a..012314fb28 100644 --- a/tests/test_pretty_print.py +++ b/tests/test_pretty_print.py @@ -133,8 +133,12 @@ def __str__(self) -> str: @pytest.mark.parametrize("streaming", [False, True]) @pytest.mark.parametrize("output_kind", ["text", "model", "dataclass"]) async def test_result_str_escapes_terminal_controls(streaming, output_kind): - payload = "Hello\x1b[2J\x1b]0;title\x07\x08\x00\x7f\x9b31m\x9d0;title\x9c" - escaped = r"Hello\x1b[2J\x1b]0;title\x07\x08\x00\x7f\x9b31m\x9d0;title\x9c" + payload = ( + "Hello\x1b[2J\x1b]0;title\x07\x08\x00\x7f\x9b31m\x9d0;title\x9c\x0b\x0c\x1c\x1d\x1e\x85" + ) + escaped = ( + r"Hello\x1b[2J\x1b]0;title\x07\x08\x00\x7f\x9b31m\x9d0;title\x9c\x0b\x0c\x1c\x1d\x1e\x85" + ) model = ScriptedModel() if output_kind == "model": output_type = Foo @@ -162,6 +166,7 @@ async def test_result_str_escapes_terminal_controls(streaming, output_kind): # JSON already escapes C0 controls; the diagnostic printer must also escape C1. assert r"\u001b[2J" in rendered assert r"\x9b31m\x9d0;title\x9c" in rendered + assert r"\x85" in rendered elif output_kind == "dataclass": assert result.final_output.text == payload assert escaped in rendered