runtime.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. import asyncio
  2. from abc import abstractmethod
  3. from opendevin.core.config import config
  4. from opendevin.core.exceptions import BrowserInitException
  5. from opendevin.core.logger import opendevin_logger as logger
  6. from opendevin.events import EventSource, EventStream, EventStreamSubscriber
  7. from opendevin.events.action import (
  8. Action,
  9. AgentRecallAction,
  10. BrowseInteractiveAction,
  11. BrowseURLAction,
  12. CmdKillAction,
  13. CmdRunAction,
  14. FileReadAction,
  15. FileWriteAction,
  16. IPythonRunCellAction,
  17. )
  18. from opendevin.events.event import Event
  19. from opendevin.events.observation import (
  20. CmdOutputObservation,
  21. ErrorObservation,
  22. NullObservation,
  23. Observation,
  24. )
  25. from opendevin.events.serialization.action import ACTION_TYPE_TO_CLASS
  26. from opendevin.runtime import (
  27. DockerExecBox,
  28. DockerSSHBox,
  29. E2BBox,
  30. LocalBox,
  31. Sandbox,
  32. )
  33. from opendevin.runtime.browser.browser_env import BrowserEnv
  34. from opendevin.runtime.plugins import PluginRequirement
  35. from opendevin.storage import FileStore, InMemoryFileStore
  36. def create_sandbox(sid: str = 'default', sandbox_type: str = 'exec') -> Sandbox:
  37. if sandbox_type == 'exec':
  38. return DockerExecBox(sid=sid)
  39. elif sandbox_type == 'local':
  40. return LocalBox()
  41. elif sandbox_type == 'ssh':
  42. return DockerSSHBox(sid=sid)
  43. elif sandbox_type == 'e2b':
  44. return E2BBox()
  45. else:
  46. raise ValueError(f'Invalid sandbox type: {sandbox_type}')
  47. class Runtime:
  48. """
  49. The runtime is how the agent interacts with the external environment.
  50. This includes a bash sandbox, a browser, and filesystem interactions.
  51. sid is the session id, which is used to identify the current user session.
  52. """
  53. sid: str
  54. file_store: FileStore
  55. def __init__(
  56. self,
  57. event_stream: EventStream,
  58. sid: str = 'default',
  59. sandbox: Sandbox | None = None,
  60. ):
  61. self.sid = sid
  62. if sandbox is None:
  63. self.sandbox = create_sandbox(sid, config.sandbox_type)
  64. self._is_external_sandbox = False
  65. else:
  66. self.sandbox = sandbox
  67. self._is_external_sandbox = True
  68. self.browser: BrowserEnv | None = None
  69. try:
  70. self.browser = BrowserEnv()
  71. except BrowserInitException:
  72. logger.warn(
  73. 'Failed to start browser environment, web browsing functionality will not work'
  74. )
  75. self.file_store = InMemoryFileStore()
  76. self.event_stream = event_stream
  77. self.event_stream.subscribe(EventStreamSubscriber.RUNTIME, self.on_event)
  78. self._bg_task = asyncio.create_task(self._start_background_observation_loop())
  79. def close(self):
  80. if not self._is_external_sandbox:
  81. self.sandbox.close()
  82. if self.browser is not None:
  83. self.browser.close()
  84. self._bg_task.cancel()
  85. def init_sandbox_plugins(self, plugins: list[PluginRequirement]) -> None:
  86. self.sandbox.init_plugins(plugins)
  87. async def on_event(self, event: Event) -> None:
  88. if isinstance(event, Action):
  89. observation = await self.run_action(event)
  90. observation._cause = event.id # type: ignore[attr-defined]
  91. source = event.source if event.source else EventSource.AGENT
  92. await self.event_stream.add_event(observation, source)
  93. async def run_action(self, action: Action) -> Observation:
  94. """
  95. Run an action and return the resulting observation.
  96. If the action is not runnable in any runtime, a NullObservation is returned.
  97. If the action is not supported by the current runtime, an ErrorObservation is returned.
  98. """
  99. if not action.runnable:
  100. return NullObservation('')
  101. action_type = action.action # type: ignore[attr-defined]
  102. if action_type not in ACTION_TYPE_TO_CLASS:
  103. return ErrorObservation(f'Action {action_type} does not exist.')
  104. if not hasattr(self, action_type):
  105. return ErrorObservation(
  106. f'Action {action_type} is not supported in the current runtime.'
  107. )
  108. observation = await getattr(self, action_type)(action)
  109. observation._parent = action.id # type: ignore[attr-defined]
  110. return observation
  111. async def _start_background_observation_loop(self):
  112. while True:
  113. await self.submit_background_obs()
  114. await asyncio.sleep(1)
  115. async def submit_background_obs(self):
  116. """
  117. Returns all observations that have accumulated in the runtime's background.
  118. Right now, this is just background commands, but could include e.g. asynchronous
  119. events happening in the browser.
  120. """
  121. for _id, cmd in self.sandbox.background_commands.items():
  122. output = cmd.read_logs()
  123. if output:
  124. await self.event_stream.add_event(
  125. CmdOutputObservation(
  126. content=output, command_id=_id, command=cmd.command
  127. ),
  128. EventSource.AGENT, # FIXME: use the original action's source
  129. )
  130. await asyncio.sleep(1)
  131. @abstractmethod
  132. async def run(self, action: CmdRunAction) -> Observation:
  133. pass
  134. @abstractmethod
  135. async def kill(self, action: CmdKillAction) -> Observation:
  136. pass
  137. @abstractmethod
  138. async def run_ipython(self, action: IPythonRunCellAction) -> Observation:
  139. pass
  140. @abstractmethod
  141. async def read(self, action: FileReadAction) -> Observation:
  142. pass
  143. @abstractmethod
  144. async def write(self, action: FileWriteAction) -> Observation:
  145. pass
  146. @abstractmethod
  147. async def browse(self, action: BrowseURLAction) -> Observation:
  148. pass
  149. @abstractmethod
  150. async def browse_interactive(self, action: BrowseInteractiveAction) -> Observation:
  151. pass
  152. @abstractmethod
  153. async def recall(self, action: AgentRecallAction) -> Observation:
  154. pass