base.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. import atexit
  2. import copy
  3. import json
  4. import os
  5. from abc import abstractmethod
  6. from pathlib import Path
  7. from typing import Callable
  8. from requests.exceptions import ConnectionError
  9. from openhands.core.config import AppConfig, SandboxConfig
  10. from openhands.core.logger import openhands_logger as logger
  11. from openhands.events import EventSource, EventStream, EventStreamSubscriber
  12. from openhands.events.action import (
  13. Action,
  14. ActionConfirmationStatus,
  15. BrowseInteractiveAction,
  16. BrowseURLAction,
  17. CmdRunAction,
  18. FileReadAction,
  19. FileWriteAction,
  20. IPythonRunCellAction,
  21. )
  22. from openhands.events.event import Event
  23. from openhands.events.observation import (
  24. CmdOutputObservation,
  25. ErrorObservation,
  26. NullObservation,
  27. Observation,
  28. UserRejectObservation,
  29. )
  30. from openhands.events.serialization.action import ACTION_TYPE_TO_CLASS
  31. from openhands.runtime.plugins import (
  32. JupyterRequirement,
  33. PluginRequirement,
  34. VSCodeRequirement,
  35. )
  36. from openhands.runtime.utils.edit import FileEditRuntimeMixin
  37. from openhands.utils.async_utils import call_sync_from_async
  38. STATUS_MESSAGES = {
  39. 'STATUS$STARTING_RUNTIME': 'Starting runtime...',
  40. 'STATUS$STARTING_CONTAINER': 'Starting container...',
  41. 'STATUS$PREPARING_CONTAINER': 'Preparing container...',
  42. 'STATUS$CONTAINER_STARTED': 'Container started.',
  43. 'STATUS$WAITING_FOR_CLIENT': 'Waiting for client...',
  44. }
  45. class RuntimeNotReadyError(Exception):
  46. pass
  47. class RuntimeDisconnectedError(Exception):
  48. pass
  49. def _default_env_vars(sandbox_config: SandboxConfig) -> dict[str, str]:
  50. ret = {}
  51. for key in os.environ:
  52. if key.startswith('SANDBOX_ENV_'):
  53. sandbox_key = key.removeprefix('SANDBOX_ENV_')
  54. ret[sandbox_key] = os.environ[key]
  55. if sandbox_config.enable_auto_lint:
  56. ret['ENABLE_AUTO_LINT'] = 'true'
  57. return ret
  58. class Runtime(FileEditRuntimeMixin):
  59. """The runtime is how the agent interacts with the external environment.
  60. This includes a bash sandbox, a browser, and filesystem interactions.
  61. sid is the session id, which is used to identify the current user session.
  62. """
  63. sid: str
  64. config: AppConfig
  65. initial_env_vars: dict[str, str]
  66. attach_to_existing: bool
  67. status_callback: Callable | None
  68. def __init__(
  69. self,
  70. config: AppConfig,
  71. event_stream: EventStream,
  72. sid: str = 'default',
  73. plugins: list[PluginRequirement] | None = None,
  74. env_vars: dict[str, str] | None = None,
  75. status_callback: Callable | None = None,
  76. attach_to_existing: bool = False,
  77. headless_mode: bool = False,
  78. ):
  79. self.sid = sid
  80. self.event_stream = event_stream
  81. self.event_stream.subscribe(
  82. EventStreamSubscriber.RUNTIME, self.on_event, self.sid
  83. )
  84. self.plugins = (
  85. copy.deepcopy(plugins) if plugins is not None and len(plugins) > 0 else []
  86. )
  87. # add VSCode plugin if not in headless mode
  88. if not headless_mode:
  89. self.plugins.append(VSCodeRequirement())
  90. self.status_callback = status_callback
  91. self.attach_to_existing = attach_to_existing
  92. self.config = copy.deepcopy(config)
  93. atexit.register(self.close)
  94. self.initial_env_vars = _default_env_vars(config.sandbox)
  95. if env_vars is not None:
  96. self.initial_env_vars.update(env_vars)
  97. self._vscode_enabled = any(
  98. isinstance(plugin, VSCodeRequirement) for plugin in self.plugins
  99. )
  100. # Load mixins
  101. FileEditRuntimeMixin.__init__(self)
  102. def setup_initial_env(self) -> None:
  103. if self.attach_to_existing:
  104. return
  105. logger.debug(f'Adding env vars: {self.initial_env_vars}')
  106. self.add_env_vars(self.initial_env_vars)
  107. if self.config.sandbox.runtime_startup_env_vars:
  108. self.add_env_vars(self.config.sandbox.runtime_startup_env_vars)
  109. def close(self) -> None:
  110. pass
  111. def log(self, level: str, message: str) -> None:
  112. message = f'[runtime {self.sid}] {message}'
  113. getattr(logger, level)(message, stacklevel=2)
  114. def send_status_message(self, message_id: str):
  115. """Sends a status message if the callback function was provided."""
  116. if self.status_callback:
  117. msg = STATUS_MESSAGES.get(message_id, '')
  118. self.status_callback('info', message_id, msg)
  119. def send_error_message(self, message_id: str, message: str):
  120. if self.status_callback:
  121. self.status_callback('error', message_id, message)
  122. # ====================================================================
  123. def add_env_vars(self, env_vars: dict[str, str]) -> None:
  124. # Add env vars to the IPython shell (if Jupyter is used)
  125. if any(isinstance(plugin, JupyterRequirement) for plugin in self.plugins):
  126. code = 'import os\n'
  127. for key, value in env_vars.items():
  128. # Note: json.dumps gives us nice escaping for free
  129. code += f'os.environ["{key}"] = {json.dumps(value)}\n'
  130. code += '\n'
  131. obs = self.run_ipython(IPythonRunCellAction(code))
  132. self.log('debug', f'Added env vars to IPython: code={code}, obs={obs}')
  133. # Add env vars to the Bash shell
  134. cmd = ''
  135. for key, value in env_vars.items():
  136. # Note: json.dumps gives us nice escaping for free
  137. cmd += f'export {key}={json.dumps(value)}; '
  138. if not cmd:
  139. return
  140. cmd = cmd.strip()
  141. logger.debug(f'Adding env var: {cmd}')
  142. obs = self.run(CmdRunAction(cmd))
  143. if not isinstance(obs, CmdOutputObservation) or obs.exit_code != 0:
  144. raise RuntimeError(
  145. f'Failed to add env vars [{env_vars}] to environment: {obs.content}'
  146. )
  147. async def on_event(self, event: Event) -> None:
  148. if isinstance(event, Action):
  149. # set timeout to default if not set
  150. if event.timeout is None:
  151. event.timeout = self.config.sandbox.timeout
  152. assert event.timeout is not None
  153. try:
  154. observation: Observation = await call_sync_from_async(
  155. self.run_action, event
  156. )
  157. except Exception as e:
  158. err_id = ''
  159. if isinstance(e, ConnectionError) or isinstance(
  160. e, RuntimeDisconnectedError
  161. ):
  162. err_id = 'STATUS$ERROR_RUNTIME_DISCONNECTED'
  163. self.log('error', f'Unexpected error while running action {e}')
  164. self.log('error', f'Problematic action: {str(event)}')
  165. self.send_error_message(err_id, str(e))
  166. self.close()
  167. return
  168. observation._cause = event.id # type: ignore[attr-defined]
  169. observation.tool_call_metadata = event.tool_call_metadata
  170. # this might be unnecessary, since source should be set by the event stream when we're here
  171. source = event.source if event.source else EventSource.AGENT
  172. self.event_stream.add_event(observation, source) # type: ignore[arg-type]
  173. def run_action(self, action: Action) -> Observation:
  174. """Run an action and return the resulting observation.
  175. If the action is not runnable in any runtime, a NullObservation is returned.
  176. If the action is not supported by the current runtime, an ErrorObservation is returned.
  177. """
  178. if not action.runnable:
  179. return NullObservation('')
  180. if (
  181. hasattr(action, 'confirmation_state')
  182. and action.confirmation_state
  183. == ActionConfirmationStatus.AWAITING_CONFIRMATION
  184. ):
  185. return NullObservation('')
  186. action_type = action.action # type: ignore[attr-defined]
  187. if action_type not in ACTION_TYPE_TO_CLASS:
  188. return ErrorObservation(f'Action {action_type} does not exist.')
  189. if not hasattr(self, action_type):
  190. return ErrorObservation(
  191. f'Action {action_type} is not supported in the current runtime.'
  192. )
  193. if (
  194. getattr(action, 'confirmation_state', None)
  195. == ActionConfirmationStatus.REJECTED
  196. ):
  197. return UserRejectObservation(
  198. 'Action has been rejected by the user! Waiting for further user input.'
  199. )
  200. observation = getattr(self, action_type)(action)
  201. return observation
  202. # ====================================================================
  203. # Context manager
  204. # ====================================================================
  205. def __enter__(self) -> 'Runtime':
  206. return self
  207. def __exit__(self, exc_type, exc_value, traceback) -> None:
  208. self.close()
  209. @abstractmethod
  210. async def connect(self) -> None:
  211. pass
  212. # ====================================================================
  213. # Action execution
  214. # ====================================================================
  215. @abstractmethod
  216. def run(self, action: CmdRunAction) -> Observation:
  217. pass
  218. @abstractmethod
  219. def run_ipython(self, action: IPythonRunCellAction) -> Observation:
  220. pass
  221. @abstractmethod
  222. def read(self, action: FileReadAction) -> Observation:
  223. pass
  224. @abstractmethod
  225. def write(self, action: FileWriteAction) -> Observation:
  226. pass
  227. @abstractmethod
  228. def browse(self, action: BrowseURLAction) -> Observation:
  229. pass
  230. @abstractmethod
  231. def browse_interactive(self, action: BrowseInteractiveAction) -> Observation:
  232. pass
  233. # ====================================================================
  234. # File operations
  235. # ====================================================================
  236. @abstractmethod
  237. def copy_to(self, host_src: str, sandbox_dest: str, recursive: bool = False):
  238. raise NotImplementedError('This method is not implemented in the base class.')
  239. @abstractmethod
  240. def list_files(self, path: str | None = None) -> list[str]:
  241. """List files in the sandbox.
  242. If path is None, list files in the sandbox's initial working directory (e.g., /workspace).
  243. """
  244. raise NotImplementedError('This method is not implemented in the base class.')
  245. @abstractmethod
  246. def copy_from(self, path: str) -> Path:
  247. """Zip all files in the sandbox and return a path in the local filesystem."""
  248. raise NotImplementedError('This method is not implemented in the base class.')
  249. # ====================================================================
  250. # VSCode
  251. # ====================================================================
  252. @property
  253. def vscode_enabled(self) -> bool:
  254. return self._vscode_enabled
  255. @property
  256. def vscode_url(self) -> str | None:
  257. raise NotImplementedError('This method is not implemented in the base class.')