runtime.py 2.2 KB

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