Skip to content

The agent that grows with you

fix(plugins): subdirectory installs download only that folder

teknium172d18ce59fbd
diff --git a/cli-config.yaml.example b/cli-config.yaml.example
index 58bf136aa7e..21ff9ea6e46 100644
--- a/cli-config.yaml.example
+++ b/cli-config.yaml.example
@@ -41,7 +41,8 @@ runtime:
# Plugin Installation
# =============================================================================
plugins:
- # Deadline for each Git clone or pinned-commit fetch. Default: 300 seconds.
+ # Deadline for each Git clone, fetch or checkout during plugin install. Default: 300
+ # seconds. Subdirectory installs download only that folder.
# Raise this for large repositories or slow connections. Maximum: 3600.
clone_timeout_seconds: 300
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 1516fad8f9a..cb95e732aeb 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -1684,7 +1684,7 @@ DEFAULT_CONFIG = {
# Plugin system. `enabled`/`disabled` lists are written by `hermes plugins enable|disable` and
# deliberately omitted here so an empty default never clobbers a user allow-list.
"plugins": {
- # Deadline (seconds) for one plugin Git clone or pinned-commit fetch. Slow repositories may
+ # Deadline (seconds) for one plugin Git clone, fetch or checkout. Slow repositories may
# need more time; each network operation is capped at one hour.
"clone_timeout_seconds": 300,
# Wall-clock cap (seconds) for one in-process Python plugin hook callback; shell hooks keep
diff --git a/hermes_cli/plugins_cmd.py b/hermes_cli/plugins_cmd.py
index 4d2dcca78bc..744ad0bafc4 100644
--- a/hermes_cli/plugins_cmd.py
+++ b/hermes_cli/plugins_cmd.py
@@ -28,6 +28,7 @@ from utils import atomic_write_text, rmtree_readonly
logger = logging.getLogger(__name__)
_DEFAULT_CLONE_TIMEOUT_SECONDS = 300
_MAX_CLONE_TIMEOUT_SECONDS = 3600
+_CLONE_TIMEOUT_HINT = "On a slow connection, raise plugins.clone_timeout_seconds in config.yaml."
@functools.lru_cache(maxsize=1)
@@ -611,19 +612,19 @@ def _git_resolve_commit(repo: Path, git_exe: str, revision: str) -> str:
def _checkout_exact_revision(repo: Path, git_exe: str, revision: str, source_url: str = "") -> None:
- """Fetch and detach at one immutable commit, then verify the resulting HEAD."""
- fetch_timeout = _clone_timeout_seconds()
+ """Fetch and detach at one immutable commit, then verify the resulting HEAD. The checkout is
+ a network verb too: in a partial (subdirectory) clone it downloads the file contents."""
+ timeout = _clone_timeout_seconds()
for verb, args, failure_prefix in (
("fetch", ("fetch", "--depth", "1", "origin", revision), f"Git commit '{revision}' could not be fetched:\n"),
("checkout", ("checkout", "--detach", revision), f"Git checkout of commit '{revision}' failed:\n"),
):
try:
_git_or_raise(git_exe, repo, *args, failure_prefix=failure_prefix, source_url=source_url,
- auth_url=source_url if verb == "fetch" else "",
- timeout=fetch_timeout if verb == "fetch" else 60)
+ auth_url=source_url, timeout=timeout)
except subprocess.TimeoutExpired as exc:
- timeout = fetch_timeout if verb == "fetch" else 60
- raise PluginOperationError(f"Git {verb} of commit '{revision}' timed out after {timeout} seconds.") from exc
+ raise PluginOperationError(
+ f"Git {verb} of commit '{revision}' timed out after {timeout} seconds. {_CLONE_TIMEOUT_HINT}") from exc
actual = _git_head_revision(repo, git_exe)
if actual != _git_resolve_commit(repo, git_exe, revision):
raise PluginOperationError(
@@ -678,26 +679,53 @@ def _check_manifest_version(manifest: dict, plugin_name: str) -> None:
) from None
-def _clone_plugin_repo(tmp_clone: Path, git_url: str, revision: Optional[str]) -> str:
+def _restrict_checkout_to_subdir(repo: Path, git_exe: str, subdir: str) -> None:
+ """Sparse-check-out only *subdir*. Written as the classic ``info/sparse-checkout`` file
+ rather than ``git sparse-checkout set`` so older Git clients work too."""
+ _git_or_raise(git_exe, repo, "config", "core.sparseCheckout", "true", timeout=15,
+ failure_prefix="Could not enable sparse checkout:\n")
+ pattern_file = repo / ".git" / "info" / "sparse-checkout"
+ pattern_file.parent.mkdir(parents=True, exist_ok=True)
+ escaped = re.sub(r"([\\*?\[])", r"\\\1", subdir.strip("/"))
+ pattern_file.write_text(f"/{escaped}/\n", encoding="utf-8")
+
+
+def _clone_plugin_repo(tmp_clone: Path, git_url: str, revision: Optional[str],
+ subdir: Optional[str] = None) -> str:
"""Shallow-clone *git_url* into *tmp_clone* (detached at *revision* when given), scrub any
- credentials from the recorded origin, and return the installed HEAD SHA."""
+ credentials from the recorded origin, and return the installed HEAD SHA.
+
+ A *subdir* install is a blobless clone with a sparse checkout of that subdirectory: a plugin
+ living in a monorepo (Hindsight: 170 MB at depth 1, 2 MB for its plugin folder) otherwise
+ downloads every file in the repository, which times out on slow connections."""
git_exe = _resolve_git_executable()
if not git_exe:
raise PluginOperationError("git is not installed or not in PATH.")
clone_timeout = _clone_timeout_seconds()
- clone_args = ["clone", "--depth", "1", *(["--no-checkout"] if revision else []), git_url, str(tmp_clone)]
+ partial = ["--filter=blob:none"] if subdir else []
+ no_checkout = ["--no-checkout"] if revision or subdir else []
+ clone_args = ["clone", "--depth", "1", *partial, *no_checkout, git_url, str(tmp_clone)]
try:
result = _run_plugin_git(git_exe, tmp_clone.parent, *clone_args, auth_url=git_url,
timeout=clone_timeout)
except FileNotFoundError as e:
raise PluginOperationError("git is not installed or not in PATH.") from e
except subprocess.TimeoutExpired as e:
- raise PluginOperationError(f"Git clone timed out after {clone_timeout} seconds.") from e
+ raise PluginOperationError(f"Git clone timed out after {clone_timeout} seconds. {_CLONE_TIMEOUT_HINT}") from e
if result.returncode != 0:
raise PluginOperationError(_clone_failure_message(git_url, _safe_git_error(result, git_url)))
_scrub_cloned_origin(tmp_clone, git_exe, git_url)
+ if subdir:
+ _restrict_checkout_to_subdir(tmp_clone, git_exe, subdir)
if revision:
_checkout_exact_revision(tmp_clone, git_exe, revision, source_url=git_url)
+ elif subdir:
+ try:
+ _git_or_raise(git_exe, tmp_clone, "checkout", "HEAD", timeout=clone_timeout, source_url=git_url,
+ auth_url=git_url, failure_prefix="Git checkout of the plugin subdirectory failed:\n")
+ except subprocess.TimeoutExpired as e:
+ raise PluginOperationError(
+ f"Git checkout timed out after {clone_timeout} seconds. {_CLONE_TIMEOUT_HINT}") from e
return _git_head_revision(tmp_clone, git_exe)
@@ -835,7 +863,7 @@ def _install_plugin_core(
with tempfile.TemporaryDirectory(prefix=".install-", dir=plugins_dir) as tmp:
tmp_clone = Path(tmp) / "plugin"
- installed_revision = _clone_plugin_repo(tmp_clone, git_url, requested_revision)
+ installed_revision = _clone_plugin_repo(tmp_clone, git_url, requested_revision, subdir)
git_exe = _resolve_git_executable()
at_reviewed_pin = bool(reviewed_pin) and installed_revision == (
_git_resolve_commit(tmp_clone, git_exe, reviewed_pin) if git_exe and reviewed_pin else reviewed_pin)
diff --git a/tests/hermes_cli/test_plugin_install_ref.py b/tests/hermes_cli/test_plugin_install_ref.py
index ee58b6520de..a02a7e78b22 100644
--- a/tests/hermes_cli/test_plugin_install_ref.py
+++ b/tests/hermes_cli/test_plugin_install_ref.py
@@ -169,7 +169,7 @@ def test_subdir_pin_records_source_identity_and_installs_requested_tree(
}
-def test_clone_timeout_applies_to_real_pinned_subdir_install(monkeypatch, tmp_path):
+def test_clone_timeout_applies_to_every_network_step_of_a_pinned_install(monkeypatch, tmp_path):
from hermes_cli import plugins_cmd
repo, old_sha, _new_sha = _plugin_repo(tmp_path)
@@ -192,7 +192,41 @@ def test_clone_timeout_applies_to_real_pinned_subdir_install(monkeypatch, tmp_pa
assert _git(target, "rev-parse", "HEAD") == old_sha
assert ("clone", 137) in calls
assert ("fetch", 137) in calls
- assert ("checkout", 60) in calls
+ assert ("checkout", 137) in calls
+
+
[email protected]("pinned", [False, True])
+def test_subdir_install_downloads_only_that_subdirectory(monkeypatch, tmp_path, pinned):
+ from hermes_cli.plugins_cmd import _install_plugin_core
+
+ repo = tmp_path / "monorepo"
+ plugin = repo / "integrations" / "hermes"
+ plugin.mkdir(parents=True)
+ _git(repo, "init", "-q")
+ _git(repo, "config", "user.email", "[email protected]")
+ _git(repo, "config", "user.name", "Fixture")
+ _git(repo, "config", "uploadpack.allowFilter", "true")
+ (plugin / "plugin.yaml").write_text("name: nested-demo\n", encoding="utf-8")
+ (repo / "unrelated.bin").write_bytes(b"x" * 4096)
+ _git(repo, "add", ".")
+ _git(repo, "commit", "-qm", "init")
+ sha = _git(repo, "rev-parse", "HEAD")
+ unrelated_blob = _git(repo, "rev-parse", "HEAD:unrelated.bin")
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
+ seen = {}
+
+ def inspect_clone(_manifest, tree):
+ clone = tree.parents[1]
+ seen["worktree"] = sorted(p.name for p in clone.iterdir() if p.name != ".git")
+ seen["missing"] = _git(clone, "rev-list", "--objects", "--missing=print", "HEAD")
+
+ target, _manifest, _name = _install_plugin_core(
+ f"{repo.as_uri()}#integrations/hermes", force=False,
+ ref=sha if pinned else None, before_swap=inspect_clone)
+
+ assert (target / "plugin.yaml").is_file()
+ assert seen["worktree"] == ["integrations"]
+ assert f"?{unrelated_blob}" in seen["missing"].splitlines()
def test_clone_timeout_uses_active_profile_and_bounds_invalid_values(monkeypatch, tmp_path):
diff --git a/tests/hermes_cli/test_plugins_cmd.py b/tests/hermes_cli/test_plugins_cmd.py
index 6d96be902c4..b024c722c9b 100644
--- a/tests/hermes_cli/test_plugins_cmd.py
+++ b/tests/hermes_cli/test_plugins_cmd.py
@@ -765,7 +765,7 @@ class TestReviewedPinScanTrust:
SHA = "a" * 40
def _fake_clone(self, pc, monkeypatch, plugins_dir, extra_file, body):
- def fake_clone(tmp_clone, git_url, revision):
+ def fake_clone(tmp_clone, git_url, revision, subdir=None):
tmp_clone.mkdir()
(tmp_clone / "plugin.yaml").write_text("name: scanme\nmanifest_version: 1\n", encoding="utf-8")
(tmp_clone / extra_file).write_text(body, encoding="utf-8")
@@ -807,7 +807,7 @@ class TestInstallReadabilityGate:
def _clone_with_unreadable_manifest(self, monkeypatch, pc):
real_chmod = os.chmod # the rollback test replaces os.chmod after this fixture runs
- def fake_clone(tmp_clone, git_url, revision):
+ def fake_clone(tmp_clone, git_url, revision, subdir=None):
tmp_clone.mkdir()
(tmp_clone / "plugin.yaml").write_text("name: badperm\nmanifest_version: 1\n", encoding="utf-8")
real_chmod(tmp_clone / "plugin.yaml", 0)
diff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.md
index 12732262b0a..1fa3b52fd72 100644
--- a/website/docs/user-guide/features/plugins.md
+++ b/website/docs/user-guide/features/plugins.md
@@ -161,9 +161,10 @@ plugins:
- disk-cleanup
disabled: # optional deny-list — always wins if a name appears in both
- noisy-plugin
- # Optional: deadline (seconds) for each Git clone or pinned-commit fetch
+ # Optional: deadline (seconds) for each Git clone, fetch or checkout
# during plugin installation, including automatic memory-provider migration.
- # Default 300; values above 3600 are clamped.
+ # Default 300; values above 3600 are clamped. A subdirectory install
+ # (owner/repo/path/to/plugin) downloads only that folder's files.
clone_timeout_seconds: 300
# Optional: wall-clock cap (seconds) for timeout-bounded in-process Python
# plugin hook callbacks (hot-path observers + pre_tool_call). Default 30;