The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(environments): surface stdin write failures as stdin_error (#79178)
Theophilus Chinomonab0594118ab10
diff --git a/tests/tools/test_file_write_surrogate_roundtrip.py b/tests/tools/test_file_write_surrogate_roundtrip.pyindex 4d267e91ef7..52e36821c75 100644--- a/tests/tools/test_file_write_surrogate_roundtrip.py+++ b/tests/tools/test_file_write_surrogate_roundtrip.py@@ -8,10 +8,14 @@ tasks in this plan append propagation and write_file tests to this file."""import shleximport subprocess+import time+from unittest.mock import MagicMockimport pytestfrom tools.environments.base import _pipe_stdin+from tools.environments.local import LocalEnvironment+from tools.file_operations import ShellFileOperationsdef _cat_to_file_proc(out_path):@@ -77,3 +81,72 @@ class TestPipeStdinSurrogates:assert proc.returncode == 0assert out.read_bytes() == b"hello\nworld\n"assert proc._hermes_stdin_errors == []+++def env(tmp_path):+ """A real LocalEnvironment rooted in a temp directory."""+ return LocalEnvironment(cwd=str(tmp_path), timeout=15)+++class TestStdinErrorPropagation:+ def test_execute_surfaces_stdin_error_without_hanging(self, env):+ t0 = time.monotonic()+ result = env.execute("cat > /dev/null", stdin_data="\ud800")+ elapsed = time.monotonic() - t0++ assert result["returncode"] == 0 # child saw EOF, exited cleanly+ assert result.get("stdin_error") # the write failure was surfaced+ assert "stdin write failed" in result["output"]+ assert elapsed < 5.0, f"stdin failure path hung for {elapsed:.1f}s"+++class TestExecStdinErrorMapping:+ def test_exec_maps_stdin_error_to_failure(self):+ """Defense-in-depth path (unreachable from write_file after Task 3 —+ tested with a mock env for exactly that reason)."""+ env = MagicMock()+ env.execute.return_value = {+ "output": "child output\n[stdin write failed: boom]",+ "returncode": 0,+ "stdin_error": "boom",+ }+ ops = ShellFileOperations(env, cwd="/tmp")+ result = ops._exec("echo hi", cwd="/tmp", stdin_data="\ud800")+ assert result.exit_code == 1+ assert "boom" in result.stdout+++class TestPipeStdinRemainingBranches:+ """Review-requested coverage: bytes passthrough + proc.stdin None."""++ def test_bytes_input_passes_through_untouched(self, tmp_path):+ out = tmp_path / "out.bin"+ proc = subprocess.Popen(+ ["bash", "-c", f"cat > {shlex.quote(str(out))}"],+ stdin=subprocess.PIPE, stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT, text=True,+ encoding="utf-8", errors="replace",+ )+ try:+ _pipe_stdin(proc, b"\x00\x01\xfe")+ _wait_or_kill(proc)+ finally:+ if proc.poll() is None:+ proc.kill()+ assert proc.returncode == 0+ assert out.read_bytes() == b"\x00\x01\xfe"+ assert proc._hermes_stdin_errors == []++ def test_stdin_none_records_runtime_error(self, tmp_path):+ proc = subprocess.Popen(+ ["bash", "-c", "exit 0"],+ stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT, text=True,+ encoding="utf-8", errors="replace",+ )+ _pipe_stdin(proc, "data")+ _wait_or_kill(proc)+ assert proc.returncode == 0+ assert proc._hermes_stdin_errors+ assert isinstance(proc._hermes_stdin_errors[0], RuntimeError)diff --git a/tools/environments/base.py b/tools/environments/base.pyindex 7b0d0279e34..5375e19bfee 100644--- a/tools/environments/base.py+++ b/tools/environments/base.py@@ -349,7 +349,9 @@ def _pipe_stdin(proc: subprocess.Popen, data: str) -> None:except Exception:pass- threading.Thread(target=_write, daemon=True).start()+ thread = threading.Thread(target=_write, daemon=True)+ proc._hermes_stdin_thread = thread+ thread.start()def _popen_bash(@@ -1259,7 +1261,22 @@ class BaseEnvironment(ABC):proc.returncode,)- return self._finalize_wait_result(output, output.render(), proc.returncode)+ # Join the stdin writer thread before reading its error list: a child+ # that exits without reading stdin can otherwise race ahead of a+ # recorded encode failure, silently dropping it. The thread cannot+ # block long after child exit (write raises BrokenPipeError once the+ # pipe closes); the timeout is a pure safety net.+ stdin_thread = getattr(proc, "_hermes_stdin_thread", None)+ if stdin_thread is not None:+ stdin_thread.join(timeout=5)+ rendered = output.render()+ result = self._finalize_wait_result(output, rendered, proc.returncode)+ stdin_errors = getattr(proc, "_hermes_stdin_errors", None)+ if stdin_errors:+ err = str(stdin_errors[0])+ result["stdin_error"] = err+ result["output"] = rendered + f"\n[stdin write failed: {err}]"+ return result@staticmethoddef _finalize_wait_result(collector: "_BoundedOutputCollector",diff --git a/tools/file_operations.py b/tools/file_operations.pyindex 6e3ede2ee94..3a152106c51 100644--- a/tools/file_operations.py+++ b/tools/file_operations.py@@ -875,9 +875,16 @@ class ShellFileOperations(FileOperations):# Fall through to init-time self.cwd only if the env doesn't track cwd.effective_cwd = cwd or getattr(self.env, 'cwd', None) or self.cwdresult = self.env.execute(command, cwd=effective_cwd, **kwargs)+ exit_code = result.get("returncode", 0)+ # A stdin write failure with an otherwise-clean child exit is still+ # a failure: the child never received the intended input. write_file+ # rejects such content up front (Task 3); this mapping is+ # defense-in-depth for any other stdin caller.+ if result.get("stdin_error") and exit_code == 0:+ exit_code = 1return ExecuteResult(stdout=result.get("output", ""),- exit_code=result.get("returncode", 0)+ exit_code=exit_code)def _has_command(self, cmd: str) -> bool: