client.py 26 KB

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