Source code for smarter.apps.account.repositories.loader

"""
Load a GitHub repository of Smarter manifests: find them, order them by their dependencies, and apply them.

:class:`RepositoryLoader` holds everything that loading a repository does, one manifest at a time, and two
callers use it:

- ``manage.py load_from_github``, whose command is a :class:`RepositoryLoader` with arguments: see
  :mod:`smarter.apps.account.management.commands.load_from_github`. ``manage.py initialize_platform`` and
  ``manage.py initialize_account`` load the example manifests and Stackademy with it.
- The web console's Apply page, which applies a repository as a user may: see
  :mod:`smarter.apps.account.repositories.apply`.

A repository may also give its folders owners, in its ``owners.yaml``
(:mod:`smarter.apps.account.repositories.owners`), and hold scripts, in its ``scripts/`` folder
(:mod:`smarter.apps.account.repositories.scripts`).
"""

import copy
import io
import os
import subprocess
from dataclasses import dataclass
from typing import Optional

import pathspec
import yaml
from django.core.management import call_command
from django.db import transaction

from smarter.apps.account.caching import smarter_cached_objects
from smarter.apps.account.models import Budget, UserProfile
from smarter.apps.account.repositories.owners import (
    OWNERS_CONFIG,
    RepositoryOwnersConfig,
)
from smarter.apps.account.repositories.scripts import (
    SCRIPTS_FOLDER,
    RepositoryScriptsConfig,
    ScriptStage,
    run_script,
    script_environment,
)
from smarter.apps.api.v1.manifests.enum import SAMKinds
from smarter.apps.llmclient.models import LLMClient
from smarter.apps.llmclient.tasks.queue import queue_deploy_default_api
from smarter.apps.llmtool.models import Extension
from smarter.common.exceptions import SmarterValueError
from smarter.lib import json, logging
from smarter.lib.annotation.const import (
    SOURCE_COMMIT_ANNOTATION,
    SOURCE_PATH_ANNOTATION,
    SOURCE_REPOSITORY_ANNOTATION,
)
from smarter.lib.annotation.validation import (
    AnnotationsMap,
    SmarterAnnotationError,
    normalize_annotations,
)
from smarter.lib.django.management.base import SmarterCommand
from smarter.lib.django.validators import SmarterValidator
from smarter.lib.manifest.broker import SAMBrokerNotFoundError
from smarter.lib.manifest.sam_apps import kind_is_enabled
from smarter.lib.manifest.template import TEMPLATE_EXTENSION, render_manifest_template
from smarter.lib.typing import SmarterDictType

logger = logging.getSmarterLogger(__name__)

MANIFEST_EXTENSIONS = (".yaml", ".yml", TEMPLATE_EXTENSION)
"""The extensions of the files that may hold a manifest.

Other files, e.g. a README, are ignored.
"""
IGNORE_FILE = ".smarterignore"
"""A repository's list of the files that are never applied, as gitignore-style patterns, at its root.

For example, ``/scripts/`` keeps the repository's scripts folder out, ``/tutorials/`` the manifests of a
tutorial, which its readers build themselves, and ``*.example.yaml`` examples. See :func:`load_ignore_spec`.
"""


