action_execution_server.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  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 ALL_PLUGINS, JupyterPlugin, Plugin, VSCodePlugin
  47. from openhands.runtime.utils.bash import BashSession
  48. from openhands.runtime.utils.files import insert_lines, read_lines
  49. from openhands.runtime.utils.runtime_init import init_user_and_working_directory
  50. from openhands.runtime.utils.system import check_port_available
  51. from openhands.utils.async_utils import wait_all
  52. class ActionRequest(BaseModel):
  53. action: dict
  54. ROOT_GID = 0
  55. INIT_COMMANDS = [
  56. 'git config --global user.name "openhands" && git config --global user.email "openhands@all-hands.dev" && alias git="git --no-pager"',
  57. ]
  58. SESSION_API_KEY = os.environ.get('SESSION_API_KEY')
  59. api_key_header = APIKeyHeader(name='X-Session-API-Key', auto_error=False)
  60. def verify_api_key(api_key: str = Depends(api_key_header)):
  61. if SESSION_API_KEY and api_key != SESSION_API_KEY:
  62. raise HTTPException(status_code=403, detail='Invalid API Key')
  63. return api_key
  64. class ActionExecutor:
  65. """ActionExecutor is running inside docker sandbox.
  66. It is responsible for executing actions received from OpenHands backend and producing observations.
  67. """
  68. def __init__(
  69. self,
  70. plugins_to_load: list[Plugin],
  71. work_dir: str,
  72. username: str,
  73. user_id: int,
  74. browsergym_eval_env: str | None,
  75. ) -> None:
  76. self.plugins_to_load = plugins_to_load
  77. self._initial_pwd = work_dir
  78. self.username = username
  79. self.user_id = user_id
  80. _updated_user_id = init_user_and_working_directory(
  81. username=username, user_id=self.user_id, initial_pwd=work_dir
  82. )
  83. if _updated_user_id is not None:
  84. self.user_id = _updated_user_id
  85. self.bash_session = BashSession(
  86. work_dir=work_dir,
  87. username=username,
  88. )
  89. self.lock = asyncio.Lock()
  90. self.plugins: dict[str, Plugin] = {}
  91. self.browser = BrowserEnv(browsergym_eval_env)
  92. self.start_time = time.time()
  93. self.last_execution_time = self.start_time
  94. @property
  95. def initial_pwd(self):
  96. return self._initial_pwd
  97. async def ainit(self):
  98. await wait_all(
  99. (self._init_plugin(plugin) for plugin in self.plugins_to_load),
  100. timeout=30,
  101. )
  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. os.environ['VSCODE_PORT'] = str(int(args.port) + 1)
  303. assert check_port_available(int(os.environ['VSCODE_PORT']))
  304. plugins_to_load: list[Plugin] = []
  305. if args.plugins:
  306. for plugin in args.plugins:
  307. if plugin not in ALL_PLUGINS:
  308. raise ValueError(f'Plugin {plugin} not found')
  309. plugins_to_load.append(ALL_PLUGINS[plugin]()) # type: ignore
  310. client: ActionExecutor | None = None
  311. @asynccontextmanager
  312. async def lifespan(app: FastAPI):
  313. global client
  314. client = ActionExecutor(
  315. plugins_to_load,
  316. work_dir=args.working_dir,
  317. username=args.username,
  318. user_id=args.user_id,
  319. browsergym_eval_env=args.browsergym_eval_env,
  320. )
  321. await client.ainit()
  322. yield
  323. # Clean up & release the resources
  324. client.close()
  325. app = FastAPI(lifespan=lifespan)
  326. # TODO below 3 exception handlers were recommended by Sonnet.
  327. # Are these something we should keep?
  328. @app.exception_handler(Exception)
  329. async def global_exception_handler(request: Request, exc: Exception):
  330. logger.exception('Unhandled exception occurred:')
  331. return JSONResponse(
  332. status_code=500,
  333. content={
  334. 'message': 'An unexpected error occurred. Please try again later.'
  335. },
  336. )
  337. @app.exception_handler(StarletteHTTPException)
  338. async def http_exception_handler(request: Request, exc: StarletteHTTPException):
  339. logger.error(f'HTTP exception occurred: {exc.detail}')
  340. return JSONResponse(
  341. status_code=exc.status_code, content={'message': exc.detail}
  342. )
  343. @app.exception_handler(RequestValidationError)
  344. async def validation_exception_handler(
  345. request: Request, exc: RequestValidationError
  346. ):
  347. logger.error(f'Validation error occurred: {exc}')
  348. return JSONResponse(
  349. status_code=422,
  350. content={'message': 'Invalid request parameters', 'details': exc.errors()},
  351. )
  352. @app.middleware('http')
  353. async def authenticate_requests(request: Request, call_next):
  354. if request.url.path != '/alive' and request.url.path != '/server_info':
  355. try:
  356. verify_api_key(request.headers.get('X-Session-API-Key'))
  357. except HTTPException as e:
  358. return e
  359. response = await call_next(request)
  360. return response
  361. @app.get('/server_info')
  362. async def get_server_info():
  363. assert client is not None
  364. current_time = time.time()
  365. uptime = current_time - client.start_time
  366. idle_time = current_time - client.last_execution_time
  367. return {'uptime': uptime, 'idle_time': idle_time}
  368. @app.post('/execute_action')
  369. async def execute_action(action_request: ActionRequest):
  370. assert client is not None
  371. try:
  372. action = event_from_dict(action_request.action)
  373. if not isinstance(action, Action):
  374. raise HTTPException(status_code=400, detail='Invalid action type')
  375. client.last_execution_time = time.time()
  376. observation = await client.run_action(action)
  377. return event_to_dict(observation)
  378. except Exception as e:
  379. logger.error(
  380. f'Error processing command: {str(e)}', exc_info=True, stack_info=True
  381. )
  382. raise HTTPException(status_code=500, detail=str(e))
  383. @app.post('/upload_file')
  384. async def upload_file(
  385. file: UploadFile, destination: str = '/', recursive: bool = False
  386. ):
  387. assert client is not None
  388. try:
  389. # Ensure the destination directory exists
  390. if not os.path.isabs(destination):
  391. raise HTTPException(
  392. status_code=400, detail='Destination must be an absolute path'
  393. )
  394. full_dest_path = destination
  395. if not os.path.exists(full_dest_path):
  396. os.makedirs(full_dest_path, exist_ok=True)
  397. if recursive or file.filename.endswith('.zip'):
  398. # For recursive uploads, we expect a zip file
  399. if not file.filename.endswith('.zip'):
  400. raise HTTPException(
  401. status_code=400, detail='Recursive uploads must be zip files'
  402. )
  403. zip_path = os.path.join(full_dest_path, file.filename)
  404. with open(zip_path, 'wb') as buffer:
  405. shutil.copyfileobj(file.file, buffer)
  406. # Extract the zip file
  407. shutil.unpack_archive(zip_path, full_dest_path)
  408. os.remove(zip_path) # Remove the zip file after extraction
  409. logger.debug(
  410. f'Uploaded file {file.filename} and extracted to {destination}'
  411. )
  412. else:
  413. # For single file uploads
  414. file_path = os.path.join(full_dest_path, file.filename)
  415. with open(file_path, 'wb') as buffer:
  416. shutil.copyfileobj(file.file, buffer)
  417. logger.debug(f'Uploaded file {file.filename} to {destination}')
  418. return JSONResponse(
  419. content={
  420. 'filename': file.filename,
  421. 'destination': destination,
  422. 'recursive': recursive,
  423. },
  424. status_code=200,
  425. )
  426. except Exception as e:
  427. raise HTTPException(status_code=500, detail=str(e))
  428. @app.get('/download_files')
  429. async def download_file(path: str):
  430. logger.debug('Downloading files')
  431. try:
  432. if not os.path.isabs(path):
  433. raise HTTPException(
  434. status_code=400, detail='Path must be an absolute path'
  435. )
  436. if not os.path.exists(path):
  437. raise HTTPException(status_code=404, detail='File not found')
  438. with tempfile.TemporaryFile() as temp_zip:
  439. with ZipFile(temp_zip, 'w') as zipf:
  440. for root, _, files in os.walk(path):
  441. for file in files:
  442. file_path = os.path.join(root, file)
  443. zipf.write(
  444. file_path, arcname=os.path.relpath(file_path, path)
  445. )
  446. temp_zip.seek(0) # Rewind the file to the beginning after writing
  447. content = temp_zip.read()
  448. # Good for small to medium-sized files. For very large files, streaming directly from the
  449. # file chunks may be more memory-efficient.
  450. zip_stream = io.BytesIO(content)
  451. return StreamingResponse(
  452. content=zip_stream,
  453. media_type='application/zip',
  454. headers={'Content-Disposition': f'attachment; filename={path}.zip'},
  455. )
  456. except Exception as e:
  457. raise HTTPException(status_code=500, detail=str(e))
  458. @app.get('/alive')
  459. async def alive():
  460. return {'status': 'ok'}
  461. # ================================
  462. # VSCode-specific operations
  463. # ================================
  464. @app.get('/vscode/connection_token')
  465. async def get_vscode_connection_token():
  466. assert client is not None
  467. if 'vscode' in client.plugins:
  468. plugin: VSCodePlugin = client.plugins['vscode'] # type: ignore
  469. return {'token': plugin.vscode_connection_token}
  470. else:
  471. return {'token': None}
  472. # ================================
  473. # File-specific operations for UI
  474. # ================================
  475. @app.post('/list_files')
  476. async def list_files(request: Request):
  477. """List files in the specified path.
  478. This function retrieves a list of files from the agent's runtime file store,
  479. excluding certain system and hidden files/directories.
  480. To list files:
  481. ```sh
  482. curl http://localhost:3000/api/list-files
  483. ```
  484. Args:
  485. request (Request): The incoming request object.
  486. path (str, optional): The path to list files from. Defaults to '/'.
  487. Returns:
  488. list: A list of file names in the specified path.
  489. Raises:
  490. HTTPException: If there's an error listing the files.
  491. """
  492. assert client is not None
  493. # get request as dict
  494. request_dict = await request.json()
  495. path = request_dict.get('path', None)
  496. # Get the full path of the requested directory
  497. if path is None:
  498. full_path = client.initial_pwd
  499. elif os.path.isabs(path):
  500. full_path = path
  501. else:
  502. full_path = os.path.join(client.initial_pwd, path)
  503. if not os.path.exists(full_path):
  504. # if user just removed a folder, prevent server error 500 in UI
  505. return []
  506. try:
  507. # Check if the directory exists
  508. if not os.path.exists(full_path) or not os.path.isdir(full_path):
  509. return []
  510. entries = os.listdir(full_path)
  511. # Separate directories and files
  512. directories = []
  513. files = []
  514. for entry in entries:
  515. # Remove leading slash and any parent directory components
  516. entry_relative = entry.lstrip('/').split('/')[-1]
  517. # Construct the full path by joining the base path with the relative entry path
  518. full_entry_path = os.path.join(full_path, entry_relative)
  519. if os.path.exists(full_entry_path):
  520. is_dir = os.path.isdir(full_entry_path)
  521. if is_dir:
  522. # add trailing slash to directories
  523. # required by FE to differentiate directories and files
  524. entry = entry.rstrip('/') + '/'
  525. directories.append(entry)
  526. else:
  527. files.append(entry)
  528. # Sort directories and files separately
  529. directories.sort(key=lambda s: s.lower())
  530. files.sort(key=lambda s: s.lower())
  531. # Combine sorted directories and files
  532. sorted_entries = directories + files
  533. return sorted_entries
  534. except Exception as e:
  535. logger.error(f'Error listing files: {e}', exc_info=True)
  536. return []
  537. logger.debug(f'Starting action execution API on port {args.port}')
  538. run(app, host='0.0.0.0', port=args.port)