client.py 28 KB

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