action_execution_server.py 22 KB

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