action_execution_server.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  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 base64
  9. import io
  10. import json
  11. import mimetypes
  12. import os
  13. import re
  14. import shutil
  15. import tempfile
  16. import time
  17. import traceback
  18. from contextlib import asynccontextmanager
  19. from pathlib import Path
  20. from zipfile import ZipFile
  21. from fastapi import Depends, FastAPI, HTTPException, Request, UploadFile
  22. from fastapi.exceptions import RequestValidationError
  23. from fastapi.responses import JSONResponse, StreamingResponse
  24. from fastapi.security import APIKeyHeader
  25. from pydantic import BaseModel
  26. from starlette.exceptions import HTTPException as StarletteHTTPException
  27. from uvicorn import run
  28. from openhands.core.logger import openhands_logger as logger
  29. from openhands.events.action import (
  30. Action,
  31. BrowseInteractiveAction,
  32. BrowseURLAction,
  33. CmdRunAction,
  34. FileReadAction,
  35. FileWriteAction,
  36. IPythonRunCellAction,
  37. )
  38. from openhands.events.observation import (
  39. CmdOutputObservation,
  40. ErrorObservation,
  41. FileReadObservation,
  42. FileWriteObservation,
  43. IPythonRunCellObservation,
  44. Observation,
  45. )
  46. from openhands.events.serialization import event_from_dict, event_to_dict
  47. from openhands.runtime.browser import browse
  48. from openhands.runtime.browser.browser_env import BrowserEnv
  49. from openhands.runtime.plugins import ALL_PLUGINS, JupyterPlugin, Plugin, VSCodePlugin
  50. from openhands.runtime.utils.bash import BashSession
  51. from openhands.runtime.utils.files import insert_lines, read_lines
  52. from openhands.runtime.utils.runtime_init import init_user_and_working_directory
  53. from openhands.runtime.utils.system import check_port_available
  54. from openhands.runtime.utils.system_stats import get_system_stats
  55. from openhands.utils.async_utils import call_sync_from_async, wait_all
  56. class ActionRequest(BaseModel):
  57. action: dict
  58. ROOT_GID = 0
  59. INIT_COMMANDS = [
  60. 'git config --global user.name "openhands" && git config --global user.email "openhands@all-hands.dev" && alias git="git --no-pager"',
  61. ]
  62. SESSION_API_KEY = os.environ.get('SESSION_API_KEY')
  63. api_key_header = APIKeyHeader(name='X-Session-API-Key', auto_error=False)
  64. def verify_api_key(api_key: str = Depends(api_key_header)):
  65. if SESSION_API_KEY and api_key != SESSION_API_KEY:
  66. raise HTTPException(status_code=403, detail='Invalid API Key')
  67. return api_key
  68. class ActionExecutor:
  69. """ActionExecutor is running inside docker sandbox.
  70. It is responsible for executing actions received from OpenHands backend and producing observations.
  71. """
  72. def __init__(
  73. self,
  74. plugins_to_load: list[Plugin],
  75. work_dir: str,
  76. username: str,
  77. user_id: int,
  78. browsergym_eval_env: str | None,
  79. ) -> None:
  80. self.plugins_to_load = plugins_to_load
  81. self._initial_pwd = work_dir
  82. self.username = username
  83. self.user_id = user_id
  84. _updated_user_id = init_user_and_working_directory(
  85. username=username, user_id=self.user_id, initial_pwd=work_dir
  86. )
  87. if _updated_user_id is not None:
  88. self.user_id = _updated_user_id
  89. self.bash_session = BashSession(
  90. work_dir=work_dir,
  91. username=username,
  92. )
  93. self.lock = asyncio.Lock()
  94. self.plugins: dict[str, Plugin] = {}
  95. self.browser = BrowserEnv(browsergym_eval_env)
  96. self.start_time = time.time()
  97. self.last_execution_time = self.start_time
  98. @property
  99. def initial_pwd(self):
  100. return self._initial_pwd
  101. async def ainit(self):
  102. await wait_all(
  103. (self._init_plugin(plugin) for plugin in self.plugins_to_load),
  104. timeout=30,
  105. )
  106. # This is a temporary workaround
  107. # TODO: refactor AgentSkills to be part of JupyterPlugin
  108. # AFTER ServerRuntime is deprecated
  109. if 'agent_skills' in self.plugins and 'jupyter' in self.plugins:
  110. obs = await self.run_ipython(
  111. IPythonRunCellAction(
  112. code='from openhands.runtime.plugins.agent_skills.agentskills import *\n'
  113. )
  114. )
  115. logger.debug(f'AgentSkills initialized: {obs}')
  116. await self._init_bash_commands()
  117. logger.debug('Runtime client initialized.')
  118. async def _init_plugin(self, plugin: Plugin):
  119. await plugin.initialize(self.username)
  120. self.plugins[plugin.name] = plugin
  121. logger.debug(f'Initializing plugin: {plugin.name}')
  122. if isinstance(plugin, JupyterPlugin):
  123. await self.run_ipython(
  124. IPythonRunCellAction(
  125. code=f'import os; os.chdir("{self.bash_session.pwd}")'
  126. )
  127. )
  128. async def _init_bash_commands(self):
  129. logger.debug(f'Initializing by running {len(INIT_COMMANDS)} bash commands...')
  130. for command in INIT_COMMANDS:
  131. action = CmdRunAction(command=command)
  132. action.timeout = 300
  133. logger.debug(f'Executing init command: {command}')
  134. obs = await self.run(action)
  135. assert isinstance(obs, CmdOutputObservation)
  136. logger.debug(
  137. f'Init command outputs (exit code: {obs.exit_code}): {obs.content}'
  138. )
  139. assert obs.exit_code == 0
  140. logger.debug('Bash init commands completed')
  141. async def run_action(self, action) -> Observation:
  142. async with self.lock:
  143. action_type = action.action
  144. logger.debug(f'Running action:\n{action}')
  145. observation = await getattr(self, action_type)(action)
  146. logger.debug(f'Action output:\n{observation}')
  147. return observation
  148. async def run(
  149. self, action: CmdRunAction
  150. ) -> CmdOutputObservation | ErrorObservation:
  151. obs = await call_sync_from_async(self.bash_session.run, action)
  152. return obs
  153. async def run_ipython(self, action: IPythonRunCellAction) -> Observation:
  154. if 'jupyter' in self.plugins:
  155. _jupyter_plugin: JupyterPlugin = self.plugins['jupyter'] # type: ignore
  156. # This is used to make AgentSkills in Jupyter aware of the
  157. # current working directory in Bash
  158. jupyter_pwd = getattr(self, '_jupyter_pwd', None)
  159. if self.bash_session.pwd != jupyter_pwd:
  160. logger.debug(
  161. f'{self.bash_session.pwd} != {jupyter_pwd} -> reset Jupyter PWD'
  162. )
  163. reset_jupyter_pwd_code = (
  164. f'import os; os.chdir("{self.bash_session.pwd}")'
  165. )
  166. _aux_action = IPythonRunCellAction(code=reset_jupyter_pwd_code)
  167. _reset_obs: IPythonRunCellObservation = await _jupyter_plugin.run(
  168. _aux_action
  169. )
  170. logger.debug(
  171. f'Changed working directory in IPython to: {self.bash_session.pwd}. Output: {_reset_obs}'
  172. )
  173. self._jupyter_pwd = self.bash_session.pwd
  174. obs: IPythonRunCellObservation = await _jupyter_plugin.run(action)
  175. obs.content = obs.content.rstrip()
  176. matches = re.findall(
  177. r'<oh_aci_output>(.*?)</oh_aci_output>', obs.content, re.DOTALL
  178. )
  179. if matches:
  180. results = []
  181. for match in matches:
  182. try:
  183. result_dict = json.loads(match)
  184. results.append(
  185. result_dict.get('formatted_output_and_error', '')
  186. )
  187. except json.JSONDecodeError:
  188. # Handle JSON decoding errors if necessary
  189. results.append(
  190. f"Invalid JSON in 'openhands-aci' output: {match}"
  191. )
  192. # Combine the results (e.g., join them) or handle them as required
  193. obs.content = '\n'.join(results)
  194. if action.include_extra:
  195. obs.content += (
  196. f'\n[Jupyter current working directory: {self.bash_session.pwd}]'
  197. )
  198. obs.content += f'\n[Jupyter Python interpreter: {_jupyter_plugin.python_interpreter_path}]'
  199. return obs
  200. else:
  201. raise RuntimeError(
  202. 'JupyterRequirement not found. Unable to run IPython action.'
  203. )
  204. def _resolve_path(self, path: str, working_dir: str) -> str:
  205. filepath = Path(path)
  206. if not filepath.is_absolute():
  207. return str(Path(working_dir) / filepath)
  208. return str(filepath)
  209. async def read(self, action: FileReadAction) -> Observation:
  210. # NOTE: the client code is running inside the sandbox,
  211. # so there's no need to check permission
  212. working_dir = self.bash_session.workdir
  213. filepath = self._resolve_path(action.path, working_dir)
  214. try:
  215. if filepath.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
  216. with open(filepath, 'rb') as file:
  217. image_data = file.read()
  218. encoded_image = base64.b64encode(image_data).decode('utf-8')
  219. mime_type, _ = mimetypes.guess_type(filepath)
  220. if mime_type is None:
  221. mime_type = 'image/png' # default to PNG if mime type cannot be determined
  222. encoded_image = f'data:{mime_type};base64,{encoded_image}'
  223. return FileReadObservation(path=filepath, content=encoded_image)
  224. elif filepath.lower().endswith('.pdf'):
  225. with open(filepath, 'rb') as file:
  226. pdf_data = file.read()
  227. encoded_pdf = base64.b64encode(pdf_data).decode('utf-8')
  228. encoded_pdf = f'data:application/pdf;base64,{encoded_pdf}'
  229. return FileReadObservation(path=filepath, content=encoded_pdf)
  230. elif filepath.lower().endswith(('.mp4', '.webm', '.ogg')):
  231. with open(filepath, 'rb') as file:
  232. video_data = file.read()
  233. encoded_video = base64.b64encode(video_data).decode('utf-8')
  234. mime_type, _ = mimetypes.guess_type(filepath)
  235. if mime_type is None:
  236. mime_type = 'video/mp4' # default to MP4 if MIME type cannot be determined
  237. encoded_video = f'data:{mime_type};base64,{encoded_video}'
  238. return FileReadObservation(path=filepath, content=encoded_video)
  239. with open(filepath, 'r', encoding='utf-8') as file:
  240. lines = read_lines(file.readlines(), action.start, action.end)
  241. except FileNotFoundError:
  242. return ErrorObservation(
  243. f'File not found: {filepath}. Your current working directory is {working_dir}.'
  244. )
  245. except UnicodeDecodeError:
  246. return ErrorObservation(f'File could not be decoded as utf-8: {filepath}.')
  247. except IsADirectoryError:
  248. return ErrorObservation(
  249. f'Path is a directory: {filepath}. You can only read files'
  250. )
  251. code_view = ''.join(lines)
  252. return FileReadObservation(path=filepath, content=code_view)
  253. async def write(self, action: FileWriteAction) -> Observation:
  254. working_dir = self.bash_session.workdir
  255. filepath = self._resolve_path(action.path, working_dir)
  256. insert = action.content.split('\n')
  257. try:
  258. if not os.path.exists(os.path.dirname(filepath)):
  259. os.makedirs(os.path.dirname(filepath))
  260. file_exists = os.path.exists(filepath)
  261. if file_exists:
  262. file_stat = os.stat(filepath)
  263. else:
  264. file_stat = None
  265. mode = 'w' if not file_exists else 'r+'
  266. try:
  267. with open(filepath, mode, encoding='utf-8') as file:
  268. if mode != 'w':
  269. all_lines = file.readlines()
  270. new_file = insert_lines(
  271. insert, all_lines, action.start, action.end
  272. )
  273. else:
  274. new_file = [i + '\n' for i in insert]
  275. file.seek(0)
  276. file.writelines(new_file)
  277. file.truncate()
  278. # Handle file permissions
  279. if file_exists:
  280. assert file_stat is not None
  281. # restore the original file permissions if the file already exists
  282. os.chmod(filepath, file_stat.st_mode)
  283. os.chown(filepath, file_stat.st_uid, file_stat.st_gid)
  284. else:
  285. # set the new file permissions if the file is new
  286. os.chmod(filepath, 0o664)
  287. os.chown(filepath, self.user_id, self.user_id)
  288. except FileNotFoundError:
  289. return ErrorObservation(f'File not found: {filepath}')
  290. except IsADirectoryError:
  291. return ErrorObservation(
  292. f'Path is a directory: {filepath}. You can only write to files'
  293. )
  294. except UnicodeDecodeError:
  295. return ErrorObservation(
  296. f'File could not be decoded as utf-8: {filepath}'
  297. )
  298. except PermissionError:
  299. return ErrorObservation(f'Malformed paths not permitted: {filepath}')
  300. return FileWriteObservation(content='', path=filepath)
  301. async def browse(self, action: BrowseURLAction) -> Observation:
  302. return await browse(action, self.browser)
  303. async def browse_interactive(self, action: BrowseInteractiveAction) -> Observation:
  304. return await browse(action, self.browser)
  305. def close(self):
  306. self.bash_session.close()
  307. self.browser.close()
  308. if __name__ == '__main__':
  309. parser = argparse.ArgumentParser()
  310. parser.add_argument('port', type=int, help='Port to listen on')
  311. parser.add_argument('--working-dir', type=str, help='Working directory')
  312. parser.add_argument('--plugins', type=str, help='Plugins to initialize', nargs='+')
  313. parser.add_argument(
  314. '--username', type=str, help='User to run as', default='openhands'
  315. )
  316. parser.add_argument('--user-id', type=int, help='User ID to run as', default=1000)
  317. parser.add_argument(
  318. '--browsergym-eval-env',
  319. type=str,
  320. help='BrowserGym environment used for browser evaluation',
  321. default=None,
  322. )
  323. # example: python client.py 8000 --working-dir /workspace --plugins JupyterRequirement
  324. args = parser.parse_args()
  325. os.environ['VSCODE_PORT'] = str(int(args.port) + 1)
  326. assert check_port_available(int(os.environ['VSCODE_PORT']))
  327. plugins_to_load: list[Plugin] = []
  328. if args.plugins:
  329. for plugin in args.plugins:
  330. if plugin not in ALL_PLUGINS:
  331. raise ValueError(f'Plugin {plugin} not found')
  332. plugins_to_load.append(ALL_PLUGINS[plugin]()) # type: ignore
  333. client: ActionExecutor | None = None
  334. @asynccontextmanager
  335. async def lifespan(app: FastAPI):
  336. global client
  337. client = ActionExecutor(
  338. plugins_to_load,
  339. work_dir=args.working_dir,
  340. username=args.username,
  341. user_id=args.user_id,
  342. browsergym_eval_env=args.browsergym_eval_env,
  343. )
  344. await client.ainit()
  345. yield
  346. # Clean up & release the resources
  347. client.close()
  348. app = FastAPI(lifespan=lifespan)
  349. # TODO below 3 exception handlers were recommended by Sonnet.
  350. # Are these something we should keep?
  351. @app.exception_handler(Exception)
  352. async def global_exception_handler(request: Request, exc: Exception):
  353. logger.exception('Unhandled exception occurred:')
  354. return JSONResponse(
  355. status_code=500,
  356. content={'detail': 'An unexpected error occurred. Please try again later.'},
  357. )
  358. @app.exception_handler(StarletteHTTPException)
  359. async def http_exception_handler(request: Request, exc: StarletteHTTPException):
  360. logger.error(f'HTTP exception occurred: {exc.detail}')
  361. return JSONResponse(status_code=exc.status_code, content={'detail': exc.detail})
  362. @app.exception_handler(RequestValidationError)
  363. async def validation_exception_handler(
  364. request: Request, exc: RequestValidationError
  365. ):
  366. logger.error(f'Validation error occurred: {exc}')
  367. return JSONResponse(
  368. status_code=422,
  369. content={'detail': 'Invalid request parameters', 'errors': exc.errors()},
  370. )
  371. @app.middleware('http')
  372. async def authenticate_requests(request: Request, call_next):
  373. if request.url.path != '/alive' and request.url.path != '/server_info':
  374. try:
  375. verify_api_key(request.headers.get('X-Session-API-Key'))
  376. except HTTPException as e:
  377. return e
  378. response = await call_next(request)
  379. return response
  380. @app.get('/server_info')
  381. async def get_server_info():
  382. assert client is not None
  383. current_time = time.time()
  384. uptime = current_time - client.start_time
  385. idle_time = current_time - client.last_execution_time
  386. response = {
  387. 'uptime': uptime,
  388. 'idle_time': idle_time,
  389. 'resources': get_system_stats(),
  390. }
  391. logger.info('Server info endpoint response: %s', response)
  392. return response
  393. @app.post('/execute_action')
  394. async def execute_action(action_request: ActionRequest):
  395. assert client is not None
  396. try:
  397. action = event_from_dict(action_request.action)
  398. if not isinstance(action, Action):
  399. raise HTTPException(status_code=400, detail='Invalid action type')
  400. client.last_execution_time = time.time()
  401. observation = await client.run_action(action)
  402. return event_to_dict(observation)
  403. except Exception as e:
  404. logger.error(
  405. f'Error processing command: {str(e)}', exc_info=True, stack_info=True
  406. )
  407. raise HTTPException(
  408. status_code=500,
  409. detail=traceback.format_exc(),
  410. )
  411. @app.post('/upload_file')
  412. async def upload_file(
  413. file: UploadFile, destination: str = '/', recursive: bool = False
  414. ):
  415. assert client is not None
  416. try:
  417. # Ensure the destination directory exists
  418. if not os.path.isabs(destination):
  419. raise HTTPException(
  420. status_code=400, detail='Destination must be an absolute path'
  421. )
  422. full_dest_path = destination
  423. if not os.path.exists(full_dest_path):
  424. os.makedirs(full_dest_path, exist_ok=True)
  425. if recursive or file.filename.endswith('.zip'):
  426. # For recursive uploads, we expect a zip file
  427. if not file.filename.endswith('.zip'):
  428. raise HTTPException(
  429. status_code=400, detail='Recursive uploads must be zip files'
  430. )
  431. zip_path = os.path.join(full_dest_path, file.filename)
  432. with open(zip_path, 'wb') as buffer:
  433. shutil.copyfileobj(file.file, buffer)
  434. # Extract the zip file
  435. shutil.unpack_archive(zip_path, full_dest_path)
  436. os.remove(zip_path) # Remove the zip file after extraction
  437. logger.debug(
  438. f'Uploaded file {file.filename} and extracted to {destination}'
  439. )
  440. else:
  441. # For single file uploads
  442. file_path = os.path.join(full_dest_path, file.filename)
  443. with open(file_path, 'wb') as buffer:
  444. shutil.copyfileobj(file.file, buffer)
  445. logger.debug(f'Uploaded file {file.filename} to {destination}')
  446. return JSONResponse(
  447. content={
  448. 'filename': file.filename,
  449. 'destination': destination,
  450. 'recursive': recursive,
  451. },
  452. status_code=200,
  453. )
  454. except Exception as e:
  455. raise HTTPException(status_code=500, detail=str(e))
  456. @app.get('/download_files')
  457. async def download_file(path: str):
  458. logger.debug('Downloading files')
  459. try:
  460. if not os.path.isabs(path):
  461. raise HTTPException(
  462. status_code=400, detail='Path must be an absolute path'
  463. )
  464. if not os.path.exists(path):
  465. raise HTTPException(status_code=404, detail='File not found')
  466. with tempfile.TemporaryFile() as temp_zip:
  467. with ZipFile(temp_zip, 'w') as zipf:
  468. for root, _, files in os.walk(path):
  469. for file in files:
  470. file_path = os.path.join(root, file)
  471. zipf.write(
  472. file_path, arcname=os.path.relpath(file_path, path)
  473. )
  474. temp_zip.seek(0) # Rewind the file to the beginning after writing
  475. content = temp_zip.read()
  476. # Good for small to medium-sized files. For very large files, streaming directly from the
  477. # file chunks may be more memory-efficient.
  478. zip_stream = io.BytesIO(content)
  479. return StreamingResponse(
  480. content=zip_stream,
  481. media_type='application/zip',
  482. headers={'Content-Disposition': f'attachment; filename={path}.zip'},
  483. )
  484. except Exception as e:
  485. raise HTTPException(status_code=500, detail=str(e))
  486. @app.get('/alive')
  487. async def alive():
  488. return {'status': 'ok'}
  489. # ================================
  490. # VSCode-specific operations
  491. # ================================
  492. @app.get('/vscode/connection_token')
  493. async def get_vscode_connection_token():
  494. assert client is not None
  495. if 'vscode' in client.plugins:
  496. plugin: VSCodePlugin = client.plugins['vscode'] # type: ignore
  497. return {'token': plugin.vscode_connection_token}
  498. else:
  499. return {'token': None}
  500. # ================================
  501. # File-specific operations for UI
  502. # ================================
  503. @app.post('/list_files')
  504. async def list_files(request: Request):
  505. """List files in the specified path.
  506. This function retrieves a list of files from the agent's runtime file store,
  507. excluding certain system and hidden files/directories.
  508. To list files:
  509. ```sh
  510. curl http://localhost:3000/api/list-files
  511. ```
  512. Args:
  513. request (Request): The incoming request object.
  514. path (str, optional): The path to list files from. Defaults to '/'.
  515. Returns:
  516. list: A list of file names in the specified path.
  517. Raises:
  518. HTTPException: If there's an error listing the files.
  519. """
  520. assert client is not None
  521. # get request as dict
  522. request_dict = await request.json()
  523. path = request_dict.get('path', None)
  524. # Get the full path of the requested directory
  525. if path is None:
  526. full_path = client.initial_pwd
  527. elif os.path.isabs(path):
  528. full_path = path
  529. else:
  530. full_path = os.path.join(client.initial_pwd, path)
  531. if not os.path.exists(full_path):
  532. # if user just removed a folder, prevent server error 500 in UI
  533. return []
  534. try:
  535. # Check if the directory exists
  536. if not os.path.exists(full_path) or not os.path.isdir(full_path):
  537. return []
  538. entries = os.listdir(full_path)
  539. # Separate directories and files
  540. directories = []
  541. files = []
  542. for entry in entries:
  543. # Remove leading slash and any parent directory components
  544. entry_relative = entry.lstrip('/').split('/')[-1]
  545. # Construct the full path by joining the base path with the relative entry path
  546. full_entry_path = os.path.join(full_path, entry_relative)
  547. if os.path.exists(full_entry_path):
  548. is_dir = os.path.isdir(full_entry_path)
  549. if is_dir:
  550. # add trailing slash to directories
  551. # required by FE to differentiate directories and files
  552. entry = entry.rstrip('/') + '/'
  553. directories.append(entry)
  554. else:
  555. files.append(entry)
  556. # Sort directories and files separately
  557. directories.sort(key=lambda s: s.lower())
  558. files.sort(key=lambda s: s.lower())
  559. # Combine sorted directories and files
  560. sorted_entries = directories + files
  561. return sorted_entries
  562. except Exception as e:
  563. logger.error(f'Error listing files: {e}', exc_info=True)
  564. return []
  565. logger.debug(f'Starting action execution API on port {args.port}')
  566. run(app, host='0.0.0.0', port=args.port)