The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(terminal): run heredocs and trailing-backslash commands without the PIPESTATUS capture
Teknium812c4bb04498
diff --git a/tests/tools/test_terminal_pipeline_status.py b/tests/tools/test_terminal_pipeline_status.pyindex c236869cb6e..980fd6d948d 100644--- a/tests/tools/test_terminal_pipeline_status.py+++ b/tests/tools/test_terminal_pipeline_status.py@@ -4,22 +4,24 @@ import subprocessimport pytest-from tools.environments.base_session_env import _wrap_command_script+from tools.environments.base_session_env import _split_cwd_marker, _wrap_command_scriptCWD_MARKER = "__HERMES_CWD_test__"PIPE_MARKER = "__HERMES_PIPE_test__"-def _script(command: str) -> str:+def _script(command: str, pipe_marker: str = PIPE_MARKER) -> str:return _wrap_command_script(command, quoted_cwd="/tmp", quoted_snap="/nonexistent-snapshot",snap_tmp_template="/tmp/hermes-snap.XXXXXX", passthrough_names=(),- snapshot_ready=False, cwd_marker=CWD_MARKER, pipe_marker=PIPE_MARKER,+ snapshot_ready=False, cwd_marker=CWD_MARKER, pipe_marker=pipe_marker,)-def _run_result(command: str) -> subprocess.CompletedProcess:- return subprocess.run(["bash", "-c", _script(command)], capture_output=True, text=True, check=False)+def _run_result(command: str, pipe_marker: str = PIPE_MARKER) -> subprocess.CompletedProcess:+ return subprocess.run(+ ["bash", "-c", _script(command, pipe_marker)], capture_output=True, text=True, check=False,+ )def _run(command: str) -> str:@@ -38,33 +40,34 @@ def test_plain_command_reports_one_status():assert f"{PIPE_MARKER}1{PIPE_MARKER}" in output+def _seen(result: subprocess.CompletedProcess) -> tuple[int, str, str]:+ """Exit code and output as the model sees them, markers stripped like production does."""+ stdout = result.stdout+ for marker in (PIPE_MARKER, CWD_MARKER):+ split = _split_cwd_marker(stdout, marker)+ stdout = split[1] if split else stdout+ return result.returncode, stdout, result.stderr++@pytest.mark.parametrize(- ("command", "expected"),+ ("command", "exit_code", "stdout"),[- ("if false; then echo yes; fi", 0),- ("while read line; do echo \"$line\"; done < /dev/null", 0),- ("set -o pipefail; false | true", 1),- ("! false", 0),- ("! true", 1),- ("echo 'unbalanced", 2),- ("echo hi \\", 0),- ("exit 3", 3),+ ("if false; then echo yes; fi", 0, ""),+ ("while read line; do echo \"$line\"; done < /dev/null", 0, ""),+ ("set -o pipefail; false | true", 1, ""),+ ("! false", 0, ""),+ ("! true", 1, ""),+ ("echo 'unbalanced", 2, ""),+ ('echo "unbalanced', 2, ""),+ ("echo $(echo unclosed", 2, ""),+ ("echo hi \\", 0, "hi \\\n"),+ ("cat <<'EOF'\nunterminated heredoc", 0, "unterminated heredoc\n"),+ ("exit 3", 3, ""),],)-def test_wrapper_preserves_shell_exit_code(command, expected):- """``PIPESTATUS`` is side data: the wrapper must return the shell's own ``$?``."""- assert _run_result(command).returncode == expected---def test_wrapper_does_not_leak_internals_on_syntax_error():- result = _run_result("echo 'unbalanced")-- assert "__hermes_ps" not in result.stderr---def test_wrapper_does_not_leak_internals_after_a_trailing_backslash():- result = _run_result("echo hi \\")+def test_capturing_pipestatus_changes_nothing_the_model_sees(command, exit_code, stdout):+ """The capture is side data: the shell's own ``$?`` and output, no wrapper text."""+ seen_code, seen_stdout, seen_stderr = _seen(_run_result(command))- assert result.returncode == 0- assert "__hermes_ps" not in result.stdout- assert "__hermes_ps" not in result.stderr+ assert (seen_code, seen_stdout) == (exit_code, stdout)+ assert "__hermes" not in seen_stderrdiff --git a/tools/environments/base_session_env.py b/tools/environments/base_session_env.pyindex 57d2785931d..1eed1d58bc2 100644--- a/tools/environments/base_session_env.py+++ b/tools/environments/base_session_env.py@@ -55,6 +55,23 @@ def _pipe_marker_printf(marker: str) -> str:return f"printf '\\n{marker}%s{marker}\\n' \"${{__hermes_ps[*]-}}\""+def _eval_capturing_pipestatus(escaped: str) -> str:+ """``eval`` the command and keep its last pipeline's ``PIPESTATUS`` as side data.++ The array must be read inside the same ``eval`` (afterwards it holds only ``eval``'s+ status), while ``$?`` stays the exit code: the two differ for ``!``, ``if``/``while``,+ ``pipefail`` and parse errors. The blank line stops the capture joining a command+ continued by a trailing backslash.+ """+ return f"eval '{escaped}\n\n__hermes_rc=$? __hermes_ps=(\"${{PIPESTATUS[@]}}\"); (exit $__hermes_rc)'"+++def _can_capture_pipestatus(command: str) -> bool:+ """An unterminated heredoc would read the capture line as its body (into the user's+ file), and a trailing ``\\`` would join onto it: such commands run unchanged."""+ return "<<" not in command and not command.endswith("\\")++def _cwd_marker_printf(marker: str) -> str:"""Emit the CWD marker on its own line (leading ``\\n`` guards against acommand whose output lacks a trailing newline; ``_split_cwd_marker`` strips it)."""@@ -159,6 +176,7 @@ def _wrap_command_script(changing the command's umask."""escaped = command.replace("'", "'\\''")+ capture = bool(pipe_marker) and _can_capture_pipestatus(command)save, restore = _passthrough_save_restore(passthrough_names)parts = list(save)if snapshot_ready:@@ -169,7 +187,7 @@ def _wrap_command_script('export GIT_PAGER="${GIT_PAGER:-cat}" PAGER="${PAGER:-cat}"',# ``--`` keeps hyphen-prefixed directory names from being parsed as options.f"builtin cd -- {quoted_cwd} || exit 126",- f"eval '{escaped}\n\n__hermes_rc=$? __hermes_ps=(\"${{PIPESTATUS[@]}}\"); (exit $__hermes_rc)'",+ _eval_capturing_pipestatus(escaped) if capture else f"eval '{escaped}'","__hermes_ec=$?","umask 077"]if snapshot_ready and persist_env:@@ -178,7 +196,7 @@ def _wrap_command_script(f"{{ {_export_dump_excluding_session_vars(_SNAP_TMP, passthrough_names)} "f"&& mv -f {_SNAP_TMP} {quoted_snap}; }} "f"2>/dev/null || rm -f {_SNAP_TMP} 2>/dev/null || true")- if pipe_marker:+ if capture:parts.append(_pipe_marker_printf(pipe_marker))parts += [_cwd_marker_printf(cwd_marker), "exit $__hermes_ec"]return "\n".join(parts)