action_execution_server.py 24 KB

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