client.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  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 re
  11. import shutil
  12. import subprocess
  13. import tempfile
  14. import time
  15. from contextlib import asynccontextmanager
  16. from pathlib import Path
  17. from zipfile import ZipFile
  18. import pexpect
  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 (
  48. ALL_PLUGINS,
  49. JupyterPlugin,
  50. Plugin,
  51. )
  52. from openhands.runtime.utils import split_bash_commands
  53. from openhands.runtime.utils.files import insert_lines, read_lines
  54. from openhands.utils.async_utils import wait_all
  55. class ActionRequest(BaseModel):
  56. action: dict
  57. ROOT_GID = 0
  58. INIT_COMMANDS = [
  59. 'git config --global user.name "openhands" && git config --global user.email "openhands@all-hands.dev" && alias git="git --no-pager"',
  60. ]
  61. SOFT_TIMEOUT_SECONDS = 5
  62. SESSION_API_KEY = os.environ.get('SESSION_API_KEY')
  63. api_key_header = APIKeyHeader(name='X-Session-API-Key', auto_error=False)
  64. def verify_api_key(api_key: str = Depends(api_key_header)):
  65. if SESSION_API_KEY and api_key != SESSION_API_KEY:
  66. raise HTTPException(status_code=403, detail='Invalid API Key')
  67. return api_key
  68. class RuntimeClient:
  69. """RuntimeClient is running inside docker sandbox.
  70. It is responsible for executing actions received from OpenHands backend and producing observations.
  71. """
  72. def __init__(
  73. self,
  74. plugins_to_load: list[Plugin],
  75. work_dir: str,
  76. username: str,
  77. user_id: int,
  78. browsergym_eval_env: str | None,
  79. ) -> None:
  80. self.plugins_to_load = plugins_to_load
  81. self.username = username
  82. self.user_id = user_id
  83. self.pwd = work_dir # current PWD
  84. self._initial_pwd = work_dir
  85. self._init_user(self.username, self.user_id)
  86. self._init_bash_shell(self.pwd, self.username)
  87. self.lock = asyncio.Lock()
  88. self.plugins: dict[str, Plugin] = {}
  89. self.browser = BrowserEnv(browsergym_eval_env)
  90. self.start_time = time.time()
  91. self.last_execution_time = self.start_time
  92. @property
  93. def initial_pwd(self):
  94. return self._initial_pwd
  95. async def ainit(self):
  96. await wait_all(self._init_plugin(plugin) for plugin in self.plugins_to_load)
  97. # This is a temporary workaround
  98. # TODO: refactor AgentSkills to be part of JupyterPlugin
  99. # AFTER ServerRuntime is deprecated
  100. if 'agent_skills' in self.plugins and 'jupyter' in self.plugins:
  101. obs = await self.run_ipython(
  102. IPythonRunCellAction(
  103. code='from openhands.runtime.plugins.agent_skills.agentskills import *\n'
  104. )
  105. )
  106. logger.info(f'AgentSkills initialized: {obs}')
  107. await self._init_bash_commands()
  108. logger.info('Runtime client initialized.')
  109. async def _init_plugin(self, plugin: Plugin):
  110. await plugin.initialize(self.username)
  111. self.plugins[plugin.name] = plugin
  112. logger.info(f'Initializing plugin: {plugin.name}')
  113. if isinstance(plugin, JupyterPlugin):
  114. await self.run_ipython(
  115. IPythonRunCellAction(code=f'import os; os.chdir("{self.pwd}")')
  116. )
  117. def _init_user(self, username: str, user_id: int) -> None:
  118. """Create working directory and user if not exists.
  119. It performs the following steps effectively:
  120. * Creates the Working Directory:
  121. - Uses mkdir -p to create the directory.
  122. - Sets ownership to username:root.
  123. - Adjusts permissions to be readable and writable by group and others.
  124. * User Verification and Creation:
  125. - Checks if the user exists using id -u.
  126. - If the user exists with the correct UID, it skips creation.
  127. - If the UID differs, it logs a warning and updates self.user_id.
  128. - If the user doesn't exist, it proceeds to create the user.
  129. * Sudo Configuration:
  130. - Appends %sudo ALL=(ALL) NOPASSWD:ALL to /etc/sudoers to grant
  131. passwordless sudo access to the sudo group.
  132. - Adds the user to the sudo group with the useradd command, handling
  133. UID conflicts by incrementing the UID if necessary.
  134. """
  135. # First create the working directory, independent of the user
  136. logger.info(f'Client working directory: {self.initial_pwd}')
  137. command = f'umask 002; mkdir -p {self.initial_pwd}'
  138. output = subprocess.run(command, shell=True, capture_output=True)
  139. out_str = output.stdout.decode()
  140. command = f'chown -R {username}:root {self.initial_pwd}'
  141. output = subprocess.run(command, shell=True, capture_output=True)
  142. out_str += output.stdout.decode()
  143. command = f'chmod g+rw {self.initial_pwd}'
  144. output = subprocess.run(command, shell=True, capture_output=True)
  145. out_str += output.stdout.decode()
  146. logger.debug(f'Created working directory. Output: [{out_str}]')
  147. # Skip root since it is already created
  148. if username == 'root':
  149. return
  150. # Check if the username already exists
  151. existing_user_id = -1
  152. try:
  153. result = subprocess.run(
  154. f'id -u {username}', shell=True, check=True, capture_output=True
  155. )
  156. existing_user_id = int(result.stdout.decode().strip())
  157. # The user ID already exists, skip setup
  158. if existing_user_id == user_id:
  159. logger.debug(
  160. f'User `{username}` already has the provided UID {user_id}. Skipping user setup.'
  161. )
  162. else:
  163. logger.warning(
  164. f'User `{username}` already exists with UID {existing_user_id}. Skipping user setup.'
  165. )
  166. self.user_id = existing_user_id
  167. return
  168. except subprocess.CalledProcessError as e:
  169. # Returncode 1 indicates, that the user does not exist yet
  170. if e.returncode == 1:
  171. logger.debug(
  172. f'User `{username}` does not exist. Proceeding with user creation.'
  173. )
  174. else:
  175. logger.error(
  176. f'Error checking user `{username}`, skipping setup:\n{e}\n'
  177. )
  178. raise
  179. # Add sudoer
  180. sudoer_line = r"echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers"
  181. output = subprocess.run(sudoer_line, shell=True, capture_output=True)
  182. if output.returncode != 0:
  183. raise RuntimeError(f'Failed to add sudoer: {output.stderr.decode()}')
  184. logger.debug(f'Added sudoer successfully. Output: [{output.stdout.decode()}]')
  185. command = (
  186. f'useradd -rm -d /home/{username} -s /bin/bash '
  187. f'-g root -G sudo -u {user_id} {username}'
  188. )
  189. output = subprocess.run(command, shell=True, capture_output=True)
  190. if output.returncode == 0:
  191. logger.debug(
  192. f'Added user `{username}` successfully with UID {user_id}. Output: [{output.stdout.decode()}]'
  193. )
  194. else:
  195. raise RuntimeError(
  196. f'Failed to create user `{username}` with UID {user_id}. Output: [{output.stderr.decode()}]'
  197. )
  198. def _init_bash_shell(self, work_dir: str, username: str) -> None:
  199. self.shell = pexpect.spawn(
  200. f'su {username}',
  201. encoding='utf-8',
  202. echo=False,
  203. )
  204. self.__bash_PS1 = (
  205. r'[PEXPECT_BEGIN]\n'
  206. r'$(which python >/dev/null 2>&1 && echo "[Python Interpreter: $(which python)]\n")'
  207. r'\u@\h:\w\n'
  208. r'[PEXPECT_END]'
  209. )
  210. # This should NOT match "PS1=\u@\h:\w [PEXPECT]$" when `env` is executed
  211. self.__bash_expect_regex = r'\[PEXPECT_BEGIN\]\s*(.*?)\s*([a-z0-9_-]*)@([a-zA-Z0-9.-]*):(.+)\s*\[PEXPECT_END\]'
  212. # Set umask to allow group write permissions
  213. self.shell.sendline(f'umask 002; export PS1="{self.__bash_PS1}"; export PS2=""')
  214. self.shell.expect(self.__bash_expect_regex)
  215. self.shell.sendline(
  216. f'if [ ! -d "{work_dir}" ]; then mkdir -p "{work_dir}"; fi && cd "{work_dir}"'
  217. )
  218. self.shell.expect(self.__bash_expect_regex)
  219. logger.debug(
  220. f'Bash initialized. Working directory: {work_dir}. Output: [{self.shell.before}]'
  221. )
  222. # Ensure the group has write permissions on the working directory
  223. self.shell.sendline(f'chmod g+rw "{work_dir}"')
  224. self.shell.expect(self.__bash_expect_regex)
  225. async def _init_bash_commands(self):
  226. logger.info(f'Initializing by running {len(INIT_COMMANDS)} bash commands...')
  227. for command in INIT_COMMANDS:
  228. action = CmdRunAction(command=command)
  229. action.timeout = 300
  230. logger.debug(f'Executing init command: {command}')
  231. obs: CmdOutputObservation = await self.run(action)
  232. logger.debug(
  233. f'Init command outputs (exit code: {obs.exit_code}): {obs.content}'
  234. )
  235. assert obs.exit_code == 0
  236. logger.info('Bash init commands completed')
  237. def _get_bash_prompt_and_update_pwd(self):
  238. ps1 = self.shell.after
  239. if ps1 == pexpect.EOF:
  240. logger.error(f'Bash shell EOF! {self.shell.after=}, {self.shell.before=}')
  241. raise RuntimeError('Bash shell EOF')
  242. if ps1 == pexpect.TIMEOUT:
  243. logger.warning('Bash shell timeout')
  244. return ''
  245. # begin at the last occurrence of '[PEXPECT_BEGIN]'.
  246. # In multi-line bash commands, the prompt will be repeated
  247. # and the matched regex captures all of them
  248. # - we only want the last one (newest prompt)
  249. _begin_pos = ps1.rfind('[PEXPECT_BEGIN]')
  250. if _begin_pos != -1:
  251. ps1 = ps1[_begin_pos:]
  252. # parse the ps1 to get username, hostname, and working directory
  253. matched = re.match(self.__bash_expect_regex, ps1)
  254. assert (
  255. matched is not None
  256. ), f'Failed to parse bash prompt: {ps1}. This should not happen.'
  257. other_info, username, hostname, working_dir = matched.groups()
  258. working_dir = working_dir.rstrip()
  259. self.pwd = os.path.expanduser(working_dir)
  260. # re-assemble the prompt
  261. prompt = f'{other_info.strip()}\n{username}@{hostname}:{working_dir} '
  262. if username == 'root':
  263. prompt += '#'
  264. else:
  265. prompt += '$'
  266. return prompt + ' '
  267. def _execute_bash(
  268. self,
  269. command: str,
  270. timeout: int,
  271. keep_prompt: bool = True,
  272. kill_on_timeout: bool = True,
  273. ) -> tuple[str, int]:
  274. logger.debug(f'Executing command: {command}')
  275. self.shell.sendline(command)
  276. return self._continue_bash(
  277. timeout=timeout, keep_prompt=keep_prompt, kill_on_timeout=kill_on_timeout
  278. )
  279. def _interrupt_bash(
  280. self,
  281. action_timeout: int | None,
  282. interrupt_timeout: int | None = None,
  283. max_retries: int = 2,
  284. ) -> tuple[str, int]:
  285. interrupt_timeout = interrupt_timeout or 1 # default timeout for SIGINT
  286. # try to interrupt the bash shell use SIGINT
  287. while max_retries > 0:
  288. self.shell.sendintr() # send SIGINT to the shell
  289. logger.debug('Sent SIGINT to bash. Waiting for output...')
  290. try:
  291. self.shell.expect(self.__bash_expect_regex, timeout=interrupt_timeout)
  292. output = self.shell.before
  293. logger.debug(f'Received output after SIGINT: {output}')
  294. exit_code = 130 # SIGINT
  295. _additional_msg = ''
  296. if action_timeout is not None:
  297. _additional_msg = (
  298. f'Command timed out after {action_timeout} seconds. '
  299. )
  300. output += (
  301. '\r\n\r\n'
  302. + f'[{_additional_msg}SIGINT was sent to interrupt the command.]'
  303. )
  304. return output, exit_code
  305. except pexpect.TIMEOUT as e:
  306. logger.warning(f'Bash pexpect.TIMEOUT while waiting for SIGINT: {e}')
  307. max_retries -= 1
  308. # fall back to send control-z
  309. logger.error(
  310. 'Failed to get output after SIGINT. Max retries reached. Sending control-z...'
  311. )
  312. self.shell.sendcontrol('z')
  313. self.shell.expect(self.__bash_expect_regex)
  314. output = self.shell.before
  315. logger.debug(f'Received output after control-z: {output}')
  316. # Try to kill the job
  317. self.shell.sendline('kill -9 %1')
  318. self.shell.expect(self.__bash_expect_regex)
  319. logger.debug(f'Received output after killing job %1: {self.shell.before}')
  320. output += self.shell.before
  321. _additional_msg = ''
  322. if action_timeout is not None:
  323. _additional_msg = f'Command timed out after {action_timeout} seconds. '
  324. output += (
  325. '\r\n\r\n'
  326. + f'[{_additional_msg}SIGINT was sent to interrupt the command, but failed. The command was killed.]'
  327. )
  328. # Try to get the exit code again
  329. self.shell.sendline('echo $?')
  330. self.shell.expect(self.__bash_expect_regex)
  331. _exit_code_output = self.shell.before
  332. exit_code = self._parse_exit_code(_exit_code_output)
  333. return output, exit_code
  334. def _parse_exit_code(self, output: str) -> int:
  335. try:
  336. exit_code = int(output.strip().split()[0])
  337. except Exception:
  338. logger.error('Error getting exit code from bash script')
  339. # If we try to run an invalid shell script the output sometimes includes error text
  340. # rather than the error code - we assume this is an error
  341. exit_code = 2
  342. return exit_code
  343. def _continue_bash(
  344. self,
  345. timeout: int,
  346. keep_prompt: bool = True,
  347. kill_on_timeout: bool = True,
  348. ) -> tuple[str, int]:
  349. logger.debug(f'Continuing bash with timeout={timeout}')
  350. try:
  351. self.shell.expect(self.__bash_expect_regex, timeout=timeout)
  352. output = self.shell.before
  353. # Get exit code
  354. self.shell.sendline('echo $?')
  355. logger.debug('Requesting exit code...')
  356. self.shell.expect(self.__bash_expect_regex, timeout=timeout)
  357. _exit_code_output = self.shell.before
  358. exit_code = self._parse_exit_code(_exit_code_output)
  359. except pexpect.TIMEOUT as e:
  360. logger.warning(f'Bash pexpect.TIMEOUT while executing bash command: {e}')
  361. if kill_on_timeout:
  362. output, exit_code = self._interrupt_bash(action_timeout=timeout)
  363. else:
  364. output = self.shell.before or ''
  365. exit_code = -1
  366. finally:
  367. bash_prompt = self._get_bash_prompt_and_update_pwd()
  368. if keep_prompt:
  369. output += '\r\n' + bash_prompt
  370. return output, exit_code
  371. async def run_action(self, action) -> Observation:
  372. action_type = action.action
  373. logger.debug(f'Running action:\n{action}')
  374. observation = await getattr(self, action_type)(action)
  375. logger.debug(f'Action output:\n{observation}')
  376. return observation
  377. async def run(self, action: CmdRunAction) -> CmdOutputObservation:
  378. try:
  379. assert (
  380. action.timeout is not None
  381. ), f'Timeout argument is required for CmdRunAction: {action}'
  382. commands = split_bash_commands(action.command)
  383. all_output = ''
  384. for command in commands:
  385. if command == '':
  386. output, exit_code = self._continue_bash(
  387. timeout=SOFT_TIMEOUT_SECONDS,
  388. keep_prompt=action.keep_prompt,
  389. kill_on_timeout=False,
  390. )
  391. elif command.lower() == 'ctrl+c':
  392. output, exit_code = self._interrupt_bash(
  393. action_timeout=None, # intentionally None
  394. )
  395. else:
  396. output, exit_code = self._execute_bash(
  397. command,
  398. timeout=SOFT_TIMEOUT_SECONDS
  399. if not action.blocking
  400. else action.timeout,
  401. keep_prompt=action.keep_prompt,
  402. kill_on_timeout=False if not action.blocking else True,
  403. )
  404. if all_output:
  405. # previous output already exists with prompt "user@hostname:working_dir #""
  406. # we need to add the command to the previous output,
  407. # so model knows the following is the output of another action)
  408. all_output = all_output.rstrip() + ' ' + command + '\r\n'
  409. all_output += str(output) + '\r\n'
  410. if exit_code != 0:
  411. break
  412. return CmdOutputObservation(
  413. command_id=-1,
  414. content=all_output.rstrip('\r\n'),
  415. command=action.command,
  416. hidden=action.hidden,
  417. exit_code=exit_code,
  418. )
  419. except UnicodeDecodeError:
  420. raise RuntimeError('Command output could not be decoded as utf-8')
  421. async def run_ipython(self, action: IPythonRunCellAction) -> Observation:
  422. if 'jupyter' in self.plugins:
  423. _jupyter_plugin: JupyterPlugin = self.plugins['jupyter'] # type: ignore
  424. # This is used to make AgentSkills in Jupyter aware of the
  425. # current working directory in Bash
  426. jupyter_pwd = getattr(self, '_jupyter_pwd', None)
  427. if self.pwd != jupyter_pwd:
  428. logger.debug(f'{self.pwd} != {jupyter_pwd} -> reset Jupyter PWD')
  429. reset_jupyter_pwd_code = f'import os; os.chdir("{self.pwd}")'
  430. _aux_action = IPythonRunCellAction(code=reset_jupyter_pwd_code)
  431. _reset_obs = await _jupyter_plugin.run(_aux_action)
  432. logger.debug(
  433. f'Changed working directory in IPython to: {self.pwd}. Output: {_reset_obs}'
  434. )
  435. self._jupyter_pwd = self.pwd
  436. obs: IPythonRunCellObservation = await _jupyter_plugin.run(action)
  437. obs.content = obs.content.rstrip()
  438. obs.content += f'\n[Jupyter current working directory: {self.pwd}]'
  439. obs.content += f'\n[Jupyter Python interpreter: {_jupyter_plugin.python_interpreter_path}]'
  440. return obs
  441. else:
  442. raise RuntimeError(
  443. 'JupyterRequirement not found. Unable to run IPython action.'
  444. )
  445. def _get_working_directory(self):
  446. # NOTE: this is part of initialization, so we hard code the timeout
  447. result, exit_code = self._execute_bash('pwd', timeout=60, keep_prompt=False)
  448. if exit_code != 0:
  449. raise RuntimeError('Failed to get working directory')
  450. return result.strip()
  451. def _resolve_path(self, path: str, working_dir: str) -> str:
  452. filepath = Path(path)
  453. if not filepath.is_absolute():
  454. return str(Path(working_dir) / filepath)
  455. return str(filepath)
  456. async def read(self, action: FileReadAction) -> Observation:
  457. # NOTE: the client code is running inside the sandbox,
  458. # so there's no need to check permission
  459. working_dir = self._get_working_directory()
  460. filepath = self._resolve_path(action.path, working_dir)
  461. try:
  462. with open(filepath, 'r', encoding='utf-8') as file:
  463. lines = read_lines(file.readlines(), action.start, action.end)
  464. except FileNotFoundError:
  465. return ErrorObservation(
  466. f'File not found: {filepath}. Your current working directory is {working_dir}.'
  467. )
  468. except UnicodeDecodeError:
  469. return ErrorObservation(f'File could not be decoded as utf-8: {filepath}.')
  470. except IsADirectoryError:
  471. return ErrorObservation(
  472. f'Path is a directory: {filepath}. You can only read files'
  473. )
  474. code_view = ''.join(lines)
  475. return FileReadObservation(path=filepath, content=code_view)
  476. async def write(self, action: FileWriteAction) -> Observation:
  477. working_dir = self._get_working_directory()
  478. filepath = self._resolve_path(action.path, working_dir)
  479. insert = action.content.split('\n')
  480. try:
  481. if not os.path.exists(os.path.dirname(filepath)):
  482. os.makedirs(os.path.dirname(filepath))
  483. file_exists = os.path.exists(filepath)
  484. if file_exists:
  485. file_stat = os.stat(filepath)
  486. else:
  487. file_stat = None
  488. mode = 'w' if not file_exists else 'r+'
  489. try:
  490. with open(filepath, mode, encoding='utf-8') as file:
  491. if mode != 'w':
  492. all_lines = file.readlines()
  493. new_file = insert_lines(
  494. insert, all_lines, action.start, action.end
  495. )
  496. else:
  497. new_file = [i + '\n' for i in insert]
  498. file.seek(0)
  499. file.writelines(new_file)
  500. file.truncate()
  501. # Handle file permissions
  502. if file_exists:
  503. assert file_stat is not None
  504. # restore the original file permissions if the file already exists
  505. os.chmod(filepath, file_stat.st_mode)
  506. os.chown(filepath, file_stat.st_uid, file_stat.st_gid)
  507. else:
  508. # set the new file permissions if the file is new
  509. os.chmod(filepath, 0o664)
  510. os.chown(filepath, self.user_id, self.user_id)
  511. except FileNotFoundError:
  512. return ErrorObservation(f'File not found: {filepath}')
  513. except IsADirectoryError:
  514. return ErrorObservation(
  515. f'Path is a directory: {filepath}. You can only write to files'
  516. )
  517. except UnicodeDecodeError:
  518. return ErrorObservation(
  519. f'File could not be decoded as utf-8: {filepath}'
  520. )
  521. except PermissionError:
  522. return ErrorObservation(f'Malformed paths not permitted: {filepath}')
  523. return FileWriteObservation(content='', path=filepath)
  524. async def browse(self, action: BrowseURLAction) -> Observation:
  525. return await browse(action, self.browser)
  526. async def browse_interactive(self, action: BrowseInteractiveAction) -> Observation:
  527. return await browse(action, self.browser)
  528. def close(self):
  529. self.shell.close()
  530. self.browser.close()
  531. if __name__ == '__main__':
  532. parser = argparse.ArgumentParser()
  533. parser.add_argument('port', type=int, help='Port to listen on')
  534. parser.add_argument('--working-dir', type=str, help='Working directory')
  535. parser.add_argument('--plugins', type=str, help='Plugins to initialize', nargs='+')
  536. parser.add_argument(
  537. '--username', type=str, help='User to run as', default='openhands'
  538. )
  539. parser.add_argument('--user-id', type=int, help='User ID to run as', default=1000)
  540. parser.add_argument(
  541. '--browsergym-eval-env',
  542. type=str,
  543. help='BrowserGym environment used for browser evaluation',
  544. default=None,
  545. )
  546. # example: python client.py 8000 --working-dir /workspace --plugins JupyterRequirement
  547. args = parser.parse_args()
  548. plugins_to_load: list[Plugin] = []
  549. if args.plugins:
  550. for plugin in args.plugins:
  551. if plugin not in ALL_PLUGINS:
  552. raise ValueError(f'Plugin {plugin} not found')
  553. plugins_to_load.append(ALL_PLUGINS[plugin]()) # type: ignore
  554. client: RuntimeClient | None = None
  555. @asynccontextmanager
  556. async def lifespan(app: FastAPI):
  557. global client
  558. client = RuntimeClient(
  559. plugins_to_load,
  560. work_dir=args.working_dir,
  561. username=args.username,
  562. user_id=args.user_id,
  563. browsergym_eval_env=args.browsergym_eval_env,
  564. )
  565. await client.ainit()
  566. yield
  567. # Clean up & release the resources
  568. client.close()
  569. app = FastAPI(lifespan=lifespan)
  570. # TODO below 3 exception handlers were recommended by Sonnet.
  571. # Are these something we should keep?
  572. @app.exception_handler(Exception)
  573. async def global_exception_handler(request: Request, exc: Exception):
  574. logger.exception('Unhandled exception occurred:')
  575. return JSONResponse(
  576. status_code=500,
  577. content={
  578. 'message': 'An unexpected error occurred. Please try again later.'
  579. },
  580. )
  581. @app.exception_handler(StarletteHTTPException)
  582. async def http_exception_handler(request: Request, exc: StarletteHTTPException):
  583. logger.error(f'HTTP exception occurred: {exc.detail}')
  584. return JSONResponse(
  585. status_code=exc.status_code, content={'message': exc.detail}
  586. )
  587. @app.exception_handler(RequestValidationError)
  588. async def validation_exception_handler(
  589. request: Request, exc: RequestValidationError
  590. ):
  591. logger.error(f'Validation error occurred: {exc}')
  592. return JSONResponse(
  593. status_code=422,
  594. content={'message': 'Invalid request parameters', 'details': exc.errors()},
  595. )
  596. @app.middleware('http')
  597. async def one_request_at_a_time(request: Request, call_next):
  598. assert client is not None
  599. async with client.lock:
  600. response = await call_next(request)
  601. return response
  602. @app.middleware('http')
  603. async def authenticate_requests(request: Request, call_next):
  604. if request.url.path != '/alive' and request.url.path != '/server_info':
  605. try:
  606. verify_api_key(request.headers.get('X-Session-API-Key'))
  607. except HTTPException as e:
  608. return e
  609. response = await call_next(request)
  610. return response
  611. @app.get('/server_info')
  612. async def get_server_info():
  613. assert client is not None
  614. current_time = time.time()
  615. uptime = current_time - client.start_time
  616. idle_time = current_time - client.last_execution_time
  617. return {'uptime': uptime, 'idle_time': idle_time}
  618. @app.post('/execute_action')
  619. async def execute_action(action_request: ActionRequest):
  620. assert client is not None
  621. try:
  622. action = event_from_dict(action_request.action)
  623. if not isinstance(action, Action):
  624. raise HTTPException(status_code=400, detail='Invalid action type')
  625. client.last_execution_time = time.time()
  626. observation = await client.run_action(action)
  627. return event_to_dict(observation)
  628. except Exception as e:
  629. logger.error(
  630. f'Error processing command: {str(e)}', exc_info=True, stack_info=True
  631. )
  632. raise HTTPException(status_code=500, detail=str(e))
  633. @app.post('/upload_file')
  634. async def upload_file(
  635. file: UploadFile, destination: str = '/', recursive: bool = False
  636. ):
  637. assert client is not None
  638. try:
  639. # Ensure the destination directory exists
  640. if not os.path.isabs(destination):
  641. raise HTTPException(
  642. status_code=400, detail='Destination must be an absolute path'
  643. )
  644. full_dest_path = destination
  645. if not os.path.exists(full_dest_path):
  646. os.makedirs(full_dest_path, exist_ok=True)
  647. if recursive or file.filename.endswith('.zip'):
  648. # For recursive uploads, we expect a zip file
  649. if not file.filename.endswith('.zip'):
  650. raise HTTPException(
  651. status_code=400, detail='Recursive uploads must be zip files'
  652. )
  653. zip_path = os.path.join(full_dest_path, file.filename)
  654. with open(zip_path, 'wb') as buffer:
  655. shutil.copyfileobj(file.file, buffer)
  656. # Extract the zip file
  657. shutil.unpack_archive(zip_path, full_dest_path)
  658. os.remove(zip_path) # Remove the zip file after extraction
  659. logger.info(
  660. f'Uploaded file {file.filename} and extracted to {destination}'
  661. )
  662. else:
  663. # For single file uploads
  664. file_path = os.path.join(full_dest_path, file.filename)
  665. with open(file_path, 'wb') as buffer:
  666. shutil.copyfileobj(file.file, buffer)
  667. logger.info(f'Uploaded file {file.filename} to {destination}')
  668. return JSONResponse(
  669. content={
  670. 'filename': file.filename,
  671. 'destination': destination,
  672. 'recursive': recursive,
  673. },
  674. status_code=200,
  675. )
  676. except Exception as e:
  677. raise HTTPException(status_code=500, detail=str(e))
  678. @app.get('/download_files')
  679. async def download_file(path: str):
  680. logger.info('Downloading files')
  681. try:
  682. if not os.path.isabs(path):
  683. raise HTTPException(
  684. status_code=400, detail='Path must be an absolute path'
  685. )
  686. if not os.path.exists(path):
  687. raise HTTPException(status_code=404, detail='File not found')
  688. with tempfile.TemporaryFile() as temp_zip:
  689. with ZipFile(temp_zip, 'w') as zipf:
  690. for root, _, files in os.walk(path):
  691. for file in files:
  692. file_path = os.path.join(root, file)
  693. zipf.write(
  694. file_path, arcname=os.path.relpath(file_path, path)
  695. )
  696. temp_zip.seek(0) # Rewind the file to the beginning after writing
  697. content = temp_zip.read()
  698. # Good for small to medium-sized files. For very large files, streaming directly from the
  699. # file chunks may be more memory-efficient.
  700. zip_stream = io.BytesIO(content)
  701. return StreamingResponse(
  702. content=zip_stream,
  703. media_type='application/zip',
  704. headers={'Content-Disposition': f'attachment; filename={path}.zip'},
  705. )
  706. except Exception as e:
  707. raise HTTPException(status_code=500, detail=str(e))
  708. @app.get('/alive')
  709. async def alive():
  710. return {'status': 'ok'}
  711. # ================================
  712. # File-specific operations for UI
  713. # ================================
  714. @app.post('/list_files')
  715. async def list_files(request: Request):
  716. """List files in the specified path.
  717. This function retrieves a list of files from the agent's runtime file store,
  718. excluding certain system and hidden files/directories.
  719. To list files:
  720. ```sh
  721. curl http://localhost:3000/api/list-files
  722. ```
  723. Args:
  724. request (Request): The incoming request object.
  725. path (str, optional): The path to list files from. Defaults to '/'.
  726. Returns:
  727. list: A list of file names in the specified path.
  728. Raises:
  729. HTTPException: If there's an error listing the files.
  730. """
  731. assert client is not None
  732. # get request as dict
  733. request_dict = await request.json()
  734. path = request_dict.get('path', None)
  735. # Get the full path of the requested directory
  736. if path is None:
  737. full_path = client.initial_pwd
  738. elif os.path.isabs(path):
  739. full_path = path
  740. else:
  741. full_path = os.path.join(client.initial_pwd, path)
  742. if not os.path.exists(full_path):
  743. # if user just removed a folder, prevent server error 500 in UI
  744. return []
  745. try:
  746. # Check if the directory exists
  747. if not os.path.exists(full_path) or not os.path.isdir(full_path):
  748. return []
  749. entries = os.listdir(full_path)
  750. # Separate directories and files
  751. directories = []
  752. files = []
  753. for entry in entries:
  754. # Remove leading slash and any parent directory components
  755. entry_relative = entry.lstrip('/').split('/')[-1]
  756. # Construct the full path by joining the base path with the relative entry path
  757. full_entry_path = os.path.join(full_path, entry_relative)
  758. if os.path.exists(full_entry_path):
  759. is_dir = os.path.isdir(full_entry_path)
  760. if is_dir:
  761. # add trailing slash to directories
  762. # required by FE to differentiate directories and files
  763. entry = entry.rstrip('/') + '/'
  764. directories.append(entry)
  765. else:
  766. files.append(entry)
  767. # Sort directories and files separately
  768. directories.sort(key=lambda s: s.lower())
  769. files.sort(key=lambda s: s.lower())
  770. # Combine sorted directories and files
  771. sorted_entries = directories + files
  772. return sorted_entries
  773. except Exception as e:
  774. logger.error(f'Error listing files: {e}', exc_info=True)
  775. return []
  776. logger.info('Runtime client initialized.')
  777. logger.info(f'Starting action execution API on port {args.port}')
  778. run(app, host='0.0.0.0', port=args.port)