action_execution_server.py 24 KB

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