Skip to content

Commit e80737c

Browse files
fix: escape terminal controls in result diagnostics (#5219)
* fix: escape terminal controls in result diagnostics * fix: escape result controls before line splitting
1 parent 0da7889 commit e80737c

2 files changed

Lines changed: 86 additions & 2 deletions

File tree

‎src/agents/util/_pretty_print.py‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import re
12
from typing import TYPE_CHECKING
23

34
from pydantic import BaseModel
@@ -8,10 +9,17 @@
89

910

1011
def _indent(text: str, indent_level: int) -> str:
12+
# Normalize ordinary CRLF breaks before escaping controls that splitlines consumes.
13+
text = _escape_terminal_controls(text.replace("\r\n", "\n"))
1114
indent_string = " " * indent_level
1215
return "\n".join(f"{indent_string}{line}" for line in text.splitlines())
1316

1417

18+
def _escape_terminal_controls(text: str) -> str:
19+
"""Escape C0, DEL, and C1 controls, preserving tabs and diagnostic line breaks."""
20+
return re.sub(r"[\x00-\x08\x0b-\x1f\x7f-\x9f]", lambda m: f"\\x{ord(m[0]):02x}", text)
21+
22+
1523
def _final_output_str(result: "RunResultBase") -> str:
1624
if result.final_output is None:
1725
return "None"
@@ -36,7 +44,7 @@ def pretty_print_result(result: "RunResult") -> str:
3644
output += f"\n- {len(result.output_guardrail_results)} output guardrail result(s)"
3745
output += "\n(See `RunResult` for more details)"
3846

39-
return output
47+
return _escape_terminal_controls(output)
4048

4149

4250
def pretty_print_run_error_details(result: "RunErrorDetails") -> str:
@@ -68,4 +76,4 @@ def pretty_print_run_result_streaming(result: "RunResultStreaming") -> str:
6876
output += f"\n- {len(result.input_guardrail_results)} input guardrail result(s)"
6977
output += f"\n- {len(result.output_guardrail_results)} output guardrail result(s)"
7078
output += "\n(See `RunResultStreaming` for more details)"
71-
return output
79+
return _escape_terminal_controls(output)

‎tests/test_pretty_print.py‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import json
2+
from dataclasses import dataclass
23

34
import pytest
45
from inline_snapshot import snapshot
@@ -120,6 +121,81 @@ class Foo(BaseModel):
120121
bar: str
121122

122123

124+
@dataclass
125+
class TextOutput:
126+
text: str
127+
128+
def __str__(self) -> str:
129+
return self.text
130+
131+
132+
@pytest.mark.asyncio
133+
@pytest.mark.parametrize("streaming", [False, True])
134+
@pytest.mark.parametrize("output_kind", ["text", "model", "dataclass"])
135+
async def test_result_str_escapes_terminal_controls(streaming, output_kind):
136+
payload = (
137+
"Hello\x1b[2J\x1b]0;title\x07\x08\x00\x7f\x9b31m\x9d0;title\x9c\x0b\x0c\x1c\x1d\x1e\x85"
138+
)
139+
escaped = (
140+
r"Hello\x1b[2J\x1b]0;title\x07\x08\x00\x7f\x9b31m\x9d0;title\x9c\x0b\x0c\x1c\x1d\x1e\x85"
141+
)
142+
model = ScriptedModel()
143+
if output_kind == "model":
144+
output_type = Foo
145+
response = Foo(bar=payload).model_dump_json()
146+
elif output_kind == "dataclass":
147+
output_type = TextOutput
148+
response = json.dumps({_WRAPPER_DICT_KEY: {"text": payload}})
149+
else:
150+
output_type = None
151+
response = payload
152+
model.enqueue([get_text_message(response)])
153+
agent = Agent(name="agent\x1b[2J\x9b31m", model=model, output_type=output_type)
154+
155+
if streaming:
156+
result = Runner.run_streamed(agent, input="Hello")
157+
async for _ in result.stream_events():
158+
pass
159+
else:
160+
result = await Runner.run(agent, input="Hello")
161+
162+
rendered = str(result)
163+
assert r'Agent(name="agent\x1b[2J\x9b31m", ...)' in rendered
164+
if output_kind == "model":
165+
assert result.final_output.bar == payload
166+
# JSON already escapes C0 controls; the diagnostic printer must also escape C1.
167+
assert r"\u001b[2J" in rendered
168+
assert r"\x9b31m\x9d0;title\x9c" in rendered
169+
assert r"\x85" in rendered
170+
elif output_kind == "dataclass":
171+
assert result.final_output.text == payload
172+
assert escaped in rendered
173+
else:
174+
assert result.final_output == payload
175+
assert escaped in rendered
176+
assert agent.name == "agent\x1b[2J\x9b31m"
177+
assert all(char >= " " or char in "\n\t" for char in rendered)
178+
assert not any("\x7f" <= char <= "\x9f" for char in rendered)
179+
180+
181+
@pytest.mark.asyncio
182+
@pytest.mark.parametrize("streaming", [False, True])
183+
async def test_result_str_preserves_readable_multiline_output(streaming):
184+
payload = "Hello, 世界 👋\r\n\tCafé\n\nlast line"
185+
model = ScriptedModel()
186+
model.enqueue([get_text_message(payload)])
187+
agent = Agent(name="test_agent", model=model)
188+
if streaming:
189+
result = Runner.run_streamed(agent, input="Hello")
190+
async for _ in result.stream_events():
191+
pass
192+
else:
193+
result = await Runner.run(agent, input="Hello")
194+
195+
assert " Hello, 世界 👋\n \tCafé\n \n last line\n- 1 new item(s)" in str(result)
196+
assert result.final_output == payload
197+
198+
123199
@pytest.mark.asyncio
124200
async def test_pretty_run_result_structured_output():
125201
model = ScriptedModel()

0 commit comments

Comments
 (0)