[docs] def load_ignore_spec(local_path: str) -> Optional[pathspec.GitIgnoreSpec]: """ Return the patterns of a repository's ``.smarterignore``, if it has one. They are gitignore's patterns, with its rules, which pathspec implements: a pattern without a slash matches at any depth, a leading slash anchors it to the repository's root, a trailing slash matches a folder and everything in it, ``**`` matches any number of folders, ``!`` includes again what an earlier pattern excluded, and ``#`` starts a comment. :param local_path: The repository's clone. :returns: The patterns, or None if the repository has no ``.smarterignore``. """ filespec = os.path.join(local_path, IGNORE_FILE) if not os.path.isfile(filespec): return None with open(filespec, encoding="utf-8") as f: spec = pathspec.GitIgnoreSpec.from_lines(f) return spec
[docs] @dataclass(frozen=True) class RepositoryManifest: """A manifest of the repository: its file, relative to the repository's root, and its content.""" path: str """The file, relative to the repository's root, e.g. ``plugins/sql/stackademy-sql.yaml``.""" filespec: str """The file's absolute path in the clone.""" kind: str """The manifest's kind, e.g. ``SqlPlugin``.""" name: str """The manifest's ``metadata.name``.""" manifest: SmarterDictType """The manifest, with a template's placeholders filled in.""" @property def rank(self) -> int: """The position of the manifest's kind in :meth:`SAMKinds.apply_order() <smarter_types.kinds.SAMKinds.apply_order>`.""" return SAMKinds.apply_rank(self.kind)
# pylint: disable=E1101
[docs] class RepositoryLoader(SmarterCommand): """ Find, order and apply the manifests of a repository's clone, as a user, through the same brokers as the ``apply`` api. It is a management command class, without arguments or a ``handle()``, because it reports its progress the way a command does, to ``self.stdout`` and ``self.stderr``, in the command's styles. ``manage.py load_from_github`` writes it to the console; the Apply page captures it for each manifest. The repository's folders are only for people: the manifests are applied in the order of their kinds' dependencies, :meth:`SAMKinds.apply_order() <smarter_types.kinds.SAMKinds.apply_order>`, so that a Connection exists before the plugin that uses it, a plugin before the LLMClient that lists it, and so on. Within a kind, they are applied in the order of their paths. See the command's docstring for what is skipped, kept and annotated. """ UNVERIFIED_DNS_STATUSES = ( LLMClient.DnsVerificationStatusChoices.NOT_VERIFIED, LLMClient.DnsVerificationStatusChoices.FAILED, ) """The domain statuses of a deployed LLMClient that no deploy task is going to change.""" _url: Optional[str] = None user_profile: Optional[UserProfile] = None owners_config: Optional[RepositoryOwnersConfig] = None """The repository's ``owners.yaml``, or None if it has none.""" verbose: bool = False skip_missing_references: bool = False commit: Optional[str] = None """The commit of the clone, from :meth:`head_commit`, or None if it is not known.""" skipped: set[str] """The manifests, by file, that :meth:`apply` skipped, because they name a resource that doesn't exist."""
[docs] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.skipped = set()
@property def url(self) -> str: """The repository's url.""" if not self._url: raise SmarterValueError("URL is required.") return self._url @url.setter def url(self, value: str) -> None: """ Set the repository's url, after validating it. :param value: The url. """ SmarterValidator.validate_url(value) self._url = value
[docs] def clone_repo(self, local_path: str) -> None: """ Clone the repository's default branch, without its history. :param local_path: The folder to clone into. :raises subprocess.CalledProcessError: If git fails. """ result = subprocess.call(["git", "clone", "--depth", "1", "--quiet", self.url, local_path]) if result != 0: raise subprocess.CalledProcessError(returncode=result, cmd=f"git clone {self.url} {local_path}") logger.debug("cloned %s to %s", self.url, local_path)
[docs] def head_commit(self, local_path: str) -> Optional[str]: """ Return the commit that the clone checked out. :param local_path: The repository's clone. :returns: The commit's full SHA, or None if git can't tell, in which case the resources are annotated without it. :rtype: Optional[str] """ try: result = subprocess.run( ["git", "-C", local_path, "rev-parse", "HEAD"], capture_output=True, text=True, check=True, timeout=30, ) except (OSError, subprocess.SubprocessError) as e: logger.warning("could not read the commit of %s: %s", self.url, e) return None return result.stdout.strip() or None
@property def source_repository(self) -> str: """The repository's url, without a trailing slash or ``.git``, as resources are annotated with it.""" url = self.url.rstrip("/") return url[: -len(".git")] if url.endswith(".git") else url
[docs] def source_annotations(self, path: str) -> AnnotationsMap: """ Return the annotations that say where a resource came from. :param path: The manifest's file, relative to the repository's root. :returns: The repository, the file and, if it is known, the commit. :rtype: AnnotationsMap """ retval: AnnotationsMap = {SOURCE_REPOSITORY_ANNOTATION: self.source_repository, SOURCE_PATH_ANNOTATION: path} if self.commit: retval[SOURCE_COMMIT_ANNOTATION] = self.commit return retval
[docs] def add_source_annotations(self, manifest: SmarterDictType, path: str) -> SmarterDictType: """ Return a copy of a manifest whose annotations also say where it came from. The manifest's own annotations are kept, in either form that SAM accepts, and returned as a map. A manifest whose annotations are invalid is returned unchanged, so that applying it reports them. :param manifest: The manifest. :param path: Its file, relative to the repository's root. :returns: The manifest, with :meth:`source_annotations` added to ``metadata.annotations``. :rtype: SmarterDictType """ manifest = copy.deepcopy(manifest) metadata = manifest.get("metadata") if not isinstance(metadata, dict): return manifest try: annotations = normalize_annotations(metadata.get("annotations")) except SmarterAnnotationError as e: logger.debug("left %s as it is: %s", path, e) return manifest annotations.update(self.source_annotations(path)) metadata["annotations"] = annotations return manifest
[docs] def run_scripts( self, local_path: str, config: Optional[RepositoryScriptsConfig], stage: ScriptStage, user_profile: UserProfile ) -> list[str]: """ Run the repository's scripts of one stage, in the order of its ``scripts/scripts.yaml``. :param local_path: The repository's clone. :param config: The repository's scripts configuration, or None if it has none. :param stage: ``pre`` or ``post``. :param user_profile: The owner of the resources, whose account and username the scripts receive. :returns: A description of each script that failed. :rtype: list[str] """ if config is None: return [] failed: list[str] = [] env = script_environment( url=self.url, local_path=local_path, account_number=str(user_profile.account.account_number), username=str(user_profile.user.username), ) for script in config.for_stage(stage): path = os.path.join(SCRIPTS_FOLDER, script.path) try: # run_script() logs each line that the script writes. run_script(local_path, script, env) except SmarterValueError as e: failed.append(f"{path}: {e.message}") continue self.stdout.write(f"Ran the {stage} script {path}.") return failed
[docs] def find_manifests(self, local_path: str) -> list[RepositoryManifest]: """ Return the repository's manifests, in the order in which to apply them. :param local_path: The repository's clone. :returns: The manifests, sorted by :meth:`SAMKinds.apply_order() <smarter_types.kinds.SAMKinds.apply_order>`, then by path. :rtype: list[RepositoryManifest] """ retval: list[RepositoryManifest] = [] ignore_spec = load_ignore_spec(local_path) ignored = 0 for root, directories, files in os.walk(local_path): directories[:] = sorted(d for d in directories if not d.startswith(".")) for file in sorted(files): if file.startswith(".") or not file.endswith(MANIFEST_EXTENSIONS): continue if root == local_path and file == OWNERS_CONFIG: continue filespec = os.path.join(root, file) path = os.path.relpath(filespec, local_path) if ignore_spec is not None and ignore_spec.match_file(path): ignored += 1 continue with open(filespec, encoding="utf-8") as f: text = f.read() if file.endswith(TEMPLATE_EXTENSION): text = render_manifest_template(text) manifest = yaml.safe_load(text) if ( not isinstance(manifest, dict) or not str(manifest.get("apiVersion", "")).startswith("smarter.sh/") or not manifest.get("kind") ): self.stdout.write(self.style.WARNING(f"Skipped {path}: it is not a Smarter manifest.")) continue metadata = manifest.get("metadata") or {} name = str(metadata.get("name", "")) retval.append( RepositoryManifest( path=path, filespec=filespec, kind=str(manifest["kind"]), name=name, manifest=manifest ) ) if ignored: self.stdout.write(f"Ignored {ignored} files that the repository's {IGNORE_FILE} lists.") return sorted(retval, key=self.apply_order_key)
[docs] def apply_order_key(self, item: RepositoryManifest) -> tuple[int, int, str]: """ Return a manifest's place in the order of application: its kind's rank, then its path. A manifest of a folder that ``owners.yaml`` gives an owner belongs to a user, so it comes after the Users, even if its kind ranks before them, e.g. a department's Secret: the Users are its owners. Everything else keeps :meth:`SAMKinds.apply_order() <smarter_types.kinds.SAMKinds.apply_order>`. :param item: The manifest. :returns: ``(rank, 0 or 1, path)``: 1 for an owned manifest moved after the Users. :rtype: tuple[int, int, str] """ user_rank = SAMKinds.apply_rank(SAMKinds.USER) owned = ( self.owners_config is not None and item.kind not in (SAMKinds.ACCOUNT.value, SAMKinds.USER.value) and self.owners_config.owner_for(item.path) is not None ) if owned and item.rank <= user_rank: return (user_rank, 1, item.path) return (item.rank, 0, item.path)
[docs] def select_manifests( self, manifests: list[RepositoryManifest], included: list[str], excluded: list[str] ) -> list[RepositoryManifest]: """ Return the manifests of the kinds to apply, and say which were skipped. :param manifests: The manifests, from :meth:`find_manifests`. :param included: Apply only these kinds, or every kind if it is empty. :param excluded: Skip these kinds. :returns: The manifests to apply, in the same order. :rtype: list[RepositoryManifest] """ retval: list[RepositoryManifest] = [] for item in manifests: if included and item.kind not in included: if self.verbose: self.stdout.write(f"Skipped {item.path}: {item.kind} is not included.") continue if item.kind in excluded: self.stdout.write(f"Skipped {item.path}: {item.kind} is excluded.") continue retval.append(item) return retval
[docs] def apply(self, filespec: str, user_profile: UserProfile, manifest: Optional[str] = None) -> Optional[str]: """ Apply one manifest, and report, rather than raise, a failure. The manifest is applied in a transaction, so that one that fails leaves nothing behind. A manifest that names a resource that doesn't exist is skipped, rather than failed, with ``--skip_missing_references``: its file is added to :attr:`skipped`. :param filespec: The manifest's path. :param user_profile: The owner of the resource. :param manifest: The manifest to apply instead of the file's, e.g. a template's, filled in. :returns: The error, or ``None`` if the manifest was applied or skipped. :rtype: Optional[str] """ if manifest is None and filespec.endswith(TEMPLATE_EXTENSION): with open(filespec, encoding="utf-8") as f: manifest = render_manifest_template(f.read()) output = io.StringIO() options = {"manifest": manifest} if manifest else {"filespec": filespec} try: with transaction.atomic(): call_command( "apply_manifest", username=user_profile.user.username, account_number=str(user_profile.account.account_number), stdout=output, stderr=output, **options, ) except SAMBrokerNotFoundError as exc: if not self.skip_missing_references: logger.error("failed to apply %s: %s", filespec, exc) return f"{os.path.basename(filespec)}: {type(exc).__name__}: {exc}" # DEBUG, because the command's output below already says so, at the same moment. logger.debug("skipped %s: %s", filespec, exc) self.skipped.add(filespec) self.stdout.write( self.style.WARNING( f"Skipped {os.path.basename(filespec)}: it names a resource that this platform doesn't have. " f"{exc.message}" ) ) return None # SystemExit: SmarterCommand.handle_completed_failure() exits when it is given an exception. # pylint: disable=broad-except except (Exception, SystemExit) as exc: logger.error("failed to apply %s: %s", filespec, exc) return f"{os.path.basename(filespec)}: {type(exc).__name__}: {exc}" if self.verbose: self.stdout.write(f"Applied {filespec}. {output.getvalue()}") return None
[docs] @staticmethod def is_staff_only(manifest: SmarterDictType) -> bool: """ Return whether an LLMClient manifest is staff-only, ``spec.config.prompt.staffOnly``. A staff-only LLMClient, e.g. ``smarter_sysadmin``, is applied to the Smarter account only, never copied into another account by ``initialize_account``, and never deployed. :param manifest: The LLMClient manifest, as a dict. :returns: True if it is staff-only. """ spec = manifest.get("spec") or {} config = spec.get("config") or {} prompt = config.get("prompt") or {} staff_only = prompt.get("staffOnly") is True return staff_only
[docs] @staticmethod def keep_deployed(manifest: SmarterDictType, user_profile: UserProfile) -> SmarterDictType: """ Return a copy of an LLMClient manifest whose ``deployed`` is that of the LLMClient that exists, if any. A manifest is not deployed, so applying it as it is would undeploy an LLMClient that is deployed, whose undeploy task destroys its A record, only for the next deploy to create it again. Resolvers that query the domain in between cache the NXDOMAIN for minutes. :param manifest: The LLMClient manifest. :param user_profile: The owner of the LLMClient. :returns: The manifest, with ``spec.config.prompt.deployed`` set. :rtype: SmarterDictType """ manifest = copy.deepcopy(manifest) name = manifest.get("metadata", {}).get("name") deployed = LLMClient.objects.filter(user_profile=user_profile, name=name, deployed=True).exists() manifest.setdefault("spec", {}).setdefault("config", {}).setdefault("prompt", {})["deployed"] = deployed return manifest
[docs] @staticmethod def missing_extensions(slugs: list[str]) -> list[str]: """ Return the slugs, of those that an LLMClient manifest lists, of the extensions that are not installed. ``manage.py install_official_extensions`` installs them, from a registry that may not be reachable. :param slugs: The extensions that the manifest lists. :returns: Those that are not installed. :rtype: list[str] """ installed = set( Extension.objects.filter(slug__in=slugs, installed_version__isnull=False).values_list("slug", flat=True) ) return [slug for slug in slugs if slug not in installed]
[docs] def is_existing_detached_budget(self, item: RepositoryManifest) -> bool: """ Whether a manifest is of a Budget that exists, and lists no resources. Such a Budget is left as it is: applying its manifest would detach it from the resources that a superuser has attached it to since it was created. :param item: The manifest. :returns: True if it is to be skipped. :rtype: bool """ if item.kind != SAMKinds.BUDGET.value: return False spec = item.manifest.get("spec") or {} if spec.get("resources"): return False return Budget.objects.filter(name=item.name).exists()
[docs] def deploy_llmclient(self, name: str, user_profile: UserProfile) -> bool: """ Deploy the LLMClient of a user, if it is not deployed. An LLMClient that is deployed is left as it is, unless its domain was never verified, or failed to verify, e.g. because the DNS service wasn't ready. It is then deployed again, with ``deploy_default_api``: otherwise nothing ever retries it, and it stays unreachable until someone undeploys and redeploys it by hand. :param name: The LLMClient's name. :param user_profile: Its owner. :returns: False if the LLMClient does not exist, or failed to deploy. :rtype: bool """ try: llmclient = LLMClient.objects.get(user_profile=user_profile, name=name) except LLMClient.DoesNotExist: self.stderr.write(self.style.ERROR(f"LLMClient {name} does not exist.")) return False try: if not llmclient.deployed: # LLMClient.save() queues the deploy task of an LLMClient that was not deployed. llmclient.deployed = True llmclient.save() self.stdout.write(self.style.SUCCESS(f"Deploying LLMClient {name}.")) elif llmclient.dns_verification_status in self.UNVERIFIED_DNS_STATUSES: self.stdout.write( self.style.WARNING( f"LLMClient {name} is deployed, but its domain is {llmclient.dns_verification_status}. " "Deploying it again." ) ) queue_deploy_default_api(llmclient) else: self.stdout.write(f"LLMClient {name} is deployed.") return True # pylint: disable=W0718 except Exception as e: self.stderr.write(self.style.ERROR(f"Failed to deploy LLMClient {name}: {e}")) return False
[docs] def apply_manifests( self, manifests: list[RepositoryManifest], user_profile: UserProfile, deploy: bool = False ) -> list[str]: """ Apply the manifests, in order, and deploy the LLMClients if ``deploy``. :param manifests: The manifests, from :meth:`find_manifests`. :param user_profile: The owner of the resources. :param deploy: Deploy each LLMClient that is not deployed. :returns: A description of each manifest that failed to apply or deploy. :rtype: list[str] """ failed: list[str] = [] for item in manifests: try: owner_profile = self.owner_profile_for(item, user_profile) except SmarterValueError as e: failed.append(f"{item.path}: {e}") continue if owner_profile is None: continue failed += self.apply_manifest(item, owner_profile, deploy) return failed
[docs] def owner_profile_for(self, item: RepositoryManifest, user_profile: UserProfile) -> Optional[UserProfile]: """ Return the profile that applies a manifest: its folder's owner in ``owners.yaml``, else ``user_profile``. Account and User manifests are always applied by ``user_profile``: they declare the organization that owns the rest. An owned folder's manifests are applied only when the repository is loaded into the Smarter account, and skipped otherwise, e.g. by ``initialize_account``: they belong to their owner, not to that account. See :mod:`smarter.apps.account.repositories.owners`. :param item: The manifest. :param user_profile: ``load_from_github``'s own user. :returns: The profile to apply it as, or None to skip it. :rtype: Optional[UserProfile] :raises SmarterValueError: If its owner doesn't exist, or doesn't belong to the account that ``owners.yaml`` names. """ if self.owners_config is None: return user_profile if item.kind in (SAMKinds.ACCOUNT.value, SAMKinds.USER.value): return user_profile owner = self.owners_config.owner_for(item.path) if owner is None: return user_profile if user_profile.account != smarter_cached_objects.smarter_account: self.stdout.write(f"Skipped {item.path}: it belongs to {owner.username}, of account {owner.accountNumber}.") return None owner_profile = ( UserProfile.objects.filter(user__username=owner.username, account__account_number=owner.accountNumber) .select_related("user", "account") .first() ) if owner_profile is None: raise SmarterValueError( f"its owner {owner.username} doesn't exist, or doesn't belong to account {owner.accountNumber}." ) return owner_profile
[docs] def deploy_skipped_reason(self, manifest: SmarterDictType, user_profile: UserProfile) -> Optional[str]: """ Return why ``--deploy`` leaves an LLMClient undeployed, or None to deploy it. - A staff-only LLMClient: its staff use it in the workbench, and a deployed url would only answer them anyway. - An LLMClient of a folder that ``owners.yaml`` gives an owner, e.g. a department's assistant over its own records: deploying it gives it a public url, which its owner decides, not the platform's load. :param manifest: The LLMClient manifest. :param user_profile: Its owner. :returns: The reason, or None. :rtype: Optional[str] """ if self.is_staff_only(manifest): return "it is staff-only." if self.user_profile is not None and user_profile != self.user_profile: return f"it belongs to {user_profile.user.username}, who decides whether to deploy it." return None
[docs] def apply_manifest(self, item: RepositoryManifest, user_profile: UserProfile, deploy: bool) -> list[str]: """ Apply one manifest, as its owner, and deploy it if it is an LLMClient and ``deploy``. :param item: The manifest. :param user_profile: Its owner: ``load_from_github``'s own user, or its folder's owner in ``owners.yaml``. :param deploy: Deploy an LLMClient that is not deployed. :returns: A description of the failure, if it failed to apply or deploy, else nothing. :rtype: list[str] """ failed: list[str] = [] manifest = item.manifest if not kind_is_enabled(item.kind): self.stdout.write(f"Skipped {item.path}: {item.kind} manifests are disabled on this platform.") return failed if self.is_existing_detached_budget(item): self.stdout.write( f"Kept Budget {item.name} as it is ({item.path}): applying its manifest, which attaches it to " "nothing, would detach the resources attached to it since it was created." ) return failed if item.kind == SAMKinds.LLM_CLIENT.value and self.is_staff_only(manifest): if user_profile.account != smarter_cached_objects.smarter_account: self.stdout.write(f"Skipped {item.path}: a staff-only LLMClient belongs to the Smarter account only.") return failed if item.kind == SAMKinds.LLM_CLIENT.value: missing = self.missing_extensions(manifest.get("spec", {}).get("extensions") or []) if missing: self.stdout.write( self.style.WARNING( f"Skipped {item.path}: it needs extensions that are not installed: {', '.join(missing)}." ) ) return failed manifest = self.keep_deployed(manifest, user_profile) manifest = self.add_source_annotations(manifest, item.path) error = self.apply(item.filespec, user_profile, manifest=json.dumps(manifest)) if error: failed.append(f"{item.path}: {error}") return failed if item.filespec in self.skipped: return failed self.stdout.write(f"Applied {item.kind} {item.name}, from {item.path}.") if not deploy or item.kind != SAMKinds.LLM_CLIENT.value: return failed return self.deploy_applied_llmclient(item, manifest, user_profile)
[docs] def deploy_applied_llmclient( self, item: RepositoryManifest, manifest: SmarterDictType, user_profile: UserProfile ) -> list[str]: """ Deploy an LLMClient that ``apply_manifest`` just applied, unless :meth:`deploy_skipped_reason` gives a reason. :param item: The LLMClient's manifest, as the repository holds it. :param manifest: The manifest as it was applied. :param user_profile: Its owner. :returns: A description of the failure, if it failed to deploy, else nothing. :rtype: list[str] """ failed: list[str] = [] reason = self.deploy_skipped_reason(manifest, user_profile) if reason: self.stdout.write(f"Did not deploy LLMClient {item.name}: {reason}") return failed if not self.deploy_llmclient(item.name, user_profile): failed.append(f"{item.path}: LLMClient {item.name} failed to deploy.") return failed