diff --git a/nanobot/agent/tools/exec_session.py b/nanobot/agent/tools/exec_session.py index 28452de79..3ecb45275 100644 --- a/nanobot/agent/tools/exec_session.py +++ b/nanobot/agent/tools/exec_session.py @@ -27,6 +27,7 @@ from nanobot.agent.tools.schema import ( tool_parameters_schema, ) from nanobot.agent.tools.shell_config import ExecToolConfig +from nanobot.agent.tools.shell_output import ShellOutputFilter DEFAULT_YIELD_MS = 1000 MAX_YIELD_MS = 30_000 @@ -175,9 +176,10 @@ class _ExecSession: if stream is None: return decoder = codecs.getincrementaldecoder("utf-8")(errors="replace") + output_filter = ShellOutputFilter() while True: chunk = await stream.read(4096) - text = decoder.decode(chunk, final=not chunk) + text = output_filter.feed(decoder.decode(chunk, final=not chunk)) async with self._lock: buffer.append(text) if not chunk: diff --git a/nanobot/agent/tools/shell.py b/nanobot/agent/tools/shell.py index 04f5683ad..cad8ad738 100644 --- a/nanobot/agent/tools/shell.py +++ b/nanobot/agent/tools/shell.py @@ -38,6 +38,7 @@ from nanobot.agent.tools.schema import ( tool_parameters_schema, ) from nanobot.agent.tools.shell_config import ExecToolConfig +from nanobot.agent.tools.shell_output import ShellOutputFilter from nanobot.config.paths import get_media_dir from nanobot.security.workspace_access import current_scope_allows_loopback, current_tool_workspace from nanobot.security.workspace_policy import is_path_within @@ -309,13 +310,13 @@ class ExecTool(Tool): output_parts: list[str] = [] - if stdout: - output_parts.append(stdout.decode("utf-8", errors="replace")) + stdout_text = ShellOutputFilter().feed(stdout.decode("utf-8", errors="replace")) + if stdout_text: + output_parts.append(stdout_text) - if stderr: - stderr_text = stderr.decode("utf-8", errors="replace") - if stderr_text.strip(): - output_parts.append(f"STDERR:\n{stderr_text}") + stderr_text = ShellOutputFilter().feed(stderr.decode("utf-8", errors="replace")) + if stderr_text.strip(): + output_parts.append(f"STDERR:\n{stderr_text}") output_parts.append(f"\nExit code: {process.returncode}") diff --git a/nanobot/agent/tools/shell_output.py b/nanobot/agent/tools/shell_output.py new file mode 100644 index 000000000..a4a759d90 --- /dev/null +++ b/nanobot/agent/tools/shell_output.py @@ -0,0 +1,51 @@ +"""Terminal control filtering for shell tool output.""" + +from __future__ import annotations + + +class ShellOutputFilter: + """Strip terminal escapes, preserving visible text and whitespace. + + Use one instance per decoded stdout/stderr stream so escape sequences can + span reads. Only parser state is retained, never control-string payloads. + """ + + def __init__(self) -> None: + self._state = "text" + self._string_escape = False + + def feed(self, text: str) -> str: + if self._state == "text" and "\x1b" not in text: + return text + + output: list[str] = [] + for char in text: + if self._state in ("osc", "string"): + if (self._string_escape and char == "\\") or ( + self._state == "osc" and char == "\x07" + ): + self._state = "text" + self._string_escape = char == "\x1b" + elif char == "\x1b": + self._state = "escape" + elif self._state in ("escape", "intermediate"): + if self._state == "escape" and char == "[": + self._state = "csi" + elif self._state == "escape" and char in "]PX^_": + self._state = "osc" if char == "]" else "string" + self._string_escape = False + elif " " <= char <= "/": + self._state = "intermediate" + else: + self._state = "text" + if not "0" <= char <= "~": + output.append(char) + elif self._state == "csi": + if "@" <= char <= "~": + self._state = "text" + elif not " " <= char <= "?": + self._state = "text" + output.append(char) + else: + output.append(char) + return "".join(output) diff --git a/tests/tools/test_shell_output.py b/tests/tools/test_shell_output.py new file mode 100644 index 000000000..7c1955992 --- /dev/null +++ b/tests/tools/test_shell_output.py @@ -0,0 +1,106 @@ +"""Plain-text output through shell tools and streaming filters.""" + +from __future__ import annotations + +import re +import sys + +import pytest + +from nanobot.agent.tools.exec_session import ExecSessionManager, ExecSessionTool +from nanobot.agent.tools.shell import ExecTool +from nanobot.agent.tools.shell_output import ShellOutputFilter + + +@pytest.mark.parametrize("chunk_size", [1, 4096]) +def test_filter_preserves_text_and_layout_across_terminal_sequences(chunk_size): + source = ( + "\x1b]0;Weather report\x07" + "北京\t\x1b[1;38;5;190m+21\x1b[0m °C\r\n" + "│ Morning │ Noon │\n" + "\x1b[?25l\x1b[2K" + "\x1b]8;;https://example.com\x1b\\forecast\x1b]8;;\x1b\\\n" + "\x1b(B\x1b_Gimage payload\x1b\\" + " 🙂\n\n" + r"literal \x1b[31m and \u001b[0m" + ) + expected = ( + "北京\t+21 °C\r\n" + "│ Morning │ Noon │\n" + "forecast\n" + " 🙂\n\n" + r"literal \x1b[31m and \u001b[0m" + ) + output_filter = ShellOutputFilter() + + result = "".join( + output_filter.feed(source[start:start + chunk_size]) + for start in range(0, len(source), chunk_size) + ) + + assert result == expected + + +@pytest.mark.parametrize("yield_time_ms", [None, 1000]) +async def test_exec_filters_before_output_limits_and_preserves_status(tmp_path, yield_time_ms): + manager = ExecSessionManager() + tool = ExecTool(working_dir=str(tmp_path), timeout=10, session_manager=manager) + session_tool = ExecSessionTool(manager=manager) + visible = "北京\t+21 °C\n│ Morning │ Noon │\n" + stderr = "\x1b[31mwarning: haze\x1b[0m\n" + command = [ + sys.executable, "-X", "utf8", "-c", + "import sys; " + f"sys.stdout.write('\\x1b[38;5;190m' * 5000 + {visible!r} + '\\x1b[0m'); " + f"sys.stderr.write({stderr!r}); sys.exit(7)", + ] + try: + result = await tool.execute( + command=command, yield_time_ms=yield_time_ms, max_output_chars=1000, + ) + session = re.search(r"session_id: ([0-9a-f]+)", result) + if session: + result += await session_tool.execute(session_id=session.group(1), until_exit=True) + + assert visible in result.replace("\r\n", "\n") + assert "STDERR:\nwarning: haze" in result + assert "Exit code: 7" in result + assert "\x1b" not in result + assert "truncated" not in result + finally: + await manager.close_all() + + +async def test_exec_session_filters_split_sequences_and_waits_for_visible_text(tmp_path): + manager = ExecSessionManager() + tool = ExecTool(working_dir=str(tmp_path), timeout=10, session_manager=manager) + session_tool = ExecSessionTool(manager=manager) + command = [ + sys.executable, "-u", "-c", + "import sys; " + "sys.stdout.write('before\\x1b[38;5;'); sys.stdout.flush(); " + "sys.stderr.write('\\x1b[31mwarning\\x1b[0m\\n'); sys.stderr.flush(); " + "sys.stdin.readline(); " + "sys.stdout.write('190mr\\x1b[1meady\\x1b[0m\\n'); sys.stdout.flush(); " + "sys.stdin.readline()", + ] + try: + initial = await tool.execute(command=command, yield_time_ms=1000) + session = re.search(r"session_id: ([0-9a-f]+)", initial) + assert session, initial + session_id = session.group(1) + ready = await session_tool.execute(session_id=session_id, input="\n", wait_for="ready") + final = await session_tool.execute(session_id=session_id, input="\n", until_exit=True) + + assert "ready" in ready + assert "Wait target not observed" not in ready + assert "Process running." in ready + assert "Exit code: 0" in final + combined = initial + ready + final + assert "before" in combined + assert "STDERR:\nwarning" in combined + assert "\x1b" not in combined + assert "38;5;" not in combined + assert "190m" not in combined + finally: + await manager.close_all()