action_execution_server.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. """
  2. This is the main file for the runtime client.
  3. It is responsible for executing actions received from OpenHands backend and producing observations.
  4. NOTE: this will be executed inside the docker sandbox.
  5. """
  6. import argparse
  7. import asyncio
  8. import io
  9. import os
  10. import shutil
  11. import tempfile
  12. import time
  13. from contextlib import asynccontextmanager
  14. from pathlib import Path
  15. from zipfile import ZipFile
  16. from fastapi import Depends, FastAPI, HTTPException, Request, UploadFile
  17. from fastapi.exceptions import RequestValidationError
  18. from fastapi.responses import JSONResponse, StreamingResponse
  19. from fastapi.security import APIKeyHeader
  20. from pydantic import BaseModel
  21. from starlette.exceptions import HTTPException as StarletteHTTPException
  22. from uvicorn import run
  23. from openhands.core.logger import openhands_logger as logger
  24. from openhands.events.action import (
  25. Action,
  26. BrowseInteractiveAction,
  27. BrowseURLAction,
  28. CmdRunAction,
  29. FileReadAction,
  30. FileWriteAction,
  31. IPythonRunCellAction,
  32. )
  33. from openhands.events.observation import (
  34. CmdOutputObservation,
  35. ErrorObservation,
  36. FatalErrorObservation,
  37. FileReadObservation,
  38. FileWriteObservation,
  39. IPythonRunCellObservation,
  40. Observation,
  41. )
  42. from openhands.events.serialization import event_from_dict, event_to_dict
  43. from openhands.runtime.browser import browse
  44. from openhands.runtime.browser.browser_env import BrowserEnv
  45. from openhands.runtime.plugins import (
  46. ALL_PLUGINS,
  47. JupyterPlugin,
  48. Plugin,
  49. )
  50. from openhands.runtime.utils.bash import BashSession
  51. from openhands.runtime.utils.files import insert_lines, read_lines
  52. from openhands.runtime.utils.runtime_init import init_user_and_working_directory
  53. from openhands.utils.async_utils import wait_all
  54. class ActionRequest(BaseModel):
  55. action: dict
  56. ROOT_GID = 0
  57. INIT_COMMANDS = [
  58. 'git config --global user.name "openhands" && git config --global user.email "openhands@all-hands.dev" && alias git="git --no-pager"',
  59. ]
  60. SESSION_API_KEY = os.environ.get('SESSION_API_KEY')
  61. api_key_header = APIKeyHeader(name='X-Session-API-Key', auto_error=False)
  62. def verify_api_key(api_key: str = Depends(api_key_header)):
  63. if SESSION_API_KEY and api_key != SESSION_API_KEY:
  64. raise HTTPException(status_code=403, detail='Invalid API Key')
  65. return api_key
  66. class ActionExecutor:
  67. """ActionExecutor is running inside docker sandbox.
  68. It is responsible for executing actions received from OpenHands backend and producing observations.
  69. """
  70. def __init__(
  71. self,
  72. plugins_to_load: list[Plugin],
  73. work_dir: str,
  74. username: str,
  75. user_id: int,
  76. browsergym_eval_env: str | None,
  77. ) -> None:
  78. self.plugins_to_load = plugins_to_load
  79. self._initial_pwd = work_dir
  80. self.username = username
  81. self.user_id = user_id
  82. _updated_user_id = init_user_and_working_directory(
  83. username=username, user_id=self.user_id, initial_pwd=work_dir
  84. )
  85. if _updated_user_id is not None:
  86. self.user_id = _updated_user_id
  87. self.bash_session = BashSession(
  88. work_dir=work_dir,
  89. username=username,
  90. )
  91. self.lock = asyncio.Lock()
  92. self.plugins: dict[str, Plugin] = {}
  93. self.browser = BrowserEnv(browsergym_eval_env)
  94. self.start_time = time.time()
  95. self.last_execution_time = self.start_time
  96. @property
  97. def initial_pwd(self):
  98. return self._initial_pwd
  99. async def ainit(self):
  100. await wait_all(self._init_plugin(plugin) for plugin in self.plugins_to_load)
  101. # This is a temporary workaround
  102. # TODO: refactor AgentSkills to be part of JupyterPlugin
  103. # AFTER ServerRuntime is deprecated
  104. if 'agent_skills' in self.plugins and 'jupyter' in self.plugins:
  105. obs = await self.run_ipython(
  106. IPythonRunCellAction(
  107. code='from openhands.runtime.plugins.agent_skills.agentskills import *\n'
  108. )
  109. )
  110. logger.debug(f'AgentSkills initialized: {obs}')
  111. await self._init_bash_commands()
  112. logger.debug('Runtime client initialized.')
  113. async def _init_plugin(self, plugin: Plugin):
  114. await plugin.initialize(self.username)
  115. self.plugins[plugin.name] = plugin
  116. logger.debug(f'Initializing plugin: {plugin.name}')
  117. if isinstance(plugin, JupyterPlugin):
  118. await self.run_ipython(
  119. IPythonRunCellAction(
  120. code=f'import os; os.chdir("{self.bash_session.pwd}")'
  121. )
  122. )
  123. async def _init_bash_commands(self):
  124. logger.debug(f'Initializing by running {len(INIT_COMMANDS)} bash commands...')
  125. for command in INIT_COMMANDS:
  126. action = CmdRunAction(command=command)
  127. action.timeout = 300
  128. logger.debug(f'Executing init command: {command}')
  129. obs = await self.run(action)
  130. assert isinstance(obs, CmdOutputObservation)
  131. logger.debug(
  132. f'Init command outputs (exit code: {obs.exit_code}): {obs.content}'
  133. )
  134. assert obs.exit_code == 0
  135. logger.debug('Bash init commands completed')
  136. async def run_action(self, action) -> Observation:
  137. async with self.lock:
  138. action_type = action.action
  139. logger.debug(f'Running action:\n{action}')
  140. observation = await getattr(self, action_type)(action)
  141. logger.debug(f'Action output:\n{observation}')
  142. return observation
  143. async def run(
  144. self, action: CmdRunAction
  145. ) -> CmdOutputObservation | FatalErrorObservation:
  146. return self.bash_session.run(action)
  147. async def run_ipython(self, action: IPythonRunCellAction) -> Observation:
  148. if 'jupyter' in self.plugins:
  149. _jupyter_plugin: JupyterPlugin = self.plugins['jupyter'] # type: ignore
  150. # This is used to make AgentSkills in Jupyter aware of the
  151. # current working directory in Bash
  152. jupyter_pwd = getattr(self, '_jupyter_pwd', None)
  153. if self.bash_session.pwd != jupyter_pwd:
  154. logger.debug(
  155. f'{self.bash_session.pwd} != {jupyter_pwd} -> reset Jupyter PWD'
  156. )
  157. reset_jupyter_pwd_code = (
  158. f'import os; os.chdir("{self.bash_session.pwd}")'
  159. )
  160. _aux_action = IPythonRunCellAction(code=reset_jupyter_pwd_code)
  161. _reset_obs: IPythonRunCellObservation = await _jupyter_plugin.run(
  162. _aux_action
  163. )
  164. logger.debug(
  165. f'Changed working directory in IPython to: {self.bash_session.pwd}. Output: {_reset_obs}'
  166. )
  167. self._jupyter_pwd = self.bash_session.pwd
  168. obs: IPythonRunCellObservation = await _jupyter_plugin.run(action)
  169. obs.content = obs.content.rstrip()
  170. if action.include_extra:
  171. obs.content += (
  172. f'\n[Jupyter current working directory: {self.bash_session.pwd}]'
  173. )
  174. obs.content += f'\n[Jupyter Python interpreter: {_jupyter_plugin.python_interpreter_path}]'
  175. return obs
  176. else:
  177. raise RuntimeError(
  178. 'JupyterRequirement not found. Unable to run IPython action.'
  179. )
  180. def _resolve_path(self, path: str, working_dir: str) -> str:
  181. filepath = Path(path)
  182. if not filepath.is_absolute():
  183. return str(Path(working_dir) / filepath)
  184. return str(filepath)
  185. async def read(self, action: FileReadAction) -> Observation:
  186. # NOTE: the client code is running inside the sandbox,
  187. # so there's no need to check permission
  188. working_dir = self.bash_session.workdir
  189. filepath = self._resolve_path(action.path, working_dir)
  190. try:
  191. with open(filepath, 'r', encoding='utf-8') as file:
  192. lines = read_lines(file.readlines(), action.start, action.end)
  193. except FileNotFoundError:
  194. return ErrorObservation(
  195. f'File not found: {filepath}. Your current working directory is {working_dir}.'
  196. )
  197. except UnicodeDecodeError:
  198. return ErrorObservation(f'File could not be decoded as utf-8: {filepath}.')
  199. except IsADirectoryError:
  200. return ErrorObservation(
  201. f'Path is a directory: {filepath}. You can only read files'
  202. )
  203. code_view = ''.join(lines)
  204. return FileReadObservation(path=filepath, content=code_view)
  205. async def write(self, action: FileWriteAction) -> Observation:
  206. working_dir = self.bash_session.workdir
  207. filepath = self._resolve_path(action.path, working_dir)
  208. insert = action.content.split('\n')
  209. try:
  210. if not os.path.exists(os.path.dirname(filepath)):
  211. os.makedirs(os.path.dirname(filepath))
  212. file_exists = os.path.exists(filepath)
  213. if file_exists:
  214. file_stat = os.stat(filepath)
  215. else:
  216. file_stat = None
  217. mode = 'w' if not file_exists else 'r+'
  218. try:
  219. with open(filepath, mode, encoding='utf-8') as file:
  220. if mode != 'w':
  221. all_lines = file.readlines()
  222. new_file = insert_lines(
  223. insert, all_lines, action.start, action.end
  224. )
  225. else:
  226. new_file = [i + '\n' for i in insert]
  227. file.seek(0)
  228. file.writelines(new_file)
  229. file.truncate()
  230. # Handle file permissions
  231. if file_exists:
  232. assert file_stat is not None
  233. # restore the original file permissions if the file already exists
  234. os.chmod(filepath, file_stat.st_mode)
  235. os.chown(filepath, file_stat.st_uid, file_stat.st_gid)
  236. else:
  237. # set the new file permissions if the file is new
  238. os.chmod(filepath, 0o664)
  239. os.chown(filepath, self.user_id, self.user_id)
  240. except FileNotFoundError:
  241. return ErrorObservation(f'File not found: {filepath}')
  242. except IsADirectoryError:
  243. return ErrorObservation(
  244. f'Path is a directory: {filepath}. You can only write to files'
  245. )
  246. except UnicodeDecodeError:
  247. return ErrorObservation(
  248. f'File could not be decoded as utf-8: {filepath}'
  249. )
  250. except PermissionError:
  251. return ErrorObservation(f'Malformed paths not permitted: {filepath}')
  252. return FileWriteObservation(content='', path=filepath)
  253. async def browse(self, action: BrowseURLAction) -> Observation:
  254. return await browse(action, self.browser)
  255. async def browse_interactive(self, action: BrowseInteractiveAction) -> Observation:
  256. return await browse(action, self.browser)
  257. def close(self):
  258. self.bash_session.close()
  259. self.browser.close()
  260. if __name__ == '__main__':
  261. parser = argparse.ArgumentParser()
  262. parser.add_argument('port', type=int, help='Port to listen on')
  263. parser.add_argument('--working-dir', type=str, help='Working directory')
  264. parser.add_argument('--plugins', type=str, help='Plugins to initialize', nargs='+')
  265. parser.add_argument(
  266. '--username', type=str, help='User to run as', default='openhands'
  267. )
  268. parser.add_argument('--user-id', type=int, help='User ID to run as', default=1000)
  269. parser.add_argument(
  270. '--browsergym-eval-env',
  271. type=str,
  272. help='BrowserGym environment used for browser evaluation',
  273. default=None,
  274. )
  275. # example: python client.py 8000 --working-dir /workspace --plugins JupyterRequirement
  276. args = parser.parse_args()
  277. plugins_to_load: list[Plugin] = []
  278. if args.plugins:
  279. for plugin in args.plugins:
  280. if plugin not in ALL_PLUGINS:
  281. raise ValueError(f'Plugin {plugin} not found')
  282. plugins_to_load.append(ALL_PLUGINS[plugin]()) # type: ignore
  283. client: ActionExecutor | None = None
  284. @asynccontextmanager
  285. async def lifespan(app: FastAPI):
  286. global client
  287. client = ActionExecutor(
  288. plugins_to_load,
  289. work_dir=args.working_dir,
  290. username=args.username,
  291. user_id=args.user_id,
  292. browsergym_eval_env=args.browsergym_eval_env,
  293. )
  294. await client.ainit()
  295. yield
  296. # Clean up & release the resources
  297. client.close()
  298. app = FastAPI(lifespan=lifespan)
  299. # TODO below 3 exception handlers were recommended by Sonnet.
  300. # Are these something we should keep?
  301. @app.exception_handler(Exception)
  302. async def global_exception_handler(request: Request, exc: Exception):
  303. logger.exception('Unhandled exception occurred:')
  304. return JSONResponse(
  305. status_code=500,
  306. content={
  307. 'message': 'An unexpected error occurred. Please try again later.'
  308. },
  309. )
  310. @app.exception_handler(StarletteHTTPException)
  311. async def http_exception_handler(request: Request, exc: StarletteHTTPException):
  312. logger.error(f'HTTP exception occurred: {exc.detail}')
  313. return JSONResponse(
  314. status_code=exc.status_code, content={'message': exc.detail}
  315. )
  316. @app.exception_handler(RequestValidationError)
  317. async def validation_exception_handler(
  318. request: Request, exc: RequestValidationError
  319. ):
  320. logger.error(f'Validation error occurred: {exc}')
  321. return JSONResponse(
  322. status_code=422,
  323. content={'message': 'Invalid request parameters', 'details': exc.errors()},
  324. )
  325. @app.middleware('http')
  326. async def authenticate_requests(request: Request, call_next):
  327. if request.url.path != '/alive' and request.url.path != '/server_info':
  328. try:
  329. verify_api_key(request.headers.get('X-Session-API-Key'))
  330. except HTTPException as e:
  331. return e
  332. response = await call_next(request)
  333. return response
  334. @app.get('/server_info')
  335. async def get_server_info():
  336. assert client is not None
  337. current_time = time.time()
  338. uptime = current_time - client.start_time
  339. idle_time = current_time - client.last_execution_time
  340. return {'uptime': uptime, 'idle_time': idle_time}
  341. @app.post('/execute_action')
  342. async def execute_action(action_request: ActionRequest):
  343. assert client is not None
  344. try:
  345. action = event_from_dict(action_request.action)
  346. if not isinstance(action, Action):
  347. raise HTTPException(status_code=400, detail='Invalid action type')
  348. client.last_execution_time = time.time()
  349. observation = await client.run_action(action)
  350. return event_to_dict(observation)
  351. except Exception as e:
  352. logger.error(
  353. f'Error processing command: {str(e)}', exc_info=True, stack_info=True
  354. )
  355. raise HTTPException(status_code=500, detail=str(e))
  356. @app.post('/upload_file')
  357. async def upload_file(
  358. file: UploadFile, destination: str = '/', recursive: bool = False
  359. ):
  360. assert client is not None
  361. try:
  362. # Ensure the destination directory exists
  363. if not os.path.isabs(destination):
  364. raise HTTPException(
  365. status_code=400, detail='Destination must be an absolute path'
  366. )
  367. full_dest_path = destination
  368. if not os.path.exists(full_dest_path):
  369. os.makedirs(full_dest_path, exist_ok=True)
  370. if recursive or file.filename.endswith('.zip'):
  371. # For recursive uploads, we expect a zip file
  372. if not file.filename.endswith('.zip'):
  373. raise HTTPException(
  374. status_code=400, detail='Recursive uploads must be zip files'
  375. )
  376. zip_path = os.path.join(full_dest_path, file.filename)
  377. with open(zip_path, 'wb') as buffer:
  378. shutil.copyfileobj(file.file, buffer)
  379. # Extract the zip file
  380. shutil.unpack_archive(zip_path, full_dest_path)
  381. os.remove(zip_path) # Remove the zip file after extraction
  382. logger.debug(
  383. f'Uploaded file {file.filename} and extracted to {destination}'
  384. )
  385. else:
  386. # For single file uploads
  387. file_path = os.path.join(full_dest_path, file.filename)
  388. with open(file_path, 'wb') as buffer:
  389. shutil.copyfileobj(file.file, buffer)
  390. logger.debug(f'Uploaded file {file.filename} to {destination}')
  391. return JSONResponse(
  392. content={
  393. 'filename': file.filename,
  394. 'destination': destination,
  395. 'recursive': recursive,
  396. },
  397. status_code=200,
  398. )
  399. except Exception as e:
  400. raise HTTPException(status_code=500, detail=str(e))
  401. @app.get('/download_files')
  402. async def download_file(path: str):
  403. logger.debug('Downloading files')
  404. try:
  405. if not os.path.isabs(path):
  406. raise HTTPException(
  407. status_code=400, detail='Path must be an absolute path'
  408. )
  409. if not os.path.exists(path):
  410. raise HTTPException(status_code=404, detail='File not found')
  411. with tempfile.TemporaryFile() as temp_zip:
  412. with ZipFile(temp_zip, 'w') as zipf:
  413. for root, _, files in os.walk(path):
  414. for file in files:
  415. file_path = os.path.join(root, file)
  416. zipf.write(
  417. file_path, arcname=os.path.relpath(file_path, path)
  418. )
  419. temp_zip.seek(0) # Rewind the file to the beginning after writing
  420. content = temp_zip.read()
  421. # Good for small to medium-sized files. For very large files, streaming directly from the
  422. # file chunks may be more memory-efficient.
  423. zip_stream = io.BytesIO(content)
  424. return StreamingResponse(
  425. content=zip_stream,
  426. media_type='application/zip',
  427. headers={'Content-Disposition': f'attachment; filename={path}.zip'},
  428. )
  429. except Exception as e:
  430. raise HTTPException(status_code=500, detail=str(e))
  431. @app.get('/alive')
  432. async def alive():
  433. return {'status': 'ok'}
  434. # ================================
  435. # File-specific operations for UI
  436. # ================================
  437. @app.post('/list_files')
  438. async def list_files(request: Request):
  439. """List files in the specified path.
  440. This function retrieves a list of files from the agent's runtime file store,
  441. excluding certain system and hidden files/directories.
  442. To list files:
  443. ```sh
  444. curl http://localhost:3000/api/list-files
  445. ```
  446. Args:
  447. request (Request): The incoming request object.
  448. path (str, optional): The path to list files from. Defaults to '/'.
  449. Returns:
  450. list: A list of file names in the specified path.
  451. Raises:
  452. HTTPException: If there's an error listing the files.
  453. """
  454. assert client is not None
  455. # get request as dict
  456. request_dict = await request.json()
  457. path = request_dict.get('path', None)
  458. # Get the full path of the requested directory
  459. if path is None:
  460. full_path = client.initial_pwd
  461. elif os.path.isabs(path):
  462. full_path = path
  463. else:
  464. full_path = os.path.join(client.initial_pwd, path)
  465. if not os.path.exists(full_path):
  466. # if user just removed a folder, prevent server error 500 in UI
  467. return []
  468. try:
  469. # Check if the directory exists
  470. if not os.path.exists(full_path) or not os.path.isdir(full_path):
  471. return []
  472. entries = os.listdir(full_path)
  473. # Separate directories and files
  474. directories = []
  475. files = []
  476. for entry in entries:
  477. # Remove leading slash and any parent directory components
  478. entry_relative = entry.lstrip('/').split('/')[-1]
  479. # Construct the full path by joining the base path with the relative entry path
  480. full_entry_path = os.path.join(full_path, entry_relative)
  481. if os.path.exists(full_entry_path):
  482. is_dir = os.path.isdir(full_entry_path)
  483. if is_dir:
  484. # add trailing slash to directories
  485. # required by FE to differentiate directories and files
  486. entry = entry.rstrip('/') + '/'
  487. directories.append(entry)
  488. else:
  489. files.append(entry)
  490. # Sort directories and files separately
  491. directories.sort(key=lambda s: s.lower())
  492. files.sort(key=lambda s: s.lower())
  493. # Combine sorted directories and files
  494. sorted_entries = directories + files
  495. return sorted_entries
  496. except Exception as e:
  497. logger.error(f'Error listing files: {e}', exc_info=True)
  498. return []
  499. logger.debug(f'Starting action execution API on port {args.port}')
  500. run(app, host='0.0.0.0', port=args.port)