runtime.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. import atexit
  2. import copy
  3. import json
  4. import os
  5. from abc import abstractmethod
  6. from typing import Callable
  7. from openhands.core.config import AppConfig, SandboxConfig
  8. from openhands.core.logger import openhands_logger as logger
  9. from openhands.events import EventSource, EventStream, EventStreamSubscriber
  10. from openhands.events.action import (
  11. Action,
  12. ActionConfirmationStatus,
  13. BrowseInteractiveAction,
  14. BrowseURLAction,
  15. CmdRunAction,
  16. FileReadAction,
  17. FileWriteAction,
  18. IPythonRunCellAction,
  19. )
  20. from openhands.events.event import Event
  21. from openhands.events.observation import (
  22. CmdOutputObservation,
  23. ErrorObservation,
  24. NullObservation,
  25. Observation,
  26. UserRejectObservation,
  27. )
  28. from openhands.events.serialization.action import ACTION_TYPE_TO_CLASS
  29. from openhands.runtime.plugins import JupyterRequirement, PluginRequirement
  30. from openhands.utils.async_utils import sync_from_async
  31. def _default_env_vars(sandbox_config: SandboxConfig) -> dict[str, str]:
  32. ret = {}
  33. for key in os.environ:
  34. if key.startswith('SANDBOX_ENV_'):
  35. sandbox_key = key.removeprefix('SANDBOX_ENV_')
  36. ret[sandbox_key] = os.environ[key]
  37. if sandbox_config.enable_auto_lint:
  38. ret['ENABLE_AUTO_LINT'] = 'true'
  39. return ret
  40. class Runtime:
  41. """The runtime is how the agent interacts with the external environment.
  42. This includes a bash sandbox, a browser, and filesystem interactions.
  43. sid is the session id, which is used to identify the current user session.
  44. """
  45. sid: str
  46. config: AppConfig
  47. initial_env_vars: dict[str, str]
  48. attach_to_existing: bool
  49. def __init__(
  50. self,
  51. config: AppConfig,
  52. event_stream: EventStream,
  53. sid: str = 'default',
  54. plugins: list[PluginRequirement] | None = None,
  55. env_vars: dict[str, str] | None = None,
  56. status_message_callback: Callable | None = None,
  57. attach_to_existing: bool = False,
  58. ):
  59. self.sid = sid
  60. self.event_stream = event_stream
  61. self.event_stream.subscribe(EventStreamSubscriber.RUNTIME, self.on_event)
  62. self.plugins = plugins if plugins is not None and len(plugins) > 0 else []
  63. self.status_message_callback = status_message_callback
  64. self.attach_to_existing = attach_to_existing
  65. self.config = copy.deepcopy(config)
  66. atexit.register(self.close)
  67. self.initial_env_vars = _default_env_vars(config.sandbox)
  68. if env_vars is not None:
  69. self.initial_env_vars.update(env_vars)
  70. def setup_initial_env(self) -> None:
  71. if self.attach_to_existing:
  72. return
  73. logger.debug(f'Adding env vars: {self.initial_env_vars}')
  74. self.add_env_vars(self.initial_env_vars)
  75. if self.config.sandbox.runtime_startup_env_vars:
  76. self.add_env_vars(self.config.sandbox.runtime_startup_env_vars)
  77. def close(self) -> None:
  78. pass
  79. # ====================================================================
  80. def add_env_vars(self, env_vars: dict[str, str]) -> None:
  81. # Add env vars to the IPython shell (if Jupyter is used)
  82. if any(isinstance(plugin, JupyterRequirement) for plugin in self.plugins):
  83. code = 'import os\n'
  84. for key, value in env_vars.items():
  85. # Note: json.dumps gives us nice escaping for free
  86. code += f'os.environ["{key}"] = {json.dumps(value)}\n'
  87. code += '\n'
  88. obs = self.run_ipython(IPythonRunCellAction(code))
  89. logger.info(f'Added env vars to IPython: code={code}, obs={obs}')
  90. # Add env vars to the Bash shell
  91. cmd = ''
  92. for key, value in env_vars.items():
  93. # Note: json.dumps gives us nice escaping for free
  94. cmd += f'export {key}={json.dumps(value)}; '
  95. if not cmd:
  96. return
  97. cmd = cmd.strip()
  98. logger.debug(f'Adding env var: {cmd}')
  99. obs = self.run(CmdRunAction(cmd))
  100. if not isinstance(obs, CmdOutputObservation) or obs.exit_code != 0:
  101. raise RuntimeError(
  102. f'Failed to add env vars [{env_vars}] to environment: {obs.content}'
  103. )
  104. async def on_event(self, event: Event) -> None:
  105. if isinstance(event, Action):
  106. # set timeout to default if not set
  107. if event.timeout is None:
  108. event.timeout = self.config.sandbox.timeout
  109. assert event.timeout is not None
  110. observation = await sync_from_async(self.run_action, event)
  111. observation._cause = event.id # type: ignore[attr-defined]
  112. source = event.source if event.source else EventSource.AGENT
  113. await self.event_stream.async_add_event(observation, source) # type: ignore[arg-type]
  114. def run_action(self, action: Action) -> Observation:
  115. """Run an action and return the resulting observation.
  116. If the action is not runnable in any runtime, a NullObservation is returned.
  117. If the action is not supported by the current runtime, an ErrorObservation is returned.
  118. """
  119. if not action.runnable:
  120. return NullObservation('')
  121. if (
  122. hasattr(action, 'is_confirmed')
  123. and action.is_confirmed == ActionConfirmationStatus.AWAITING_CONFIRMATION
  124. ):
  125. return NullObservation('')
  126. action_type = action.action # type: ignore[attr-defined]
  127. if action_type not in ACTION_TYPE_TO_CLASS:
  128. return ErrorObservation(f'Action {action_type} does not exist.')
  129. if not hasattr(self, action_type):
  130. return ErrorObservation(
  131. f'Action {action_type} is not supported in the current runtime.'
  132. )
  133. if (
  134. hasattr(action, 'is_confirmed')
  135. and action.is_confirmed == ActionConfirmationStatus.REJECTED
  136. ):
  137. return UserRejectObservation(
  138. 'Action has been rejected by the user! Waiting for further user input.'
  139. )
  140. observation = getattr(self, action_type)(action)
  141. return observation
  142. # ====================================================================
  143. # Context manager
  144. # ====================================================================
  145. def __enter__(self) -> 'Runtime':
  146. return self
  147. def __exit__(self, exc_type, exc_value, traceback) -> None:
  148. self.close()
  149. # ====================================================================
  150. # Action execution
  151. # ====================================================================
  152. @abstractmethod
  153. def run(self, action: CmdRunAction) -> Observation:
  154. pass
  155. @abstractmethod
  156. def run_ipython(self, action: IPythonRunCellAction) -> Observation:
  157. pass
  158. @abstractmethod
  159. def read(self, action: FileReadAction) -> Observation:
  160. pass
  161. @abstractmethod
  162. def write(self, action: FileWriteAction) -> Observation:
  163. pass
  164. @abstractmethod
  165. def browse(self, action: BrowseURLAction) -> Observation:
  166. pass
  167. @abstractmethod
  168. def browse_interactive(self, action: BrowseInteractiveAction) -> Observation:
  169. pass
  170. # ====================================================================
  171. # File operations
  172. # ====================================================================
  173. @abstractmethod
  174. def copy_to(self, host_src: str, sandbox_dest: str, recursive: bool = False):
  175. raise NotImplementedError('This method is not implemented in the base class.')
  176. @abstractmethod
  177. def list_files(self, path: str | None = None) -> list[str]:
  178. """List files in the sandbox.
  179. If path is None, list files in the sandbox's initial working directory (e.g., /workspace).
  180. """
  181. raise NotImplementedError('This method is not implemented in the base class.')
  182. @abstractmethod
  183. def copy_from(self, path: str) -> bytes:
  184. """Zip all files in the sandbox and return as a stream of bytes."""
  185. raise NotImplementedError('This method is not implemented in the base class.')