runtime.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from opendevin.events.action import (
  2. FileReadAction,
  3. FileWriteAction,
  4. )
  5. from opendevin.events.observation import (
  6. ErrorObservation,
  7. FileReadObservation,
  8. FileWriteObservation,
  9. Observation,
  10. )
  11. from opendevin.events.stream import EventStream
  12. from opendevin.runtime import Sandbox
  13. from opendevin.runtime.server.files import insert_lines, read_lines
  14. from opendevin.runtime.server.runtime import ServerRuntime
  15. from .sandbox import E2BSandbox
  16. class E2BRuntime(ServerRuntime):
  17. def __init__(
  18. self,
  19. event_stream: EventStream,
  20. sid: str = 'default',
  21. sandbox: Sandbox | None = None,
  22. ):
  23. super().__init__(event_stream, sid, sandbox)
  24. if not isinstance(self.sandbox, E2BSandbox):
  25. raise ValueError('E2BRuntime requires an E2BSandbox')
  26. self.filesystem = self.sandbox.filesystem
  27. async def read(self, action: FileReadAction) -> Observation:
  28. content = self.filesystem.read(action.path)
  29. lines = read_lines(content.split('\n'), action.start, action.end)
  30. code_view = ''.join(lines)
  31. return FileReadObservation(code_view, path=action.path)
  32. async def write(self, action: FileWriteAction) -> Observation:
  33. if action.start == 0 and action.end == -1:
  34. self.filesystem.write(action.path, action.content)
  35. return FileWriteObservation(content='', path=action.path)
  36. files = self.filesystem.list(action.path)
  37. if action.path in files:
  38. all_lines = self.filesystem.read(action.path)
  39. new_file = insert_lines(
  40. action.content.split('\n'), all_lines, action.start, action.end
  41. )
  42. self.filesystem.write(action.path, ''.join(new_file))
  43. return FileWriteObservation('', path=action.path)
  44. else:
  45. # FIXME: we should create a new file here
  46. return ErrorObservation(f'File not found: {action.path}')