client.py 29 KB

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