action_execution_server.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  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 call_sync_from_async, 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. obs = await call_sync_from_async(self.bash_session.run, action)
  148. return obs
  149. async def run_ipython(self, action: IPythonRunCellAction) -> Observation:
  150. if 'jupyter' in self.plugins:
  151. _jupyter_plugin: JupyterPlugin = self.plugins['jupyter'] # type: ignore
  152. # This is used to make AgentSkills in Jupyter aware of the
  153. # current working directory in Bash
  154. jupyter_pwd = getattr(self, '_jupyter_pwd', None)
  155. if self.bash_session.pwd != jupyter_pwd:
  156. logger.debug(
  157. f'{self.bash_session.pwd} != {jupyter_pwd} -> reset Jupyter PWD'
  158. )
  159. reset_jupyter_pwd_code = (
  160. f'import os; os.chdir("{self.bash_session.pwd}")'
  161. )
  162. _aux_action = IPythonRunCellAction(code=reset_jupyter_pwd_code)
  163. _reset_obs: IPythonRunCellObservation = await _jupyter_plugin.run(
  164. _aux_action
  165. )
  166. logger.debug(
  167. f'Changed working directory in IPython to: {self.bash_session.pwd}. Output: {_reset_obs}'
  168. )
  169. self._jupyter_pwd = self.bash_session.pwd
  170. obs: IPythonRunCellObservation = await _jupyter_plugin.run(action)
  171. obs.content = obs.content.rstrip()
  172. if action.include_extra:
  173. obs.content += (
  174. f'\n[Jupyter current working directory: {self.bash_session.pwd}]'
  175. )
  176. obs.content += f'\n[Jupyter Python interpreter: {_jupyter_plugin.python_interpreter_path}]'
  177. return obs
  178. else:
  179. raise RuntimeError(
  180. 'JupyterRequirement not found. Unable to run IPython action.'
  181. )
  182. def _resolve_path(self, path: str, working_dir: str) -> str:
  183. filepath = Path(path)
  184. if not filepath.is_absolute():
  185. return str(Path(working_dir) / filepath)
  186. return str(filepath)
  187. async def read(self, action: FileReadAction) -> Observation:
  188. # NOTE: the client code is running inside the sandbox,
  189. # so there's no need to check permission
  190. working_dir = self.bash_session.workdir
  191. filepath = self._resolve_path(action.path, working_dir)
  192. try:
  193. if filepath.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
  194. with open(filepath, 'rb') as file:
  195. image_data = file.read()
  196. encoded_image = base64.b64encode(image_data).decode('utf-8')
  197. mime_type, _ = mimetypes.guess_type(filepath)
  198. if mime_type is None:
  199. mime_type = 'image/png' # default to PNG if mime type cannot be determined
  200. encoded_image = f'data:{mime_type};base64,{encoded_image}'
  201. return FileReadObservation(path=filepath, content=encoded_image)
  202. elif filepath.lower().endswith('.pdf'):
  203. with open(filepath, 'rb') as file:
  204. pdf_data = file.read()
  205. encoded_pdf = base64.b64encode(pdf_data).decode('utf-8')
  206. encoded_pdf = f'data:application/pdf;base64,{encoded_pdf}'
  207. return FileReadObservation(path=filepath, content=encoded_pdf)
  208. elif filepath.lower().endswith(('.mp4', '.webm', '.ogg')):
  209. with open(filepath, 'rb') as file:
  210. video_data = file.read()
  211. encoded_video = base64.b64encode(video_data).decode('utf-8')
  212. mime_type, _ = mimetypes.guess_type(filepath)
  213. if mime_type is None:
  214. mime_type = 'video/mp4' # default to MP4 if MIME type cannot be determined
  215. encoded_video = f'data:{mime_type};base64,{encoded_video}'
  216. return FileReadObservation(path=filepath, content=encoded_video)
  217. with open(filepath, 'r', encoding='utf-8') as file:
  218. lines = read_lines(file.readlines(), action.start, action.end)
  219. except FileNotFoundError:
  220. return ErrorObservation(
  221. f'File not found: {filepath}. Your current working directory is {working_dir}.'
  222. )
  223. except UnicodeDecodeError:
  224. return ErrorObservation(f'File could not be decoded as utf-8: {filepath}.')
  225. except IsADirectoryError:
  226. return ErrorObservation(
  227. f'Path is a directory: {filepath}. You can only read files'
  228. )
  229. code_view = ''.join(lines)
  230. return FileReadObservation(path=filepath, content=code_view)
  231. async def write(self, action: FileWriteAction) -> Observation:
  232. working_dir = self.bash_session.workdir
  233. filepath = self._resolve_path(action.path, working_dir)
  234. insert = action.content.split('\n')
  235. try:
  236. if not os.path.exists(os.path.dirname(filepath)):
  237. os.makedirs(os.path.dirname(filepath))
  238. file_exists = os.path.exists(filepath)
  239. if file_exists:
  240. file_stat = os.stat(filepath)
  241. else:
  242. file_stat = None
  243. mode = 'w' if not file_exists else 'r+'
  244. try:
  245. with open(filepath, mode, encoding='utf-8') as file:
  246. if mode != 'w':
  247. all_lines = file.readlines()
  248. new_file = insert_lines(
  249. insert, all_lines, action.start, action.end
  250. )
  251. else:
  252. new_file = [i + '\n' for i in insert]
  253. file.seek(0)
  254. file.writelines(new_file)
  255. file.truncate()
  256. # Handle file permissions
  257. if file_exists:
  258. assert file_stat is not None
  259. # restore the original file permissions if the file already exists
  260. os.chmod(filepath, file_stat.st_mode)
  261. os.chown(filepath, file_stat.st_uid, file_stat.st_gid)
  262. else:
  263. # set the new file permissions if the file is new
  264. os.chmod(filepath, 0o664)
  265. os.chown(filepath, self.user_id, self.user_id)
  266. except FileNotFoundError:
  267. return ErrorObservation(f'File not found: {filepath}')
  268. except IsADirectoryError:
  269. return ErrorObservation(
  270. f'Path is a directory: {filepath}. You can only write to files'
  271. )
  272. except UnicodeDecodeError:
  273. return ErrorObservation(
  274. f'File could not be decoded as utf-8: {filepath}'
  275. )
  276. except PermissionError:
  277. return ErrorObservation(f'Malformed paths not permitted: {filepath}')
  278. return FileWriteObservation(content='', path=filepath)
  279. async def browse(self, action: BrowseURLAction) -> Observation:
  280. return await browse(action, self.browser)
  281. async def browse_interactive(self, action: BrowseInteractiveAction) -> Observation:
  282. return await browse(action, self.browser)
  283. def close(self):
  284. self.bash_session.close()
  285. self.browser.close()
  286. if __name__ == '__main__':
  287. parser = argparse.ArgumentParser()
  288. parser.add_argument('port', type=int, help='Port to listen on')
  289. parser.add_argument('--working-dir', type=str, help='Working directory')
  290. parser.add_argument('--plugins', type=str, help='Plugins to initialize', nargs='+')
  291. parser.add_argument(
  292. '--username', type=str, help='User to run as', default='openhands'
  293. )
  294. parser.add_argument('--user-id', type=int, help='User ID to run as', default=1000)
  295. parser.add_argument(
  296. '--browsergym-eval-env',
  297. type=str,
  298. help='BrowserGym environment used for browser evaluation',
  299. default=None,
  300. )
  301. # example: python client.py 8000 --working-dir /workspace --plugins JupyterRequirement
  302. args = parser.parse_args()
  303. os.environ['VSCODE_PORT'] = str(int(args.port) + 1)
  304. assert check_port_available(int(os.environ['VSCODE_PORT']))
  305. plugins_to_load: list[Plugin] = []
  306. if args.plugins:
  307. for plugin in args.plugins:
  308. if plugin not in ALL_PLUGINS:
  309. raise ValueError(f'Plugin {plugin} not found')
  310. plugins_to_load.append(ALL_PLUGINS[plugin]()) # type: ignore
  311. client: ActionExecutor | None = None
  312. @asynccontextmanager
  313. async def lifespan(app: FastAPI):
  314. global client
  315. client = ActionExecutor(
  316. plugins_to_load,
  317. work_dir=args.working_dir,
  318. username=args.username,
  319. user_id=args.user_id,
  320. browsergym_eval_env=args.browsergym_eval_env,
  321. )
  322. await client.ainit()
  323. yield
  324. # Clean up & release the resources
  325. client.close()
  326. app = FastAPI(lifespan=lifespan)
  327. # TODO below 3 exception handlers were recommended by Sonnet.
  328. # Are these something we should keep?
  329. @app.exception_handler(Exception)
  330. async def global_exception_handler(request: Request, exc: Exception):
  331. logger.exception('Unhandled exception occurred:')
  332. return JSONResponse(
  333. status_code=500,
  334. content={
  335. 'message': 'An unexpected error occurred. Please try again later.'
  336. },
  337. )
  338. @app.exception_handler(StarletteHTTPException)
  339. async def http_exception_handler(request: Request, exc: StarletteHTTPException):
  340. logger.error(f'HTTP exception occurred: {exc.detail}')
  341. return JSONResponse(
  342. status_code=exc.status_code, content={'message': exc.detail}
  343. )
  344. @app.exception_handler(RequestValidationError)
  345. async def validation_exception_handler(
  346. request: Request, exc: RequestValidationError
  347. ):
  348. logger.error(f'Validation error occurred: {exc}')
  349. return JSONResponse(
  350. status_code=422,
  351. content={'message': 'Invalid request parameters', 'details': exc.errors()},
  352. )
  353. @app.middleware('http')
  354. async def authenticate_requests(request: Request, call_next):
  355. if request.url.path != '/alive' and request.url.path != '/server_info':
  356. try:
  357. verify_api_key(request.headers.get('X-Session-API-Key'))
  358. except HTTPException as e:
  359. return e
  360. response = await call_next(request)
  361. return response
  362. @app.get('/server_info')
  363. async def get_server_info():
  364. assert client is not None
  365. current_time = time.time()
  366. uptime = current_time - client.start_time
  367. idle_time = current_time - client.last_execution_time
  368. return {'uptime': uptime, 'idle_time': idle_time}
  369. @app.post('/execute_action')
  370. async def execute_action(action_request: ActionRequest):
  371. assert client is not None
  372. try:
  373. action = event_from_dict(action_request.action)
  374. if not isinstance(action, Action):
  375. raise HTTPException(status_code=400, detail='Invalid action type')
  376. client.last_execution_time = time.time()
  377. observation = await client.run_action(action)
  378. return event_to_dict(observation)
  379. except Exception as e:
  380. logger.error(
  381. f'Error processing command: {str(e)}', exc_info=True, stack_info=True
  382. )
  383. raise HTTPException(status_code=500, detail=str(e))
  384. @app.post('/upload_file')
  385. async def upload_file(
  386. file: UploadFile, destination: str = '/', recursive: bool = False
  387. ):
  388. assert client is not None
  389. try:
  390. # Ensure the destination directory exists
  391. if not os.path.isabs(destination):
  392. raise HTTPException(
  393. status_code=400, detail='Destination must be an absolute path'
  394. )
  395. full_dest_path = destination
  396. if not os.path.exists(full_dest_path):
  397. os.makedirs(full_dest_path, exist_ok=True)
  398. if recursive or file.filename.endswith('.zip'):
  399. # For recursive uploads, we expect a zip file
  400. if not file.filename.endswith('.zip'):
  401. raise HTTPException(
  402. status_code=400, detail='Recursive uploads must be zip files'
  403. )
  404. zip_path = os.path.join(full_dest_path, file.filename)
  405. with open(zip_path, 'wb') as buffer:
  406. shutil.copyfileobj(file.file, buffer)
  407. # Extract the zip file
  408. shutil.unpack_archive(zip_path, full_dest_path)
  409. os.remove(zip_path) # Remove the zip file after extraction
  410. logger.debug(
  411. f'Uploaded file {file.filename} and extracted to {destination}'
  412. )
  413. else:
  414. # For single file uploads
  415. file_path = os.path.join(full_dest_path, file.filename)
  416. with open(file_path, 'wb') as buffer:
  417. shutil.copyfileobj(file.file, buffer)
  418. logger.debug(f'Uploaded file {file.filename} to {destination}')
  419. return JSONResponse(
  420. content={
  421. 'filename': file.filename,
  422. 'destination': destination,
  423. 'recursive': recursive,
  424. },
  425. status_code=200,
  426. )
  427. except Exception as e:
  428. raise HTTPException(status_code=500, detail=str(e))
  429. @app.get('/download_files')
  430. async def download_file(path: str):
  431. logger.debug('Downloading files')
  432. try:
  433. if not os.path.isabs(path):
  434. raise HTTPException(
  435. status_code=400, detail='Path must be an absolute path'
  436. )
  437. if not os.path.exists(path):
  438. raise HTTPException(status_code=404, detail='File not found')
  439. with tempfile.TemporaryFile() as temp_zip:
  440. with ZipFile(temp_zip, 'w') as zipf:
  441. for root, _, files in os.walk(path):
  442. for file in files:
  443. file_path = os.path.join(root, file)
  444. zipf.write(
  445. file_path, arcname=os.path.relpath(file_path, path)
  446. )
  447. temp_zip.seek(0) # Rewind the file to the beginning after writing
  448. content = temp_zip.read()
  449. # Good for small to medium-sized files. For very large files, streaming directly from the
  450. # file chunks may be more memory-efficient.
  451. zip_stream = io.BytesIO(content)
  452. return StreamingResponse(
  453. content=zip_stream,
  454. media_type='application/zip',
  455. headers={'Content-Disposition': f'attachment; filename={path}.zip'},
  456. )
  457. except Exception as e:
  458. raise HTTPException(status_code=500, detail=str(e))
  459. @app.get('/alive')
  460. async def alive():
  461. return {'status': 'ok'}
  462. # ================================
  463. # VSCode-specific operations
  464. # ================================
  465. @app.get('/vscode/connection_token')
  466. async def get_vscode_connection_token():
  467. assert client is not None
  468. if 'vscode' in client.plugins:
  469. plugin: VSCodePlugin = client.plugins['vscode'] # type: ignore
  470. return {'token': plugin.vscode_connection_token}
  471. else:
  472. return {'token': None}
  473. # ================================
  474. # File-specific operations for UI
  475. # ================================
  476. @app.post('/list_files')
  477. async def list_files(request: Request):
  478. """List files in the specified path.
  479. This function retrieves a list of files from the agent's runtime file store,
  480. excluding certain system and hidden files/directories.
  481. To list files:
  482. ```sh
  483. curl http://localhost:3000/api/list-files
  484. ```
  485. Args:
  486. request (Request): The incoming request object.
  487. path (str, optional): The path to list files from. Defaults to '/'.
  488. Returns:
  489. list: A list of file names in the specified path.
  490. Raises:
  491. HTTPException: If there's an error listing the files.
  492. """
  493. assert client is not None
  494. # get request as dict
  495. request_dict = await request.json()
  496. path = request_dict.get('path', None)
  497. # Get the full path of the requested directory
  498. if path is None:
  499. full_path = client.initial_pwd
  500. elif os.path.isabs(path):
  501. full_path = path
  502. else:
  503. full_path = os.path.join(client.initial_pwd, path)
  504. if not os.path.exists(full_path):
  505. # if user just removed a folder, prevent server error 500 in UI
  506. return []
  507. try:
  508. # Check if the directory exists
  509. if not os.path.exists(full_path) or not os.path.isdir(full_path):
  510. return []
  511. entries = os.listdir(full_path)
  512. # Separate directories and files
  513. directories = []
  514. files = []
  515. for entry in entries:
  516. # Remove leading slash and any parent directory components
  517. entry_relative = entry.lstrip('/').split('/')[-1]
  518. # Construct the full path by joining the base path with the relative entry path
  519. full_entry_path = os.path.join(full_path, entry_relative)
  520. if os.path.exists(full_entry_path):
  521. is_dir = os.path.isdir(full_entry_path)
  522. if is_dir:
  523. # add trailing slash to directories
  524. # required by FE to differentiate directories and files
  525. entry = entry.rstrip('/') + '/'
  526. directories.append(entry)
  527. else:
  528. files.append(entry)
  529. # Sort directories and files separately
  530. directories.sort(key=lambda s: s.lower())
  531. files.sort(key=lambda s: s.lower())
  532. # Combine sorted directories and files
  533. sorted_entries = directories + files
  534. return sorted_entries
  535. except Exception as e:
  536. logger.error(f'Error listing files: {e}', exc_info=True)
  537. return []
  538. logger.debug(f'Starting action execution API on port {args.port}')
  539. run(app, host='0.0.0.0', port=args.port)