command_manager.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. from typing import List
  2. from opendevin import config
  3. from opendevin.observation import CmdOutputObservation
  4. from opendevin.sandbox import DockerExecBox, DockerSSHBox, Sandbox, LocalBox
  5. from opendevin.schema import ConfigType
  6. class CommandManager:
  7. id: str
  8. shell: Sandbox
  9. def __init__(
  10. self,
  11. sid: str,
  12. container_image: str | None = None,
  13. ):
  14. sandbox_type = config.get(ConfigType.SANDBOX_TYPE).lower()
  15. if sandbox_type == 'exec':
  16. self.shell = DockerExecBox(
  17. sid=(sid or 'default'), container_image=container_image
  18. )
  19. elif sandbox_type == 'local':
  20. self.shell = LocalBox()
  21. elif sandbox_type == 'ssh':
  22. self.shell = DockerSSHBox(
  23. sid=(sid or 'default'), container_image=container_image
  24. )
  25. else:
  26. raise ValueError(f'Invalid sandbox type: {sandbox_type}')
  27. def run_command(self, command: str, background=False) -> CmdOutputObservation:
  28. if background:
  29. return self._run_background(command)
  30. else:
  31. return self._run_immediately(command)
  32. def _run_immediately(self, command: str) -> CmdOutputObservation:
  33. exit_code, output = self.shell.execute(command)
  34. return CmdOutputObservation(
  35. command_id=-1, content=output, command=command, exit_code=exit_code
  36. )
  37. def _run_background(self, command: str) -> CmdOutputObservation:
  38. bg_cmd = self.shell.execute_in_background(command)
  39. content = f'Background command started. To stop it, send a `kill` action with id {bg_cmd.id}'
  40. return CmdOutputObservation(
  41. content=content,
  42. command_id=bg_cmd.id,
  43. command=command,
  44. exit_code=0,
  45. )
  46. def kill_command(self, id: int) -> CmdOutputObservation:
  47. cmd = self.shell.kill_background(id)
  48. return CmdOutputObservation(
  49. content=f'Background command with id {id} has been killed.',
  50. command_id=id,
  51. command=cmd.command,
  52. exit_code=0,
  53. )
  54. def get_background_obs(self) -> List[CmdOutputObservation]:
  55. obs = []
  56. for _id, cmd in self.shell.background_commands.items():
  57. output = cmd.read_logs()
  58. if output is not None and output != '':
  59. obs.append(
  60. CmdOutputObservation(
  61. content=output, command_id=_id, command=cmd.command
  62. )
  63. )
  64. return obs