The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(environments): preserve byte-exact SDK stdin
JoaoMarcos442a0f0f4a66de
diff --git a/tests/tools/test_daytona_environment.py b/tests/tools/test_daytona_environment.pyindex 22530a5e6fd..595d6cc0277 100644--- a/tests/tools/test_daytona_environment.py+++ b/tests/tools/test_daytona_environment.py@@ -193,6 +193,33 @@ class TestExecute:assert "hello" in result["output"]assert result["returncode"] == 0+ def test_cancel_cleans_staged_stdin_before_stopping(self, make_env):+ env = make_env()+ sandbox = env._sandbox+ sandbox.process.exec.reset_mock()+ started = threading.Event()+ release = threading.Event()++ def exec_side_effect(command, **kwargs):+ if "cat > /tmp/payload.txt" in command:+ started.set()+ release.wait(timeout=5)+ return _make_exec_response(result="", exit_code=0)++ sandbox.process.exec.side_effect = exec_side_effect+ handle = env._run_bash("cat > /tmp/payload.txt", stdin_data="secret")+ assert started.wait(timeout=1)++ handle.kill()+ release.set()++ assert handle.wait(timeout=2) == 0+ sandbox.fs.delete_file.assert_called()+ deleted_path = sandbox.fs.delete_file.call_args.args[0]+ assert ".hermes-stdin-" in deleted_path+ assert sandbox.fs.delete_file.call_args.kwargs["request_timeout"] == 5+ sandbox.stop.assert_called()+def test_large_stdin_is_staged_outside_command_argv(self, make_env):env = make_env()sandbox = env._sandbox@@ -205,19 +232,24 @@ class TestExecute:uploads.append((remote_path, staged.read()))sandbox.fs.upload_file.side_effect = capture_upload- payload = "x" * (70 * 1024)+ expected = (b"A" * (160 * 1024)) + b"\x00\xff\xfeTAIL"+ payload = expected.decode("utf-8", "surrogateescape")handle = env._run_bash("cat > /tmp/payload.txt", stdin_data=payload)assert handle.wait(timeout=2) == 0assert env._stdin_mode == "payload"- assert uploads and uploads[0][1] == payload.encode("utf-8")+ assert uploads and uploads[0][1] == expected+ assert sandbox.fs.set_file_permissions.call_args.args[0] == uploads[0][0]+ assert sandbox.fs.set_file_permissions.call_args.kwargs["mode"] == "600"shell_cmd = next(call.args[0] for call in sandbox.process.exec.call_args_listif "cat > /tmp/payload.txt" in call.args[0])assert payload not in shell_cmdassert ".hermes-stdin-" in shell_cmd+ assert shell_cmd.index("exec 0<") < shell_cmd.index("rm -f --")+ assert shell_cmd.index("rm -f --") < shell_cmd.index("cat > /tmp/payload.txt")diff --git a/tests/tools/test_modal_bulk_upload.py b/tests/tools/test_modal_bulk_upload.pyindex 120e13f7d69..f349219d207 100644--- a/tests/tools/test_modal_bulk_upload.py+++ b/tests/tools/test_modal_bulk_upload.py@@ -114,7 +114,7 @@ class TestModalBulkUpload:assert args[1] == "-c"# Reassemble the base64 payload from stdin chunks and verify tar contents- payload = "".join(stdin_mock._written_chunks)+ payload = b"".join(stdin_mock._written_chunks)tar_data = base64.b64decode(payload)buf = io.BytesIO(tar_data)with tarfile.open(fileobj=buf, mode="r:gz") as tar:@@ -150,7 +150,7 @@ class TestModalBulkUpload:assert len(stdin_mock._written_chunks) >= 2# Reassembled payload should still decode to valid tar- payload = "".join(stdin_mock._written_chunks)+ payload = b"".join(stdin_mock._written_chunks)tar_data = base64.b64decode(payload)buf = io.BytesIO(tar_data)with tarfile.open(fileobj=buf, mode="r:gz") as tar:@@ -161,14 +161,15 @@ class TestModalBulkUpload:class TestModalCommandStdin:def test_large_payload_uses_sdk_stdin_not_bash_argv(self, monkeypatch, tmp_path):env = _make_mock_modal_env(monkeypatch, tmp_path)- payload = "x" * (70 * 1024)+ expected = (b"A" * (160 * 1024)) + b"\x00\xff\xfeTAIL"+ payload = expected.decode("utf-8", "surrogateescape")exec_calls, _, stdin_mock = _wire_async_exec(env)handle = env._run_bash("cat > /tmp/payload.txt", stdin_data=payload)assert handle.wait(timeout=2) == 0assert modal_env.ModalEnvironment._stdin_mode == "payload"- assert "".join(stdin_mock._written_chunks) == payload+ assert b"".join(stdin_mock._written_chunks) == expectedassert len(exec_calls) == 1assert payload not in " ".join(str(part) for part in exec_calls[0])stdin_mock.write_eof.assert_called_once()diff --git a/tests/tools/test_vercel_sandbox_environment.py b/tests/tools/test_vercel_sandbox_environment.pyindex 533ae8c1746..1561de004ed 100644--- a/tests/tools/test_vercel_sandbox_environment.py+++ b/tests/tools/test_vercel_sandbox_environment.py@@ -523,6 +523,36 @@ class TestExecute:assert args == ["-c", "echo done"]assert kwargs["cwd"] == "/vercel/sandbox"+ def test_cancel_stops_without_dispatching_cleanup_command(+ self, make_env, vercel_sdk+ ):+ env = make_env()+ sandbox = vercel_sdk.current+ sandbox.run_command_calls.clear()+ started = threading.Event()+ release = threading.Event()++ def blocking_command(_cmd: str, _args: list[str], _kwargs: dict):+ started.set()+ release.wait(timeout=5)+ return _FakeRunResult("")++ sandbox.run_command_side_effects.append(blocking_command)+ handle = env._run_bash("cat > /tmp/payload.txt", stdin_data="secret")+ assert started.wait(timeout=1)++ handle.kill()+ release.set()++ assert handle.wait(timeout=2) == 0+ # kill() must not dispatch another potentially unbounded SDK command.+ user_calls = [+ (cmd, args) for cmd, args, _ in sandbox.run_command_calls+ if cmd == "bash" and len(args) > 1 and "cat > /tmp/payload.txt" in args[1]+ ]+ assert len(user_calls) == 1+ assert len(sandbox.stop_calls) == 1+def test_large_stdin_is_staged_outside_command_argv(self, make_env, vercel_sdk):@@ -530,7 +560,8 @@ class TestExecute:sandbox = vercel_sdk.currentsandbox.run_command_calls.clear()sandbox.write_files_calls.clear()- payload = "x" * (70 * 1024)+ expected = (b"A" * (160 * 1024)) + b"\x00\xff\xfeTAIL"+ payload = expected.decode("utf-8", "surrogateescape")handle = env._run_bash("cat > /tmp/payload.txt", stdin_data=payload)@@ -538,13 +569,16 @@ class TestExecute:assert env._stdin_mode == "payload"assert sandbox.write_files_callsstaged = sandbox.write_files_calls[0][0]- assert staged["content"] == payload.encode("utf-8")+ assert staged["content"] == expected+ assert staged["mode"] == 0o600command = next(args[1] for cmd, args, _ in sandbox.run_command_callsif cmd == "bash" and len(args) > 1 and "cat > /tmp/payload.txt" in args[1])assert payload not in commandassert ".hermes-stdin-" in command+ assert command.index("exec 0<") < command.index("rm -f --")+ assert command.index("rm -f --") < command.index("cat > /tmp/payload.txt")class TestSnapshotPersistence:diff --git a/tools/environments/daytona.py b/tools/environments/daytona.pyindex 9791a8477fc..57c76ee4113 100644--- a/tools/environments/daytona.py+++ b/tools/environments/daytona.py@@ -142,10 +142,16 @@ class DaytonaEnvironment(BaseEnvironment):def _run_bash(self, cmd_string: str, *, login: bool = False, timeout: int = 120,stdin_data: str | None = None):sandbox, lock = self._sandbox, self._lock+ staged_stdin = {"path": None}def cancel():- with lock, contextlib.suppress(Exception):- sandbox.stop()+ with lock:+ remote_stdin = staged_stdin["path"]+ if remote_stdin:+ with contextlib.suppress(Exception):+ sandbox.fs.delete_file(remote_stdin, request_timeout=5)+ with contextlib.suppress(Exception):+ sandbox.stop()def exec_fn() -> tuple[str, int]:remote_stdin = None@@ -153,15 +159,19 @@ class DaytonaEnvironment(BaseEnvironment):try:command = cmd_stringif stdin_data is not None:- remote_stdin = f"/tmp/.hermes-stdin-{uuid.uuid4().hex}"+ temp_dir = self.get_temp_dir().rstrip("/") or "/"+ remote_stdin = f"{temp_dir}/.hermes-stdin-{uuid.uuid4().hex}"+ staged_stdin["path"] = remote_stdinwith tempfile.NamedTemporaryFile(delete=False) as staged:local_stdin = staged.name- staged.write(stdin_data.encode("utf-8"))+ staged.write(stdin_data.encode("utf-8", "surrogateescape"))sandbox.fs.upload_file(local_stdin, remote_stdin)+ sandbox.fs.set_file_permissions(remote_stdin, mode="600")quoted_stdin = shlex.quote(remote_stdin)command = (- f"trap 'rm -f -- {quoted_stdin}' EXIT\n"- f"{{\n{cmd_string}\n}} < {quoted_stdin}"+ f"exec 0< {quoted_stdin} || exit $?\n"+ f"rm -f -- {quoted_stdin} || exit $?\n"+ f"{cmd_string}")shell_cmd = f"bash {'-l ' if login else ''}-c {shlex.quote(command)}"response = sandbox.process.exec(shell_cmd, timeout=timeout)@@ -172,7 +182,8 @@ class DaytonaEnvironment(BaseEnvironment):os.unlink(local_stdin)if remote_stdin:with contextlib.suppress(Exception):- sandbox.process.exec(f"rm -f -- {shlex.quote(remote_stdin)}")+ sandbox.fs.delete_file(remote_stdin, request_timeout=5)+ staged_stdin["path"] = Nonereturn _ThreadedProcessHandle(exec_fn, cancel_fn=cancel)diff --git a/tools/environments/modal.py b/tools/environments/modal.pyindex 08a85ce234a..22fcb101dbc 100644--- a/tools/environments/modal.py+++ b/tools/environments/modal.py@@ -82,9 +82,10 @@ def _resolve_modal_image(image_spec: Any) -> Any:async def _stream_stdin(proc, payload: str, chunk_size: int) -> None:- """Write ``payload`` to ``proc.stdin`` in ``chunk_size`` pieces, draining after each, then EOF."""- for offset in range(0, len(payload), chunk_size):- proc.stdin.write(payload[offset:offset + chunk_size])+ """Write byte-exact UTF-8 payload chunks to ``proc.stdin``, then EOF."""+ data = payload.encode("utf-8", "surrogateescape")+ for offset in range(0, len(data), chunk_size):+ proc.stdin.write(data[offset:offset + chunk_size])await proc.stdin.drain.aio()proc.stdin.write_eof()await proc.stdin.drain.aio()diff --git a/tools/environments/vercel_sandbox.py b/tools/environments/vercel_sandbox.pyindex 1768ab14afe..0075afc801b 100644--- a/tools/environments/vercel_sandbox.py+++ b/tools/environments/vercel_sandbox.py@@ -345,6 +345,10 @@ class VercelSandboxEnvironment(BaseEnvironment):sandbox, workspace_root, lock = self._require_sandbox(), self._workspace_root, self._lockdef cancel() -> None:+ # Do not dispatch a second command here: the pinned 0.7.2 SDK has no+ # per-command timeout, so cleanup could block the synchronous kill path.+ # Once the staged file is opened below it is unlinked before user code;+ # stopping the captured sandbox contains the pre-dispatch race.with lock:self._stop_sandbox(sandbox)@@ -353,27 +357,32 @@ class VercelSandboxEnvironment(BaseEnvironment):try:command = cmd_stringif stdin_data is not None:- remote_stdin = f"/tmp/.hermes-stdin-{uuid.uuid4().hex}"+ temp_dir = self.get_temp_dir().rstrip("/") or "/"+ remote_stdin = f"{temp_dir}/.hermes-stdin-{uuid.uuid4().hex}"_retry_vercel_call("stdin upload",lambda: sandbox.write_files([{"path": remote_stdin,- "content": stdin_data.encode("utf-8"),+ "content": stdin_data.encode("utf-8", "surrogateescape"),+ "mode": 0o600,}]),attempts=_WRITE_RETRY_ATTEMPTS,)quoted_stdin = shlex.quote(remote_stdin)command = (- f"trap 'rm -f -- {quoted_stdin}' EXIT\n"- f"{{\n{cmd_string}\n}} < {quoted_stdin}"+ f"exec 0< {quoted_stdin} || exit $?\n"+ f"rm -f -- {quoted_stdin} || exit $?\n"+ f"{cmd_string}")- return _result_parts(- sandbox.run_command("bash", ["-lc" if login else "-c", command], cwd=workspace_root))- finally:- if remote_stdin:- with contextlib.suppress(Exception):- sandbox.run_command(- "bash", ["-c", f"rm -f -- {shlex.quote(remote_stdin)}"], cwd=workspace_root)+ result = sandbox.run_command(+ "bash", ["-lc" if login else "-c", command], cwd=workspace_root)+ return _result_parts(result)+ except Exception:+ # If dispatch failed before the shell could open+unlink the staging+ # file, fail closed by stopping this captured sandbox. Hermes never+ # reuses a terminal Vercel sandbox on the next execute.+ self._stop_sandbox(sandbox)+ raisereturn _ThreadedProcessHandle(exec_fn, cancel_fn=cancel)def cleanup(self):diff --git a/tools/terminal_tool_sudo.py b/tools/terminal_tool_sudo.pyindex 4f1b78949b7..f3499a4c182 100644--- a/tools/terminal_tool_sudo.py+++ b/tools/terminal_tool_sudo.py@@ -437,8 +437,8 @@ def _transform_sudo_command(execution environment). Returns ``(command, sudo_stdin)``: ``sudo_stdin`` is one passwordline per sudo invocation that the caller must PREPEND to the process stdin (sudo -S consumesexactly one line and passes the rest through, so it's safe alongside the caller's own- stdin_data). Backends that can't pipe stdin (modal, daytona, vercel_sandbox) embed the- password in the command string themselves. With no password available the command is+ stdin_data). Backends transport that merged stream according to their execution API+ (pipe, SDK stdin, or staged file). With no password available the command isreturned unchanged and ``sudo_stdin`` is None, so it fails gracefully with "sudo: a passwordis required". Password sources, in order: configured SUDO_PASSWORD, the session cache, thenan interactive prompt (45s timeout, cached on success) when a UI is reachable.