base.py 10 KB

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