client.py 25 KB

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