client.py 28 KB

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