action_execution_server.py 23 KB

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