runtime.py 2.1 KB

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