plugin_packs.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. """Plugin packs — declarative, shareable plugin sets.
  2. Every plugin entry MUST pin an exact 40-character commit SHA in ``ref``; tags and branch names are
  3. rejected with an error naming the entry.
  4. """
  5. from __future__ import annotations
  6. import logging
  7. import re
  8. import sys
  9. from dataclasses import dataclass, field
  10. from pathlib import Path
  11. from typing import Any, List, Optional
  12. logger = logging.getLogger(__name__)
  13. _EXACT_SHA_RE = re.compile(r"^[0-9a-fA-F]{40}$")
  14. # Secret-shaped keys are refused in config seeds and stripped from exports; packs declare secrets
  15. # via each plugin's ``requires_env``, which prompts at install time.
  16. _SECRET_KEY_RE = re.compile(r"(?i)(token|secret|passw(or)?d|api[_-]?key|private[_-]?key|credential|auth)")
  17. # plugins.entries.<id> keys a pack may never set (consent state; allow_* gates are also refused).
  18. _RESERVED_ENTRY_KEYS = frozenset({"granted_capabilities", "capabilities_consent"})
  19. _MAX_PACK_BYTES = 1 * 1024 * 1024 # a pack is a small manifest, not a payload
  20. _FETCH_TIMEOUT = 15.0
  21. class PackError(Exception):
  22. """Pack parse/validation/fetch failure (CLI exits non-zero)."""
  23. @dataclass
  24. class PackPluginEntry:
  25. """One pinned plugin in a pack."""
  26. ref: str # exact 40-char commit SHA (lowercased)
  27. name: Optional[str] = None # bare community-index name…
  28. repo: Optional[str] = None # …or owner/repo shorthand / git URL
  29. subdir: Optional[str] = None # path within the repo
  30. @property
  31. def display(self) -> str:
  32. base = self.name or self.repo or "?"
  33. return f"{base}/{self.subdir}" if (self.repo and self.subdir) else base
  34. @property
  35. def install_identifier(self) -> Optional[str]:
  36. """Identifier for the install path; None for bare names (resolved via the plugin catalog)."""
  37. if self.repo:
  38. return f"{self.repo}/{self.subdir}" if self.subdir else self.repo
  39. return None
  40. @dataclass
  41. class PluginPack:
  42. """A parsed, validated pack manifest."""
  43. name: str
  44. description: str = ""
  45. author: str = ""
  46. version: str = ""
  47. plugins: list[PackPluginEntry] = field(default_factory=list)
  48. # plugin id → {entry-key: seed-value}; validated non-secret, non-reserved.
  49. config: dict[str, dict[str, Any]] = field(default_factory=dict)
  50. # Skill-hub ids. Parsed + displayed, NOT installed (documented seam).
  51. skills: list[str] = field(default_factory=list)
  52. # ── Parse + validate ────────────────────────────────────────────────────────────────────────
  53. def _entry_label(item: Any, index: int) -> str:
  54. if isinstance(item, dict):
  55. label = item.get("name") or item.get("repo")
  56. if isinstance(label, str) and label.strip():
  57. return f"'{label.strip()}'"
  58. return f"#{index + 1}"
  59. def _forbidden_key_reason(key: str) -> Optional[str]:
  60. """``"reserved"`` / ``"secret"`` when a config key may never travel in a pack, else None."""
  61. if key in _RESERVED_ENTRY_KEYS or key.startswith("allow_"):
  62. return "reserved"
  63. if _SECRET_KEY_RE.search(key):
  64. return "secret"
  65. return None
  66. def _first_forbidden_key(value: Any, path: str = "") -> Optional[tuple[str, str]]:
  67. """``(dotted key, reason)`` of the first forbidden key at ANY depth of *value*, else None.
  68. A nested mapping (or a mapping inside a list) is the same contract as the top level (#85050)."""
  69. if isinstance(value, dict):
  70. for key, child in value.items():
  71. if isinstance(key, str) and (reason := _forbidden_key_reason(key)):
  72. return f"{path}{key}", reason
  73. if found := _first_forbidden_key(child, f"{path}{key}."):
  74. return found
  75. elif isinstance(value, list):
  76. for child in value:
  77. if found := _first_forbidden_key(child, path):
  78. return found
  79. return None
  80. def _strip_forbidden_keys(value: Any) -> Any:
  81. """Copy of *value* with forbidden keys and non-YAML-scalar leaves removed at every depth."""
  82. if isinstance(value, dict):
  83. return {
  84. key: _strip_forbidden_keys(child) for key, child in value.items()
  85. if isinstance(key, str) and _forbidden_key_reason(key) is None
  86. and (child is None or isinstance(child, (str, int, float, bool, list, dict)))
  87. }
  88. if isinstance(value, list):
  89. return [_strip_forbidden_keys(child) for child in value]
  90. return value
  91. def validate_config_seed(plugin_id: str, seed: Any) -> dict[str, Any]:
  92. """Validate one plugin's config seed mapping and return a copy. Rejects non-dict seeds,
  93. reserved consent keys, ``allow_*`` trust gates, and secret-shaped keys — at any depth."""
  94. if not isinstance(seed, dict):
  95. raise PackError(
  96. f"Pack config for plugin '{plugin_id}' must be a mapping of plugins.entries.{plugin_id} keys.")
  97. for key in seed:
  98. if not isinstance(key, str) or not key.strip():
  99. raise PackError(f"Pack config for plugin '{plugin_id}' has an invalid key: {key!r}.")
  100. found = _first_forbidden_key(seed)
  101. if found is not None:
  102. key, reason = found
  103. if reason == "reserved":
  104. raise PackError(
  105. f"Pack config for plugin '{plugin_id}' sets reserved key "
  106. f"'{key}': packs cannot pre-grant capabilities or trust gates. "
  107. "Capability consent happens interactively at install time.")
  108. raise PackError(
  109. f"Pack config for plugin '{plugin_id}' sets secret-shaped key "
  110. f"'{key}': secrets never travel in packs. Declare the secret in "
  111. "the plugin's requires_env instead — it is prompted at install.")
  112. return dict(seed)
  113. def parse_pack(text: str, *, source: str = "<pack>") -> PluginPack:
  114. """Parse and validate a pack YAML document."""
  115. import hermes_yaml as yaml
  116. try:
  117. raw = yaml.safe_load(text)
  118. except yaml.YAMLError as exc:
  119. raise PackError(f"Pack {source} is not valid YAML: {exc}") from exc
  120. if not isinstance(raw, dict):
  121. raise PackError(f"Pack {source} must be a YAML mapping.")
  122. # Accept the nested form (pack: {name: ...}) as sugar.
  123. meta = raw.get("pack") if isinstance(raw.get("pack"), dict) else raw
  124. name = meta.get("name")
  125. if not isinstance(name, str) or not name.strip():
  126. raise PackError(f"Pack {source} is missing a 'name'.")
  127. plugins_raw = raw.get("plugins")
  128. if not isinstance(plugins_raw, list) or not plugins_raw:
  129. raise PackError(f"Pack {source} must declare a non-empty 'plugins' list.")
  130. entries = [_parse_pack_entry(item, _entry_label(item, i)) for i, item in enumerate(plugins_raw)]
  131. config_raw = raw.get("config") or {}
  132. if not isinstance(config_raw, dict):
  133. raise PackError(f"Pack {source} 'config' must be a mapping of plugin id → settings.")
  134. config = {str(pid): validate_config_seed(str(pid), seed) for pid, seed in config_raw.items()}
  135. skills_raw = raw.get("skills") or []
  136. if not isinstance(skills_raw, list):
  137. raise PackError(f"Pack {source} 'skills' must be a list of skill ids.")
  138. return PluginPack(
  139. name=name.strip(), description=str(meta.get("description") or ""),
  140. author=str(meta.get("author") or ""), version=str(meta.get("version") or ""), plugins=entries,
  141. config=config, skills=[str(s).strip() for s in skills_raw if str(s).strip()])
  142. def _parse_pack_entry(item: Any, label: str) -> PackPluginEntry:
  143. """Validate one ``plugins:`` item (``name`` and/or ``repo``, exact-SHA ``ref``, ``subdir``)."""
  144. if not isinstance(item, dict):
  145. raise PackError(f"Pack plugin entry {label} must be a mapping.")
  146. entry_name = item.get("name")
  147. entry_repo = item.get("repo") or item.get("source")
  148. if isinstance(entry_repo, str):
  149. entry_repo = entry_repo.removeprefix("github:").strip() or None
  150. if entry_name is not None and (not isinstance(entry_name, str) or not entry_name.strip()):
  151. raise PackError(f"Pack plugin entry {label} has an invalid 'name'.")
  152. entry_name = entry_name.strip() if isinstance(entry_name, str) else None
  153. if not entry_name and not entry_repo:
  154. raise PackError(
  155. f"Pack plugin entry {label} needs either 'name' (community "
  156. "index) or 'repo' (owner/repo or git URL).")
  157. ref = item.get("ref") or item.get("version")
  158. if not isinstance(ref, str) or not _EXACT_SHA_RE.fullmatch(ref.strip()):
  159. raise PackError(
  160. f"Pack plugin entry {label} has ref {ref!r}: refs must be "
  161. "exact 40-character commit SHAs (tags and branch names are "
  162. "rejected — pin the commit for reproducible installs).")
  163. subdir = item.get("subdir")
  164. if subdir is not None and (not isinstance(subdir, str) or not subdir.strip("/")):
  165. raise PackError(f"Pack plugin entry {label} has an invalid 'subdir'.")
  166. return PackPluginEntry(
  167. ref=ref.strip().lower(), name=entry_name, repo=entry_repo,
  168. subdir=subdir.strip("/") if isinstance(subdir, str) else None)
  169. def load_pack(path_or_url: str) -> PluginPack:
  170. """Load a pack from a local file path or an ``https://`` URL."""
  171. if path_or_url.startswith("https://"):
  172. try:
  173. import httpx
  174. resp = httpx.get(path_or_url, timeout=_FETCH_TIMEOUT, follow_redirects=True)
  175. resp.raise_for_status()
  176. text = resp.text
  177. except Exception as exc:
  178. raise PackError(f"Could not fetch pack from {path_or_url}: {exc}") from exc
  179. if len(text.encode("utf-8", errors="ignore")) > _MAX_PACK_BYTES:
  180. raise PackError("Pack payload exceeds the 1 MiB size limit.")
  181. return parse_pack(text, source=path_or_url)
  182. if path_or_url.startswith(("http://", "file://", "ftp://")):
  183. raise PackError("Pack URLs must use https:// (or pass a local file path).")
  184. path = Path(path_or_url).expanduser()
  185. if not path.is_file():
  186. raise PackError(f"Pack file not found: {path}")
  187. if path.stat().st_size > _MAX_PACK_BYTES:
  188. raise PackError("Pack file exceeds the 1 MiB size limit.")
  189. return parse_pack(path.read_text(encoding="utf-8-sig"), source=str(path))
  190. # ── Resolution (bare index names → owner/repo) + review screen ──────────────────────────────
  191. @dataclass
  192. class ResolvedPackPlugin:
  193. """A pack entry resolved to an installable identifier."""
  194. entry: PackPluginEntry
  195. identifier: Optional[str] # None when index resolution failed
  196. index_capabilities: list[str] = field(default_factory=list)
  197. resolve_error: Optional[str] = None
  198. def resolve_pack_plugins(pack: PluginPack) -> list[ResolvedPackPlugin]:
  199. """Resolve every entry; bare names go through the curated plugin catalog. Failures do not raise —
  200. they are carried per-entry so the review screen shows them and install reports partial failure."""
  201. resolved: list[ResolvedPackPlugin] = []
  202. catalog_entries = None
  203. for entry in pack.plugins:
  204. if entry.install_identifier is not None:
  205. resolved.append(ResolvedPackPlugin(entry=entry, identifier=entry.install_identifier))
  206. continue
  207. try:
  208. if catalog_entries is None:
  209. from hermes_cli.plugin_catalog import load_catalog_live
  210. catalog_entries = load_catalog_live()
  211. except Exception as exc: # catalog load must not crash pack handling
  212. resolved.append(ResolvedPackPlugin(
  213. entry=entry, identifier=None, resolve_error=f"plugin catalog unavailable: {exc}"))
  214. continue
  215. match = next((e for e in catalog_entries if e.name == (entry.name or "")), None)
  216. if match is None:
  217. resolved.append(ResolvedPackPlugin(
  218. entry=entry, identifier=None, resolve_error="not found in the plugin catalog"))
  219. continue
  220. caps = match.capabilities
  221. resolved.append(ResolvedPackPlugin(
  222. entry=entry, identifier=match.install_identifier,
  223. index_capabilities=[*caps.provides_tools, *caps.provides_hooks, *caps.provides_middleware]))
  224. return resolved
  225. def render_pack_review(console, pack: PluginPack, resolved: list[ResolvedPackPlugin]) -> None:
  226. """Print the full pack review screen (mandatory before install)."""
  227. from rich.table import Table
  228. header = f"[bold]{pack.name}[/bold]" + (f" v{pack.version}" if pack.version else "")
  229. if pack.author:
  230. header += f" — by {pack.author}"
  231. console.print(f"\n{header}")
  232. if pack.description:
  233. console.print(f"[dim]{pack.description}[/dim]")
  234. table = Table(show_header=True, header_style="bold")
  235. table.add_column("Plugin")
  236. table.add_column("Source")
  237. table.add_column("Pinned ref")
  238. table.add_column("Capabilities (declared)")
  239. for rp in resolved:
  240. caps = ", ".join(rp.index_capabilities) if rp.index_capabilities else "(shown at install)"
  241. source = rp.identifier or f"[red]unresolved: {rp.resolve_error}[/red]"
  242. table.add_row(rp.entry.display, source, rp.entry.ref[:12], caps)
  243. console.print(table)
  244. if pack.config:
  245. console.print("[bold]Config seeds[/bold] (plugins.entries.<id>, non-secret):")
  246. for plugin_id, seed in pack.config.items():
  247. for key, value in seed.items():
  248. console.print(f" {plugin_id}.{key} = {value!r}")
  249. if pack.skills:
  250. console.print(
  251. "[yellow]Pack lists skills (NOT auto-installed yet):[/yellow] " + ", ".join(pack.skills))
  252. console.print("[dim]Install them manually, e.g. `hermes skills install <id>`.[/dim]")
  253. console.print(
  254. "\n[dim]Installing a pack runs third-party code × "
  255. f"{len(resolved)} plugins. Each plugin's declared capabilities still "
  256. "require individual consent after install — a pack never bulk-grants.[/dim]")
  257. # ── Install fan-out ─────────────────────────────────────────────────────────────────────────
  258. @dataclass
  259. class PackInstallResult:
  260. """Outcome of one plugin install within a pack."""
  261. display: str
  262. ok: bool
  263. installed_name: Optional[str] = None
  264. error: Optional[str] = None
  265. def _seed_plugin_config(plugin_id: str, seed: dict[str, Any], console) -> None:
  266. """Seed plugins.entries.<plugin_id> keys that are not already set (user values always win)."""
  267. from hermes_cli.config import load_config, save_config
  268. seed = validate_config_seed(plugin_id, seed)
  269. config = load_config()
  270. entry = config.setdefault("plugins", {}).setdefault("entries", {}).setdefault(plugin_id, {})
  271. if not isinstance(entry, dict):
  272. console.print(
  273. f"[yellow]Warning:[/yellow] plugins.entries.{plugin_id} is not a "
  274. "mapping; skipping pack config seed.")
  275. return
  276. wrote = False
  277. for key, value in seed.items():
  278. if key in entry:
  279. console.print(f"[dim] plugins.entries.{plugin_id}.{key} already set — keeping your value.[/dim]")
  280. continue
  281. entry[key] = value
  282. wrote = True
  283. if wrote:
  284. save_config(config)
  285. console.print(f"[dim] Seeded plugins.entries.{plugin_id} from pack.[/dim]")
  286. def install_pack_plugins(
  287. pack: PluginPack,
  288. resolved: list[ResolvedPackPlugin],
  289. console,
  290. *,
  291. force: bool = False,
  292. ) -> list[PackInstallResult]:
  293. """Fan a pack out to N ordinary pinned installs; never raises per-plugin.
  294. Each plugin goes through the exact-ref install path, then the SAME per-plugin capability
  295. consent flow as a single install (a pack never bulk-grants). Successful installs are enabled
  296. (the user consented via the review screen) and their config seed applied.
  297. """
  298. from hermes_cli.plugins_cmd import (
  299. PluginOperationError,
  300. _declared_capabilities_from_manifest,
  301. _install_plugin_core,
  302. _prompt_plugin_env_vars,
  303. _run_capability_consent,
  304. _set_plugin_enabled,
  305. )
  306. from hermes_cli.plugins_admission import AdmissionRefused
  307. from hermes_cli.plugins_cmd_install import recorded_install
  308. results: list[PackInstallResult] = []
  309. def _fail(display: str, error: str) -> None:
  310. results.append(PackInstallResult(display=display, ok=False, error=error))
  311. console.print(f"[red]✗[/red] {display}: {error}")
  312. for rp in resolved:
  313. display = rp.entry.display
  314. if rp.identifier is None:
  315. _fail(display, rp.resolve_error)
  316. continue
  317. console.print(f"[dim]Installing {display} @ {rp.entry.ref[:12]}...[/dim]")
  318. try:
  319. # A bare pack name resolved through the plugin catalog; repo entries are custom sources.
  320. _target, manifest, installed_name = recorded_install(
  321. lambda: _install_plugin_core(rp.identifier, force=force, ref=rp.entry.ref),
  322. catalog_name=None if rp.entry.repo else rp.entry.name, identifier=rp.identifier)
  323. except PluginOperationError as exc:
  324. _fail(display, str(exc))
  325. continue
  326. except Exception as exc: # keep the fan-out alive on unexpected errors
  327. logger.exception("pack install failed for %s", display)
  328. _fail(display, str(exc))
  329. continue
  330. # Secrets are prompted (requires_env), never carried by the pack.
  331. try:
  332. _prompt_plugin_env_vars(manifest, console)
  333. except Exception:
  334. logger.debug("requires_env prompt failed for %s", installed_name, exc_info=True)
  335. try:
  336. _set_plugin_enabled(installed_name, enable=True)
  337. except AdmissionRefused as exc:
  338. _fail(display, str(exc))
  339. continue
  340. # Per-plugin capability consent — the SAME flow as a single install (#64228). A pack never
  341. # bulk-grants capabilities.
  342. declared = _declared_capabilities_from_manifest(manifest, installed_name)
  343. if declared:
  344. _run_capability_consent(console, installed_name, declared, context="install")
  345. seed = pack.config.get(installed_name)
  346. if seed is None and rp.entry.name and rp.entry.name != installed_name:
  347. seed = pack.config.get(rp.entry.name)
  348. if seed:
  349. try:
  350. _seed_plugin_config(installed_name, seed, console)
  351. except PackError as exc:
  352. console.print(f"[yellow]Warning:[/yellow] {exc}")
  353. console.print(f"[green]✓[/green] {display} installed as [bold]{installed_name}[/bold].")
  354. results.append(PackInstallResult(display=display, ok=True, installed_name=installed_name))
  355. return results
  356. # ── Export ──────────────────────────────────────────────────────────────────────────────────
  357. _GITHUB_HTTPS_RE = re.compile(r"^https://github\.com/(?P<owner>[^/\s]+)/(?P<repo>[^/\s#]+?)(?:\.git)?$")
  358. def _source_to_repo_subdir(source: str) -> tuple[Optional[str], Optional[str]]:
  359. """Turn recorded install-metadata source into (repo-or-url, subdir)."""
  360. if not source:
  361. return None, None
  362. base, _, subdir = source.partition("#")
  363. subdir = subdir.strip("/") or None
  364. m = _GITHUB_HTTPS_RE.match(base.strip())
  365. if m:
  366. return f"{m.group('owner')}/{m.group('repo')}", subdir
  367. return base.strip() or None, subdir
  368. def _sanitized_entry_config(plugin_id: str) -> dict[str, Any]:
  369. """Exportable plugins.entries.<id> keys: YAML scalars/containers only, reserved and
  370. secret-shaped keys stripped at every depth."""
  371. try:
  372. from hermes_cli.config import load_config
  373. config = load_config() or {}
  374. except Exception:
  375. return {}
  376. entry = ((config.get("plugins") or {}).get("entries") or {}).get(plugin_id)
  377. if not isinstance(entry, dict):
  378. return {}
  379. return _strip_forbidden_keys(entry)
  380. def export_pack(*, enabled_only: bool = False, pack_name: str = "my-hermes-pack") -> tuple[str, list[str]]:
  381. """Build pack YAML from the current install; returns ``(yaml_text, warnings)``. Plugins with
  382. unknown Git provenance (no install metadata) become warnings + YAML comments, never entries."""
  383. import hermes_yaml as yaml
  384. from hermes_cli.plugins_cmd import _get_enabled_set, _plugins_dir, _read_install_metadata
  385. metadata = _read_install_metadata()
  386. enabled = _get_enabled_set()
  387. installed = sorted(d.name for d in _plugins_dir().iterdir() if d.is_dir() and not d.name.startswith("."))
  388. if enabled_only:
  389. installed = [n for n in installed if n in enabled]
  390. entries: list[dict[str, Any]] = []
  391. config: dict[str, dict[str, Any]] = {}
  392. warnings: list[str] = []
  393. for plugin_id in installed:
  394. record = metadata.get(plugin_id) or {}
  395. source = record.get("source")
  396. revision = record.get("revision")
  397. repo, subdir = _source_to_repo_subdir(str(source or ""))
  398. if not repo or not isinstance(revision, str) or not _EXACT_SHA_RE.fullmatch(revision):
  399. warnings.append(
  400. f"{plugin_id}: no Git provenance (local-only or pre-metadata "
  401. "install) — listed as a comment, not installable from this pack.")
  402. continue
  403. entry: dict[str, Any] = {"repo": repo, "ref": revision.lower()}
  404. if subdir:
  405. entry["subdir"] = subdir
  406. entries.append(entry)
  407. seed = _sanitized_entry_config(plugin_id)
  408. if seed:
  409. config[plugin_id] = seed
  410. doc: dict[str, Any] = {
  411. "name": pack_name,
  412. "description": "Exported by `hermes plugins pack export`.",
  413. "version": "1.0.0",
  414. "plugins": entries,
  415. }
  416. if config:
  417. doc["config"] = config
  418. text = yaml.safe_dump(doc, sort_keys=False, default_flow_style=False)
  419. if warnings:
  420. text = "\n".join(f"# WARNING (not exported): {w}" for w in warnings) + f"\n{text}"
  421. return text, warnings
  422. # ── CLI commands ────────────────────────────────────────────────────────────────────────────
  423. def _load_and_review(console, source: str):
  424. """Load *source* (exit 1 on PackError), resolve it, print the review screen."""
  425. from hermes_cli.plugins_cmd import _fail
  426. try:
  427. pack = load_pack(source)
  428. except PackError as exc:
  429. _fail(console, f"[red]Error:[/red] {exc}")
  430. resolved = resolve_pack_plugins(pack)
  431. render_pack_review(console, pack, resolved)
  432. return pack, resolved
  433. def cmd_pack_show(source: str) -> None:
  434. """``hermes plugins pack show <path-or-url>`` — dry-run review."""
  435. from hermes_cli.plugins_cmd import _console
  436. console = _console()
  437. _pack, resolved = _load_and_review(console, source)
  438. unresolved = [rp for rp in resolved if rp.identifier is None]
  439. if unresolved:
  440. console.print(
  441. f"\n[yellow]{len(unresolved)} entr{'y' if len(unresolved) == 1 else 'ies'} "
  442. "could not be resolved — install would skip them and exit non-zero.[/yellow]")
  443. console.print("\n[dim]Dry run only. Install with `hermes plugins pack install ...`.[/dim]")
  444. def cmd_pack_install(source: str, *, force: bool = False) -> None:
  445. """``hermes plugins pack install <path-or-url>``: mandatory review screen -> one pack-level
  446. consent -> pinned fan-out installs -> per-plugin capability consent. Exit 1 if any failed."""
  447. from hermes_cli.plugins_cmd import _ask_yes, _console, _fail, _is_tty
  448. console = _console()
  449. pack, resolved = _load_and_review(console, source)
  450. # Mandatory review confirmation — no --yes in v1 (arbitrary third-party code × N).
  451. if not _is_tty():
  452. _fail(console, (
  453. "[red]Error:[/red] Pack install requires an interactive terminal "
  454. "to review and confirm the pack contents (no --yes in v1)."))
  455. if not _ask_yes(f"\nInstall {len(resolved)} plugin(s) from pack '{pack.name}'? [y/N] ", console.input):
  456. _fail(console, "[dim]Aborted — nothing installed.[/dim]")
  457. results = install_pack_plugins(pack, resolved, console, force=force)
  458. ok = [r for r in results if r.ok]
  459. failed = [r for r in results if not r.ok]
  460. console.print(f"\n[bold]Pack '{pack.name}':[/bold] {len(ok)} installed, {len(failed)} failed.")
  461. for r in failed:
  462. console.print(f" [red]✗[/red] {r.display}: {r.error}")
  463. if ok:
  464. console.print("[dim]Restart the gateway for the plugins to take effect:[/dim]")
  465. console.print("[dim] hermes gateway restart[/dim]")
  466. if failed:
  467. sys.exit(1)
  468. def cmd_pack_export(*, enabled_only: bool = False, name: str = "my-hermes-pack") -> None:
  469. """``hermes plugins pack export [--enabled-only]`` — pack YAML on stdout."""
  470. from rich.console import Console
  471. console = Console(stderr=True)
  472. try:
  473. text, warnings = export_pack(enabled_only=enabled_only, pack_name=name)
  474. except Exception as exc:
  475. console.print(f"[red]Error:[/red] Could not export pack: {exc}")
  476. sys.exit(1)
  477. for w in warnings:
  478. console.print(f"[yellow]Warning:[/yellow] {w}")
  479. sys.stdout.write(text)
  480. def pack_command(args) -> None:
  481. """Dispatch ``hermes plugins pack <action>``."""
  482. handler = _PACK_ACTIONS.get(getattr(args, "pack_action", None))
  483. if handler is None:
  484. from hermes_cli.plugins_cmd import _console, _fail
  485. _fail(_console(), "[red]Error:[/red] Usage: hermes plugins pack {install|export|show}")
  486. handler(args)
  487. _PACK_ACTIONS = {
  488. "install": lambda args: cmd_pack_install(args.source, force=getattr(args, "force", False)),
  489. "export": lambda args: cmd_pack_export(
  490. enabled_only=getattr(args, "enabled_only", False),
  491. name=getattr(args, "name", None) or "my-hermes-pack"),
  492. "show": lambda args: cmd_pack_show(args.source),
  493. }