π OpenHands: AI-Driven Development
Sandbox: adjust whitespace processing (#1474)
Robert Brennand94b575cd479
diff --git a/opendevin/runtime/docker/ssh_box.py b/opendevin/runtime/docker/ssh_box.pyindex 4e3da8ad1e..c2949bd800 100644--- a/opendevin/runtime/docker/ssh_box.py+++ b/opendevin/runtime/docker/ssh_box.py@@ -7,6 +7,7 @@ import timeimport uuidfrom collections import namedtuplefrom glob import glob+from typing import Tupleimport dockerfrom pexpect import pxssh@@ -28,6 +29,95 @@ InputType = namedtuple('InputType', ['content'])OutputType = namedtuple('OutputType', ['content'])+def split_bash_commands(commands):+ # States+ NORMAL = 0+ IN_SINGLE_QUOTE = 1+ IN_DOUBLE_QUOTE = 2+ IN_HEREDOC = 3++ state = NORMAL+ heredoc_trigger = None+ result = []+ current_command: list[str] = []++ i = 0+ while i < len(commands):+ char = commands[i]++ if state == NORMAL:+ if char == "'":+ state = IN_SINGLE_QUOTE+ elif char == '"':+ state = IN_DOUBLE_QUOTE+ elif char == '\\':+ # Check if this is escaping a newline+ if i + 1 < len(commands) and commands[i + 1] == '\n':+ i += 1 # Skip the newline+ # Continue with the next line as part of the same command+ i += 1 # Move to the first character of the next line+ continue+ elif char == '\n':+ if not heredoc_trigger and current_command:+ result.append(''.join(current_command).strip())+ current_command = []+ elif char == '<' and commands[i : i + 2] == '<<':+ # Detect heredoc+ state = IN_HEREDOC+ i += 2 # Skip '<<'+ while commands[i] == ' ':+ i += 1+ start = i+ while commands[i] not in [' ', '\n']:+ i += 1+ heredoc_trigger = commands[start:i]+ current_command.append(commands[start - 2 : i]) # Include '<<'+ continue # Skip incrementing i at the end of the loop+ current_command.append(char)++ elif state == IN_SINGLE_QUOTE:+ current_command.append(char)+ if char == "'" and commands[i - 1] != '\\':+ state = NORMAL++ elif state == IN_DOUBLE_QUOTE:+ current_command.append(char)+ if char == '"' and commands[i - 1] != '\\':+ state = NORMAL++ elif state == IN_HEREDOC:+ current_command.append(char)+ if (+ char == '\n'+ and heredoc_trigger+ and commands[i + 1 : i + 1 + len(heredoc_trigger) + 1]+ == heredoc_trigger + '\n'+ ):+ # Check if the next line starts with the heredoc trigger followed by a newline+ i += (+ len(heredoc_trigger) + 1+ ) # Move past the heredoc trigger and newline+ current_command.append(+ heredoc_trigger + '\n'+ ) # Include the heredoc trigger and newline+ result.append(''.join(current_command).strip())+ current_command = []+ heredoc_trigger = None+ state = NORMAL+ continue++ i += 1++ # Add the last command if any+ if current_command:+ result.append(''.join(current_command).strip())++ # Remove any empty strings from the result+ result = [cmd for cmd in result if cmd]++ return result++class DockerSSHBox(Sandbox):instance_id: strcontainer_image: str@@ -189,7 +279,7 @@ class DockerSSHBox(Sandbox):def start_ssh_session(self):# start ssh session at the background- self.ssh = pxssh.pxssh()+ self.ssh = pxssh.pxssh(echo=False, timeout=self.timeout)hostname = self.ssh_hostnameif self.run_as_devin:username = 'opendevin'@@ -221,9 +311,18 @@ class DockerSSHBox(Sandbox):bg_cmd = self.background_commands[id]return bg_cmd.read_logs()- def execute(self, cmd: str) -> tuple[int, str]:- cmd = cmd.strip()- # use self.ssh+ def execute(self, cmd: str) -> Tuple[int, str]:+ commands = split_bash_commands(cmd)+ if len(commands) > 1:+ all_output = ''+ for command in commands:+ exit_code, output = self.execute(command)+ if all_output:+ all_output += '\r\n'+ all_output += output+ if exit_code != 0:+ return exit_code, all_output+ return 0, all_outputself.ssh.sendline(cmd)success = self.ssh.prompt(timeout=self.timeout)if not success:@@ -231,12 +330,12 @@ class DockerSSHBox(Sandbox):# send a SIGINT to the processself.ssh.sendintr()self.ssh.prompt()- command_output = self.ssh.before.decode('utf-8').lstrip(cmd).strip()+ command_output = self.ssh.before.decode('utf-8')return (-1,f'Command: "{cmd}" timed out. Sending SIGINT to the process: {command_output}',)- command_output = self.ssh.before.decode('utf-8').strip()+ command_output = self.ssh.before.decode('utf-8')# once out, make sure that we have *every* output, we while loop until we get an empty outputwhile True:@@ -247,24 +346,24 @@ class DockerSSHBox(Sandbox):logger.debug('TIMEOUT REACHED')breaklogger.debug('WAITING FOR .before')- output = self.ssh.before.decode('utf-8').strip()+ output = self.ssh.before.decode('utf-8')logger.debug(f'WAITING FOR END OF command output ({bool(output)}): {output}')if output == '':breakcommand_output += output- command_output = command_output.lstrip(cmd).strip()+ command_output = command_output.removesuffix('\r\n')# get the exit codeself.ssh.sendline('echo $?')self.ssh.prompt()- exit_code = self.ssh.before.decode('utf-8')- while not exit_code.startswith('echo $?'):+ exit_code_str = self.ssh.before.decode('utf-8')+ while not exit_code_str:self.ssh.prompt()- exit_code = self.ssh.before.decode('utf-8')- logger.debug(f'WAITING FOR exit code: {exit_code}')- exit_code = int(exit_code.lstrip('echo $?').strip())+ exit_code_str = self.ssh.before.decode('utf-8')+ logger.debug(f'WAITING FOR exit code: {exit_code_str}')+ exit_code = int(exit_code_str.strip())return exit_code, command_outputdef copy_to(self, host_src: str, sandbox_dest: str, recursive: bool = False):diff --git a/opendevin/runtime/e2b/sandbox.py b/opendevin/runtime/e2b/sandbox.pyindex 38033b71e4..3e1786b31b 100644--- a/opendevin/runtime/e2b/sandbox.py+++ b/opendevin/runtime/e2b/sandbox.py@@ -94,7 +94,7 @@ class E2BBox(Sandbox):tar_filename = self._archive(host_src, recursive)# Prepend the sandbox destination with our sandbox cwd- sandbox_dest = os.path.join(self._cwd, sandbox_dest.lstrip('/'))+ sandbox_dest = os.path.join(self._cwd, sandbox_dest.removeprefix('/'))with open(tar_filename, 'rb') as tar_file:# Upload the archive to /home/user (default destination that always exists)diff --git a/tests/unit/test_sandbox.py b/tests/unit/test_sandbox.pyindex 7a9826931e..6ba183f3f1 100644--- a/tests/unit/test_sandbox.py+++ b/tests/unit/test_sandbox.py@@ -8,7 +8,7 @@ import pytestfrom opendevin.core.config import AppConfig, configfrom opendevin.runtime.docker.exec_box import DockerExecBoxfrom opendevin.runtime.docker.local_box import LocalBox-from opendevin.runtime.docker.ssh_box import DockerSSHBox+from opendevin.runtime.docker.ssh_box import DockerSSHBox, split_bash_commands@pytest.fixture@@ -39,6 +39,62 @@ def test_env_vars(temp_dir):assert output.strip() == 'BAZ abc"def', f'Output: {output} for {box_class}'+def test_split_commands():+ cmds = [+ 'ls -l',+ 'echo -e "hello\nworld"',+ """+echo -e 'hello it\\'s me'+""".strip(),+ """+echo \\+ -e 'hello' \\+ -v+""".strip(),+ """+echo -e 'hello\\nworld\\nare\\nyou\\nthere?'+""".strip(),+ """+echo -e 'hello+world+are+you\\n+there?'+""".strip(),+ """+echo -e 'hello+world "+'+""".strip(),+ """+kubectl apply -f - <<EOF+apiVersion: v1+kind: Pod+metadata:+ name: busybox-sleep+spec:+ containers:+ - name: busybox+ image: busybox:1.28+ args:+ - sleep+ - "1000000"+EOF+""".strip(),+ ]+ joined_cmds = '\n'.join(cmds)+ split_cmds = split_bash_commands(joined_cmds)+ for s in split_cmds:+ print('\nCMD')+ print(s)+ cmds = [+ c.replace('\\\n', '') for c in cmds+ ] # The function strips escaped newlines, but this shouldn't matter+ assert (+ split_cmds == cmds+ ), 'The split commands should be the same as the input commands.'++def test_ssh_box_run_as_devin(temp_dir):# get a temporary directorywith patch.object(config, 'workspace_base', new=temp_dir), patch.object(@@ -46,30 +102,51 @@ def test_ssh_box_run_as_devin(temp_dir):), patch.object(config, 'run_as_devin', new='true'), patch.object(config, 'sandbox_type', new='ssh'):- ssh_box = DockerSSHBox()+ for box in [+ DockerSSHBox()+ ]: # FIXME: permission error on mkdir test for exec box+ exit_code, output = box.execute('ls -l')+ assert exit_code == 0, (+ 'The exit code should be 0 for ' + box.__class__.__name__+ )+ assert output.strip() == 'total 0'- # test the ssh box- assert config.workspace_base == temp_dir- exit_code, output = ssh_box.execute('ls -l')- assert exit_code == 0, 'The exit code should be 0.'- assert output.strip() == 'total 0'+ exit_code, output = box.execute('mkdir test')+ assert exit_code == 0, (+ 'The exit code should be 0 for ' + box.__class__.__name__+ )+ assert output.strip() == ''- exit_code, output = ssh_box.execute('mkdir test')- assert exit_code == 0, 'The exit code should be 0.'- assert output.strip() == ''+ assert config.workspace_base == temp_dir+ exit_code, output = box.execute('ls -l')+ assert exit_code == 0, 'The exit code should be 0.'+ assert output.strip() == 'total 0'- exit_code, output = ssh_box.execute('ls -l')- assert exit_code == 0, 'The exit code should be 0.'- assert 'opendevin' in output, "The output should contain username 'opendevin'"- assert 'test' in output, 'The output should contain the test directory'+ exit_code, output = box.execute('ls -l')+ assert exit_code == 0, 'The exit code should be 0.'+ assert 'opendevin' in output, (+ "The output should contain username 'opendevin' for "+ + box.__class__.__name__+ )+ assert 'test' in output, (+ 'The output should contain the test directory for '+ + box.__class__.__name__+ )- exit_code, output = ssh_box.execute('touch test/foo.txt')- assert exit_code == 0, 'The exit code should be 0.'- assert output.strip() == ''+ exit_code, output = box.execute('touch test/foo.txt')+ assert exit_code == 0, (+ 'The exit code should be 0. for ' + box.__class__.__name__+ )+ assert output.strip() == ''- exit_code, output = ssh_box.execute('ls -l test')- assert exit_code == 0, 'The exit code should be 0.'- assert 'foo.txt' in output, 'The output should contain the foo.txt file'+ exit_code, output = box.execute('ls -l test')+ assert exit_code == 0, (+ 'The exit code should be 0. for ' + box.__class__.__name__+ )+ assert 'foo.txt' in output, (+ 'The output should contain the foo.txt file for '+ + box.__class__.__name__+ )def test_ssh_box_multi_line_cmd_run_as_devin(temp_dir):@@ -79,13 +156,17 @@ def test_ssh_box_multi_line_cmd_run_as_devin(temp_dir):), patch.object(config, 'run_as_devin', new='true'), patch.object(config, 'sandbox_type', new='ssh'):- ssh_box = DockerSSHBox()-- # test the ssh box- exit_code, output = ssh_box.execute('pwd\nls -l')- assert exit_code == 0, 'The exit code should be 0.'- expected_lines = ['/workspacels -l', 'total 0']- assert output.strip().splitlines() == expected_lines+ for box in [DockerSSHBox(), DockerExecBox()]:+ exit_code, output = box.execute('pwd\nls -l')+ assert exit_code == 0, (+ 'The exit code should be 0 for ' + box.__class__.__name__+ )+ expected_lines = ['/workspace', 'total 0']+ line_sep = '\r\n' if isinstance(box, DockerSSHBox) else '\n'+ assert output == line_sep.join(expected_lines), (+ 'The output should be the same as the input for '+ + box.__class__.__name__+ )def test_ssh_box_stateful_cmd_run_as_devin(temp_dir):@@ -95,20 +176,28 @@ def test_ssh_box_stateful_cmd_run_as_devin(temp_dir):), patch.object(config, 'run_as_devin', new='true'), patch.object(config, 'sandbox_type', new='ssh'):- ssh_box = DockerSSHBox()-- # test the ssh box- exit_code, output = ssh_box.execute('mkdir test')- assert exit_code == 0, 'The exit code should be 0.'- assert output.strip() == ''+ for box in [+ DockerSSHBox()+ ]: # FIXME: DockerExecBox() does not work with stateful commands+ exit_code, output = box.execute('mkdir test')+ assert exit_code == 0, 'The exit code should be 0.'+ assert output.strip() == ''- exit_code, output = ssh_box.execute('cd test')- assert exit_code == 0, 'The exit code should be 0.'- assert output.strip() == ''+ exit_code, output = box.execute('cd test')+ assert exit_code == 0, (+ 'The exit code should be 0 for ' + box.__class__.__name__+ )+ assert output.strip() == '', (+ 'The output should be empty for ' + box.__class__.__name__+ )- exit_code, output = ssh_box.execute('pwd')- assert exit_code == 0, 'The exit code should be 0.'- assert output.strip() == '/workspace/test'+ exit_code, output = box.execute('pwd')+ assert exit_code == 0, (+ 'The exit code should be 0 for ' + box.__class__.__name__+ )+ assert output.strip() == '/workspace/test', (+ 'The output should be /workspace for ' + box.__class__.__name__+ )def test_ssh_box_failed_cmd_run_as_devin(temp_dir):@@ -118,8 +207,94 @@ def test_ssh_box_failed_cmd_run_as_devin(temp_dir):), patch.object(config, 'run_as_devin', new='true'), patch.object(config, 'sandbox_type', new='ssh'):- ssh_box = DockerSSHBox()+ for box in [DockerSSHBox(), DockerExecBox()]:+ exit_code, output = box.execute('non_existing_command')+ assert exit_code != 0, (+ 'The exit code should not be 0 for a failed command for '+ + box.__class__.__name__+ )+++def test_single_multiline_command(temp_dir):+ with patch.dict(+ config.config,+ {+ config.ConfigType.WORKSPACE_BASE: temp_dir,+ config.ConfigType.RUN_AS_DEVIN: 'true',+ config.ConfigType.SANDBOX_TYPE: 'ssh',+ },+ clear=True,+ ):+ for box in [DockerSSHBox(), DockerExecBox()]:+ exit_code, output = box.execute('echo \\\n -e "foo"')+ assert exit_code == 0, (+ 'The exit code should be 0 for ' + box.__class__.__name__+ )+ if isinstance(box, DockerExecBox):+ assert output == 'foo', (+ 'The output should be the same as the input for '+ + box.__class__.__name__+ )+ else:+ # FIXME: why is there a `>` in the output? Probably PS2?+ assert output == '> foo', (+ 'The output should be the same as the input for '+ + box.__class__.__name__+ )+- # test the ssh box with a command that fails- exit_code, output = ssh_box.execute('non_existing_command')- assert exit_code != 0, 'The exit code should not be 0 for a failed command.'+def test_multiline_echo(temp_dir):+ with patch.dict(+ config.config,+ {+ config.ConfigType.WORKSPACE_BASE: temp_dir,+ config.ConfigType.RUN_AS_DEVIN: 'true',+ config.ConfigType.SANDBOX_TYPE: 'ssh',+ },+ clear=True,+ ):+ for box in [DockerSSHBox(), DockerExecBox()]:+ exit_code, output = box.execute('echo -e "hello\nworld"')+ assert exit_code == 0, (+ 'The exit code should be 0 for ' + box.__class__.__name__+ )+ if isinstance(box, DockerExecBox):+ assert output == 'hello\nworld', (+ 'The output should be the same as the input for '+ + box.__class__.__name__+ )+ else:+ # FIXME: why is there a `>` in the output?+ assert output == '> hello\r\nworld', (+ 'The output should be the same as the input for '+ + box.__class__.__name__+ )+++def test_sandbox_whitespace(temp_dir):+ # get a temporary directory+ with patch.dict(+ config.config,+ {+ config.ConfigType.WORKSPACE_BASE: temp_dir,+ config.ConfigType.RUN_AS_DEVIN: 'true',+ config.ConfigType.SANDBOX_TYPE: 'ssh',+ },+ clear=True,+ ):+ for box in [DockerSSHBox(), DockerExecBox()]:+ # test the ssh box+ exit_code, output = box.execute('echo -e "\\n\\n\\n"')+ assert exit_code == 0, (+ 'The exit code should be 0 for ' + box.__class__.__name__+ )+ if isinstance(box, DockerExecBox):+ assert output == '\n\n\n', (+ 'The output should be the same as the input for '+ + box.__class__.__name__+ )+ else:+ assert output == '\r\n\r\n\r\n', (+ 'The output should be the same as the input for '+ + box.__class__.__name__+ )