The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(environments): deliver heredoc stdin byte-exact
John Paul Soliva66186a8c045a
diff --git a/tests/tools/test_file_ops_single_roundtrip.py b/tests/tools/test_file_ops_single_roundtrip.pyindex 1a371ca4f5c..f0c0045dd5b 100644--- a/tests/tools/test_file_ops_single_roundtrip.py+++ b/tests/tools/test_file_ops_single_roundtrip.py@@ -271,6 +271,39 @@ class TestWriteFileRoundTrips:assert r.error is Noneassert p.read_bytes() == b"x\r\ny\r\n"++class TestHeredocStdinBackends:+ """Modal/Daytona/Vercel embed stdin as a heredoc in the command string (the SDK exec has+ no stdin; the local env gets DEVNULL, same as there). The atomic write's temp file must+ receive exactly the content, or ``mv`` swaps a wrong file over the target."""++ @pytest.fixture+ def heredoc_ops(self, shell, monkeypatch):+ ops, _calls = shell+ monkeypatch.setattr(ops.env, "_stdin_mode", "heredoc")+ return ops++ @pytest.mark.parametrize("content", [+ "no trailing newline",+ "one trailing newline\n",+ "blank tail\n\n\n",+ "q ' \" ) ( $(x) `y` ${z} \\\ncontinued\\",+ ])+ def test_write_file_is_byte_exact(self, heredoc_ops, tmp_path, content):+ p = tmp_path / "existing.txt"+ p.write_bytes(b"keep me\n")+ r = heredoc_ops.write_file(str(p), content)+ assert p.read_bytes() == content.encode()+ assert r.error is None and r.verified is True++ def test_patch_replace_is_byte_exact(self, heredoc_ops, tmp_path):+ p = tmp_path / "notes.txt"+ p.write_bytes(b"line one\nline two\nimportant data")+ r = heredoc_ops.patch_replace(str(p), "line two", "line 2")+ assert p.read_bytes() == b"line one\nline 2\nimportant data"+ assert r.success is True++class TestNativeRead:def test_native_read_makes_no_shell_call(self, native, tmp_path):ops, calls = nativediff --git a/tests/tools/test_tool_result_storage.py b/tests/tools/test_tool_result_storage.pyindex 1e98312cc49..59e84be0cc8 100644--- a/tests/tools/test_tool_result_storage.py+++ b/tests/tools/test_tool_result_storage.py@@ -99,13 +99,12 @@ class TestWriteToSandbox:[("pipe", 512, False), # short write: bytes lost("pipe", 171, False), # pipe backends must be exact- ("heredoc", 171, True), # heredoc appends exactly one newline("host", 3, False), # host spillover: os.stat says only 3 bytes landed("host", None, True), # host spillover: real write, real stat],)def test_size_probe_decides_lossless(self, stdin_mode, probed, ok):- """An archive that is not byte-exact (modulo the heredoc newline) is discarded — never+ """An archive that is not byte-exact is discarded — neverreferenced to the model (port of lobehub/lobehub#18258). Multibyte content pins thecomparison to UTF-8 bytes (170 here, 130 chars), on both the sandbox and host paths."""import osdiff --git a/tools/environments/base.py b/tools/environments/base.pyindex 8e314b2f6f2..4bc9f330899 100644--- a/tools/environments/base.py+++ b/tools/environments/base.py@@ -421,9 +421,15 @@ class BaseEnvironment(ABC):@staticmethoddef _embed_stdin_heredoc(command: str, stdin_data: str) -> str:- """Redirect stdin_data to the complete command with a shell heredoc (SDK backends)."""+ """Redirect stdin_data to the complete command with a shell heredoc (SDK backends).+ A heredoc body always ends in a newline stdin_data may lack, and write_file verifies a+ byte-exact hash, so a process substitution re-emits the body minus that last character.+ Redirections apply left to right, so the substitution inherits the heredoc as its stdin;+ the heredoc stays outside ``<( )`` because bash 3.2 mis-parses bodies inside it. ``|| :``+ keeps an inherited ``set -e`` from killing the reader on read's EOF status."""delimiter = f"HERMES_STDIN_{uuid.uuid4().hex[:12]}"- return f"{{\n{command}\n}} << '{delimiter}'\n{stdin_data}\n{delimiter}"+ return (f"{{\n{command}\n}} << '{delimiter}' < <(IFS= read -r -d '' s || :; printf '%s' \"${{s%?}}\")\n"+ f"{stdin_data}\n{delimiter}")# --- Process lifecycle ---def _wait_for_process(diff --git a/tools/tool_result_storage.py b/tools/tool_result_storage.pyindex f00a3a79dc7..1b939ceb0be 100644--- a/tools/tool_result_storage.py+++ b/tools/tool_result_storage.py@@ -181,9 +181,7 @@ def _write_to_sandbox(content: str, remote_path: str, env) -> bool:The write is round-trip verified with ``wc -c`` (one extra exec RTT per oversized result):a zero exit from ``cat`` does not prove the bytes landed (quota/ENOSPC races, API-bodytruncation on payload backends). A measured mismatch removes the archive and fails closed;- an unprobeable backend (no ``wc``, exec error, unparseable output) stays best-effort success.- Heredoc-mode backends append exactly one trailing newline by construction- (``BaseEnvironment._embed_stdin_heredoc``), so one extra byte is accepted there."""+ an unprobeable backend (no ``wc``, exec error, unparseable output) stays best-effort success."""storage_dir = os.path.dirname(remote_path)cmd = f"mkdir -p {shlex.quote(storage_dir)} && cat > {shlex.quote(remote_path)}"if env.execute(cmd, timeout=30, stdin_data=content).get("returncode", 1) != 0:@@ -203,10 +201,6 @@ def _write_to_sandbox(content: str, remote_path: str, env) -> bool:persisted_size = int(raw[-1])if persisted_size == expected:return True- # Only heredoc mode may be +1; the payload backend (managed_modal) delivers stdin verbatim, so- # it is expected byte-exact and any drift there is a real loss.- if persisted_size == expected + 1 and getattr(env, "_stdin_mode", None) == "heredoc":- return Truelogger.warning("Sandbox spill for %s is not lossless (%d bytes in sandbox, expected %d) — discarding archive",remote_path, persisted_size, expected)try: