action_execution_server.py 22 KB

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