client.py 26 KB

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