client.py 26 KB

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