runtime.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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 .filestore import E2BFileStore
  16. from .sandbox import E2BSandbox
  17. class E2BRuntime(ServerRuntime):
  18. def __init__(
  19. self,
  20. event_stream: EventStream,
  21. sid: str = 'default',
  22. sandbox: Sandbox | None = None,
  23. ):
  24. super().__init__(event_stream, sid, sandbox)
  25. if not isinstance(self.sandbox, E2BSandbox):
  26. raise ValueError('E2BRuntime requires an E2BSandbox')
  27. self.file_store = E2BFileStore(self.sandbox.filesystem)
  28. async def read(self, action: FileReadAction) -> Observation:
  29. content = self.file_store.read(action.path)
  30. lines = read_lines(content.split('\n'), action.start, action.end)
  31. code_view = ''.join(lines)
  32. return FileReadObservation(code_view, path=action.path)
  33. async def write(self, action: FileWriteAction) -> Observation:
  34. if action.start == 0 and action.end == -1:
  35. self.file_store.write(action.path, action.content)
  36. return FileWriteObservation(content='', path=action.path)
  37. files = self.file_store.list(action.path)
  38. if action.path in files:
  39. all_lines = self.file_store.read(action.path).split('\n')
  40. new_file = insert_lines(
  41. action.content.split('\n'), all_lines, action.start, action.end
  42. )
  43. self.file_store.write(action.path, ''.join(new_file))
  44. return FileWriteObservation('', path=action.path)
  45. else:
  46. # FIXME: we should create a new file here
  47. return ErrorObservation(f'File not found: {action.path}')