plugins_cmd_install.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  1. """``hermes plugins install``: dependency/env consent, the atomic clone-scan-publish installer core, and
  2. the dashboard/TUI non-interactive install.
  3. Sibling of :mod:`hermes_cli.plugins_cmd` (the facade re-exports the names other modules use and is
  4. imported late here, never at module level).
  5. """
  6. from __future__ import annotations
  7. import logging
  8. import os
  9. import sys
  10. import tempfile
  11. from contextlib import ExitStack, contextmanager
  12. from contextvars import ContextVar
  13. from pathlib import Path
  14. from typing import Any, Callable, Optional
  15. from hermes_cli.cli_output import line_input
  16. from hermes_cli.plugin_install_phase import InstallPhase
  17. logger = logging.getLogger(__name__)
  18. # Answers to the dependency questions, reused while one plugin is installed into several profile
  19. # homes that share one environment (memory-provider migration on ``hermes update``, #125794).
  20. _shared_answers: ContextVar[Optional[dict]] = ContextVar("plugin_dependency_answers", default=None)
  21. @contextmanager
  22. def shared_dependency_answers():
  23. """Inside this block each dependency question is asked once; repeats reuse the first answer."""
  24. token = _shared_answers.set({})
  25. try:
  26. yield
  27. finally:
  28. _shared_answers.reset(token)
  29. def _ask_yes_no(key: tuple, prompt: str, console) -> bool:
  30. answers = _shared_answers.get()
  31. if answers is not None and key in answers:
  32. console.print(f" [dim]Reusing your answer for the first profile: {'yes' if answers[key] else 'no'}[/dim]")
  33. return answers[key]
  34. try:
  35. accepted = input(prompt).strip().lower() in {"y", "yes"}
  36. except (EOFError, KeyboardInterrupt):
  37. accepted = False
  38. if answers is not None:
  39. answers[key] = accepted
  40. return accepted
  41. def _pc():
  42. """The facade, read at call time: tests patch ``plugins_cmd.<name>`` and sibling calls must see it."""
  43. from hermes_cli import plugins_cmd
  44. return plugins_cmd
  45. class _ConsentRefusal(str):
  46. """A refusal reason (user-facing text) carrying its closed extension-install ``failure_class``,
  47. so publication classifies the refusal without matching the copy."""
  48. def __new__(cls, text: str, failure_class: str) -> _ConsentRefusal:
  49. refusal = super().__new__(cls, text)
  50. refusal.failure_class = failure_class
  51. return refusal
  52. def _install_plugin_python_deps(
  53. manifest: dict, target: Path, console, *, assume_yes: bool = False
  54. ) -> tuple[bool, Optional[str]]:
  55. """Consent gate for plugin python deps (settled 2026-09-02; C13 rework).
  56. Node sidecar: y/n prompt → ``npm ci`` into the plugin's OWN
  57. node_modules (separate question, failure never blocks enable).
  58. Python deps: NO resolution here — the resolve runs inside the ONE
  59. admission transaction when the enable commits
  60. (:func:`_admit_and_save_plugin_sets`), so the environment and the
  61. config always change together or not at all. Returns (consented,
  62. reason): consented=True when the user accepted (or no prompt was
  63. needed); a decline/skip returns False and NOTHING is installed.
  64. Never raises — the caller keeps the plugin installed-but-disabled.
  65. *assume_yes* is ``--yes-deps``: the user's own non-interactive answer
  66. to the Python question, so a headless install is not refused (#122134).
  67. """
  68. from pm.plugin_declarations import read_python_declaration
  69. try:
  70. declaration = read_python_declaration(target)
  71. deps = declaration.install_requirements
  72. except Exception as exc:
  73. return False, _ConsentRefusal(f"invalid Python dependency declaration: {exc}", "manifest_invalid")
  74. has_python = declaration.installs_packages
  75. has_package_json = (target / "package.json").is_file()
  76. if not has_python and not has_package_json:
  77. return True, None # no declared deps at all
  78. # Node sidecar (package.json): the npm ci executor — separate consent
  79. # question, same try-then-enable posture. Failure never blocks the
  80. # python path below.
  81. node_reason = None
  82. if has_package_json:
  83. console.print(f"\n[bold]{manifest.get('name', 'this plugin')}[/bold] declares Node dependencies (package.json).")
  84. node_ok = sys.stdin.isatty() and sys.stdout.isatty() and _ask_yes_no(
  85. ("node", manifest.get("name")), " Install them into the plugin's own node_modules now? [y/N]: ", console)
  86. if node_ok:
  87. from pm.workspace import install_node_sidecar
  88. node_reason = install_node_sidecar(target, explicit=True)
  89. if node_reason:
  90. console.print(f"[yellow]⚠[/yellow] Node deps: {node_reason}")
  91. else:
  92. console.print("[dim]Skipped Node deps — run `hermes plugins install` again to retry.[/dim]\n")
  93. if not has_python:
  94. return True, None
  95. return _consent_python_deps(manifest.get("name", "this plugin"), deps, console, assume_yes=assume_yes)
  96. def _consent_python_deps(
  97. plugin_name: str, deps: tuple[str, ...], console, *, assume_yes: bool = False
  98. ) -> tuple[bool, Optional[str]]:
  99. """The y/N gate for Python deps entering the shared environment — install,
  100. reinstall AND an update that declares new ones all pass through here.
  101. Returns (consented, reason); never raises. *assume_yes* (``--yes-deps``)
  102. answers the question on the user's behalf ONLY because the user passed the
  103. flag; the non-interactive default below stays a refusal."""
  104. console.print(
  105. f"\n[bold]{plugin_name}[/bold] declares Python dependencies:"
  106. )
  107. if deps:
  108. for dep in deps:
  109. console.print(f" - {dep}")
  110. else:
  111. console.print(" - (declared in its pyproject.toml)")
  112. # An explicit --yes-deps is the user's own answer, TTY or not.
  113. if assume_yes:
  114. console.print(
  115. "[dim]Consent given up front — preparing them without prompting.[/dim]\n"
  116. )
  117. return True, None
  118. # A decline or non-interactive invocation leaves the new plugin disabled.
  119. if not (sys.stdin.isatty() and sys.stdout.isatty()):
  120. console.print(
  121. "[dim]Non-interactive install — skipping dependency install. "
  122. "Run `hermes plugins enable` when ready to prepare them.[/dim]\n"
  123. )
  124. return False, _ConsentRefusal("dependency install skipped (non-interactive)", "non_interactive")
  125. if not _ask_yes_no(("python", plugin_name, deps), " Prepare these with Hermes through PM now? [y/N]: ", console):
  126. console.print(
  127. "[dim]Skipped — run `hermes plugins enable` when ready "
  128. "to prepare them.[/dim]\n"
  129. )
  130. return False, _ConsentRefusal("dependency install declined", "deps_declined")
  131. # Consent only — the python-deps resolution itself runs inside the ONE
  132. # admission transaction at enable-commit time (C13): env + config move
  133. # together or not at all.
  134. return True, None
  135. def _python_dependency_summary(target: Path, warnings: list[str]) -> list[str]:
  136. """Read dashboard dependency details; publication and admission own installation."""
  137. from pm.plugin_declarations import read_python_declaration
  138. try:
  139. return list(read_python_declaration(target).install_requirements)
  140. except Exception as exc:
  141. warnings.append(f"Could not read Python dependencies: {exc}")
  142. return []
  143. def _prompt_plugin_env_vars(manifest: dict, console) -> None:
  144. """Prompt for unset ``requires_env`` variables and save the answers to the user's ``.env``."""
  145. missing = _pc()._missing_env_specs(manifest)
  146. if not missing:
  147. return
  148. from hermes_cli.config import save_env_value
  149. from hermes_constants import display_hermes_home
  150. plugin_name = manifest.get("name", "this plugin")
  151. console.print(f"\n[bold]{plugin_name}[/bold] requires the following environment variables:\n")
  152. for spec in missing:
  153. name = spec["name"]
  154. desc = spec.get("description", "")
  155. url = spec.get("url", "")
  156. console.print(f" {name}" + (f" — {desc}" if desc else ""))
  157. if url:
  158. console.print(f" [dim]Get yours at: {url}[/dim]")
  159. try:
  160. value = (_pc().masked_secret_prompt if spec.get("secret", False) else line_input)(f" {name}: ").strip()
  161. except (EOFError, KeyboardInterrupt):
  162. console.print(f"\n[dim] Skipped (you can set these later in {display_hermes_home()}/.env)[/dim]")
  163. return
  164. if value:
  165. save_env_value(name, value)
  166. os.environ[name] = value
  167. console.print(f" [green]✓[/green] Saved to {display_hermes_home()}/.env")
  168. else:
  169. console.print(f" [dim] Skipped (set {name} in {display_hermes_home()}/.env later)[/dim]")
  170. console.print()
  171. def _display_after_install(plugin_dir: Path, identifier: str, *, brief: bool = False) -> None:
  172. """Show after-install.md if it exists, otherwise a default message (skipped when *brief*)."""
  173. from rich.markdown import Markdown
  174. from rich.panel import Panel
  175. console = _pc()._console()
  176. after_install = plugin_dir / "after-install.md"
  177. if brief and not after_install.exists():
  178. return
  179. if after_install.exists():
  180. body, title = Markdown(after_install.read_text(encoding="utf-8-sig")), None
  181. else:
  182. body = f"[green bold]Plugin installed:[/] {identifier}\n[dim]Location:[/] {plugin_dir}"
  183. title = "✓ Installed"
  184. console.print()
  185. console.print(Panel(body, border_style="green", title=title, expand=False))
  186. console.print()
  187. def _check_manifest_version(manifest: dict, plugin_name: str) -> None:
  188. """Reject manifests declaring a newer ``manifest_version`` than this installer supports."""
  189. from pm.plugin_declarations import manifest_version_error
  190. reason = manifest_version_error(manifest, plugin_name)
  191. if reason:
  192. from hermes_cli.config import recommended_update_command
  193. raise _pc().PluginOperationError(f"{reason} Run {recommended_update_command()} to update Hermes.",
  194. failure_class="incompatible")
  195. def _read_manifest_for_install(plugin_dir: Path) -> dict:
  196. """A candidate's unreadable or malformed manifest must stop publication."""
  197. native = _pc()._native_manifest_file(plugin_dir)
  198. if native is not None:
  199. try:
  200. manifest = _pc()._load_yaml_manifest(native)
  201. except Exception as exc:
  202. raise _pc().PluginOperationError(f"Could not read plugin manifest {native}: {exc}",
  203. failure_class="manifest_invalid") from exc
  204. if not isinstance(manifest, dict):
  205. raise _pc().PluginOperationError(f"Plugin manifest must be a mapping: {native}",
  206. failure_class="manifest_invalid")
  207. return manifest
  208. if not _pc()._has_portable_manifest(plugin_dir):
  209. return {}
  210. try:
  211. from hermes_cli.agent_plugins import read_agent_plugin_manifest
  212. manifest, diagnostics = read_agent_plugin_manifest(plugin_dir)
  213. except Exception as exc:
  214. raise _pc().PluginOperationError(f"Portable plugin manifest validation failed: {exc}",
  215. failure_class="manifest_invalid") from exc
  216. for diagnostic in diagnostics:
  217. logger.warning("Agent Plugin install: %s", diagnostic.message)
  218. return manifest
  219. def _probe_readable(path: Path) -> None:
  220. """Raise ``OSError`` unless *path* can actually be listed (dir) or opened for reading (file)."""
  221. if path.is_dir():
  222. os.listdir(path)
  223. else:
  224. with open(path, "rb"):
  225. pass
  226. def _ensure_tree_readable(root: Path, plugins_dir: Path) -> None:
  227. """Refuse to ship a tree Hermes cannot read back. A clone can land unreadable (Windows ACL
  228. inheritance -> WinError 5, a mode-000 file) and discovery would then skip the plugin forever
  229. (#111804); repair ``u+rX`` where the OS supports it, otherwise fail before anything moves."""
  230. paths = [root]
  231. for dirpath, dirnames, filenames in os.walk(root):
  232. paths.extend(Path(dirpath) / name for name in (*dirnames, *filenames))
  233. for path in paths:
  234. try:
  235. _probe_readable(path)
  236. continue
  237. except OSError:
  238. if os.name != "nt": # chmod only toggles the read-only bit on Windows; ACLs need icacls
  239. try:
  240. os.chmod(path, os.stat(path).st_mode | (0o500 if path.is_dir() else 0o400))
  241. except OSError:
  242. pass
  243. try:
  244. _probe_readable(path)
  245. except OSError as exc:
  246. fix = (f'icacls "{plugins_dir}" /grant:r "%USERNAME%":(OI)(CI)F /T' if os.name == "nt"
  247. else f"chmod -R u+rX {plugins_dir}")
  248. raise _pc().PluginOperationError(
  249. f"Installed file {path.relative_to(root)} is not readable ({exc.strerror or exc}); "
  250. f"nothing was installed. Fix permissions on {plugins_dir} (e.g. `{fix}`) and retry.",
  251. failure_class="permission",
  252. ) from exc
  253. def _refuse_unavailable_portable_plugin(plugin_name: str, tree: Path, app_title: Optional[str] = None) -> None:
  254. """Refuse a portable plugin whose app is missing here, in the same sentence the runtime surfaces use.
  255. *app_title* is the catalog's human name for the app ("Blender"); without it the server name stands in."""
  256. if not (tree / "plugin.json").is_file():
  257. return
  258. from hermes_cli.agent_plugins import load_agent_plugin
  259. from hermes_platform.resolver.availability import availability
  260. from tools.mcp_liveness import availability_problem, describe
  261. try:
  262. package = load_agent_plugin(tree, tree.parent / ".hermes-install-data")
  263. except ValueError as exc:
  264. raise _pc().PluginOperationError(f"Plugin '{plugin_name}' is unavailable: {exc}.",
  265. failure_class="manifest_invalid") from exc
  266. for server_decl in package.server_declarations.values():
  267. result = availability(server_decl.declaration)
  268. if result.offerable:
  269. continue
  270. problem = availability_problem(result)
  271. reason = (describe(server_decl.declaration, result, problem, display_name=app_title)
  272. if problem else f"its app is unavailable ({result.state}).")
  273. raise _pc().PluginOperationError(f"Can't install plugin '{plugin_name}': {reason}",
  274. failure_class="incompatible")
  275. def _known_issue_warnings(entry) -> list[str]:
  276. """Catalog ``known_issues`` are informational (#124058): surface them as warnings, never a gate.
  277. The guard for the traps they describe belongs at the mode-selection seam (#122341 / #123771).
  278. """
  279. return [f"Known issue: {issue}" for issue in entry.known_issues]
  280. def interactive_scan_decision(console, verb: str) -> Callable[[Any], bool]:
  281. """The terminal ``[y/N]`` that accepts a caution verdict, shared by install and update (*verb*)."""
  282. def decide(scan_result) -> bool:
  283. from tools.plugin_guard import format_scan_report
  284. console.print()
  285. console.print("[yellow]⚠ Security scan flagged this plugin:[/yellow]")
  286. console.print(format_scan_report(scan_result))
  287. return _pc()._is_tty() and _pc()._ask_yes(f" {verb} anyway? Only continue if you trust the source. [y/N]: ")
  288. return decide
  289. def scan_blocked_result(exc) -> dict[str, Any]:
  290. """The non-interactive surfaces' answer to a scan block: the verdict and findings, so the client can
  291. show them and, for a caution verdict, retry with ``force``."""
  292. fields = ("pattern_id", "severity", "category", "file", "line", "description")
  293. return {
  294. "ok": False, "error": str(exc), "scan_blocked": True,
  295. "scan_verdict": getattr(exc.scan_result, "verdict", "dangerous"),
  296. "scan_findings": [
  297. {k: getattr(f, k) for k in fields}
  298. for f in (exc.scan_result.findings if exc.scan_result is not None else ())
  299. ],
  300. }
  301. def _clone_at_reviewed_commit(tmp_clone: Path, git_url: str, requested_revision: Optional[str],
  302. inspected_sha: Optional[str], subdir: Optional[str], *, catalog_pin: bool = False) -> str:
  303. """Clone *git_url* and return the checked-out sha. *inspected_sha* is the commit the install dialog's
  304. ``inspect`` read and the user reviewed: a branch that moved since is refused, never installed. The
  305. clone stays an ordinary checkout of the branch (a detached one at the old commit could not ``git
  306. pull`` later), so the install stays unpinned and ``update`` still follows the branch. A retained pin
  307. that names another commit is refused too. A *catalog_pin* install clones the catalog's CURRENT pin
  308. (possibly an annotated tag), which a re-pin since the dialog opened moves: the commit actually checked
  309. out is what must equal the reviewed one."""
  310. if not inspected_sha:
  311. return _pc()._clone_plugin_repo(tmp_clone, git_url, requested_revision, subdir)
  312. sha = _pc()._normalize_exact_revision(inspected_sha)
  313. if not catalog_pin and requested_revision is not None and requested_revision != sha:
  314. raise _pc().PluginOperationError(
  315. f"This plugin is pinned to commit {requested_revision[:12]}, not the commit {sha[:12]} you reviewed. "
  316. "Reinstall it with that pin, or re-open the install dialog.", failure_class="already_installed")
  317. head = _pc()._clone_plugin_repo(tmp_clone, git_url, requested_revision, subdir)
  318. git_exe = _pc()._resolve_git_executable()
  319. if git_exe:
  320. sha = _pc()._git_resolve_commit(tmp_clone, git_exe, sha)
  321. if head != sha:
  322. raise _pc().PluginSourceMoved(
  323. f"The source changed since you reviewed it: it is now at commit {head[:12]}, not {sha[:12]}. "
  324. "Re-open the install dialog to review the new version.")
  325. return head
  326. def _install_plugin_core(
  327. identifier: str,
  328. *,
  329. force: bool,
  330. accept_caution: Optional[bool] = None,
  331. ref: Optional[str] = None,
  332. scan_decision_cb=None,
  333. reviewed_pin: Optional[str] = None,
  334. python_deps: bool = True,
  335. assume_deps_consent: bool = False,
  336. catalog: Optional[dict] = None,
  337. allow_removed: bool = False,
  338. before_swap=None,
  339. app_title: Optional[str] = None,
  340. inspected_sha: Optional[str] = None,
  341. ) -> tuple[Path, dict, str]:
  342. """Clone a Git plugin and atomically record its source and exact revision.
  343. *reviewed_pin* is the curated-catalog sha for this install; the scan trusts the tree
  344. only when the checked-out revision is exactly that sha (an annotated-tag pin is peeled to
  345. its commit first — HEAD can only ever be the commit). *python_deps* False refuses active
  346. replacements; it never bypasses PM dependency admission. *assume_deps_consent* is the
  347. caller's ``--yes-deps`` answer carried into the publication consent gate, so a headless
  348. install of an active replacement is not refused non-interactively (#122134). *catalog*
  349. (``{"name", "repo", "tier", "pin"}``) is recorded on the install-metadata record with the
  350. checked-out sha — provenance lives OUTSIDE the plugin tree, so a repo cannot forge it;
  351. its ``pin`` is kept only when the checkout satisfies it (a ``--ref`` install is off-pin).
  352. *allow_removed* records that the user knowingly bypassed the kill list.
  353. *before_swap(manifest, tree)* runs on the manifest-checked clone BEFORE the security scan, so
  354. the single scan and portable-package check admit the merged tree (file-count/size limits
  355. included). It may return the relative paths it merged in, which a scan block then attributes,
  356. and may raise :class:`PluginOperationError` to abort (re-pin consent). *accept_caution* decides a
  357. caution scan verdict on its own when *force* only means "replace the existing tree" (an update's
  358. re-clone); None lets *force* decide both, as ``install --force`` does. *inspected_sha*: see
  359. :func:`_clone_at_reviewed_commit`."""
  360. requested_revision = _pc()._normalize_exact_revision(ref) if ref is not None else None
  361. try:
  362. git_url, subdir = _pc()._resolve_git_url(identifier)
  363. except ValueError as e:
  364. raise _pc().PluginOperationError(str(e), failure_class="invalid_source") from e
  365. plugins_dir = _pc()._plugins_dir()
  366. source = _pc()._canonical_source(git_url, subdir)
  367. old_metadata = _pc()._read_install_metadata()
  368. # Reinstalling the same pinned source retains its pin, even if its plugin
  369. # directory was manually removed. Moving a pin requires an explicit --ref.
  370. if requested_revision is None:
  371. pins = [e for e in old_metadata.values() if e.get("source") == source and e.get("pinned") is True]
  372. if len(pins) == 1 and isinstance(pins[0].get("revision"), str):
  373. requested_revision = _pc()._normalize_exact_revision(pins[0]["revision"])
  374. with tempfile.TemporaryDirectory(prefix=".install-", dir=plugins_dir) as tmp, ExitStack() as owner:
  375. tmp_clone = Path(tmp) / "plugin"
  376. installed_revision = _clone_at_reviewed_commit(tmp_clone, git_url, requested_revision, inspected_sha, subdir,
  377. catalog_pin=bool(catalog))
  378. git_exe = _pc()._resolve_git_executable()
  379. at_reviewed_pin = bool(reviewed_pin) and installed_revision == (
  380. _pc()._git_resolve_commit(tmp_clone, git_exe, reviewed_pin) if git_exe and reviewed_pin else reviewed_pin)
  381. tmp_target = _pc()._resolve_subdir_within(tmp_clone, subdir) if subdir else tmp_clone
  382. _ensure_tree_readable(tmp_target, plugins_dir)
  383. manifest = _read_manifest_for_install(tmp_target)
  384. plugin_name = manifest.get("name") or (
  385. subdir.rstrip("/").rsplit("/", 1)[-1] if subdir else _pc()._repo_name_from_url(git_url))
  386. link = plugins_dir / str(plugin_name)
  387. from pm.filesystem import is_junction
  388. if "/" not in str(plugin_name) and (link.is_symlink() or is_junction(link)):
  389. # A provider's own installer (e.g. `mnemosyne-hermes install`) links its package here; the
  390. # name is fine, the slot is taken. Say so instead of blaming the manifest.
  391. raise _pc().PluginOperationError(
  392. f"Plugin '{plugin_name}' is already installed outside the catalog: {link} is a link to "
  393. f"{os.path.realpath(link)}. Delete that link to install the catalog version.",
  394. failure_class="already_installed")
  395. try:
  396. target = _pc()._sanitize_plugin_name(plugin_name, plugins_dir)
  397. except ValueError as e:
  398. raise _pc().PluginOperationError(str(e), failure_class="manifest_invalid") from e
  399. _check_manifest_version(manifest, plugin_name)
  400. # One owner per plugin: an `install --ref` publishing between an unattended updater's hold
  401. # check and its publication would be overwritten (the updater holds this lock across both).
  402. from hermes_cli.plugins_auto_update import plugin_update_lock
  403. owner.enter_context(plugin_update_lock(target))
  404. old_metadata = _pc()._read_install_metadata()
  405. prior = old_metadata.get(plugin_name)
  406. # `install --force --ref` is the documented way to move a pin, so a reinstall of the same
  407. # source is an update: it replaces the plugin's code, never the user's state.
  408. tracked_edits: list[str] = []
  409. if (before_swap is None and force and target.is_dir() and not target.is_symlink()
  410. and isinstance(prior, dict) and prior.get("source") == source):
  411. from hermes_cli.plugins_cmd_catalog import _carry_user_files, _local_changes
  412. local, tracked_edits = _local_changes(target)
  413. def _carry(_manifest, tree):
  414. return _carry_user_files(target, tree, local)
  415. before_swap = _carry
  416. # A callback may merge user-owned state into the candidate tree; run it first so one scan
  417. # admits the final bytes.
  418. merged = before_swap(manifest, tmp_target) if before_swap is not None else None
  419. # Scan BEFORE anything is moved into place; raises PluginScanBlocked when blocked.
  420. _pc()._scan_merged_tree(tmp_target, identifier, merged, force=force if accept_caution is None else accept_caution,
  421. scan_decision_cb=scan_decision_cb, reviewed_pin=at_reviewed_pin)
  422. if not python_deps:
  423. from pm.workspace import enabled_plugin_dirs
  424. if target.resolve() in enabled_plugin_dirs(installing=target):
  425. raise _pc().PluginOperationError(
  426. "--no-deps cannot replace an active plugin. Retry without --no-deps; "
  427. "PM must prepare its dependencies before publication.", failure_class="already_installed")
  428. _refuse_unavailable_portable_plugin(plugin_name, tmp_target, app_title)
  429. if target.exists() and not force:
  430. from pm.environments import cli_command_name
  431. from pm.paths import repo_root
  432. raise _pc().PluginOperationError(
  433. f"Plugin '{plugin_name}' already exists. Use force reinstall "
  434. f"or run `{cli_command_name(repo_root())} plugins update {plugin_name}`.",
  435. failure_class="already_installed")
  436. if target.exists() and requested_revision is None and isinstance(prior, dict) and prior.get("pinned") is True:
  437. raise _pc().PluginOperationError(
  438. f"Plugin '{plugin_name}' is pinned. Reinstall it with an explicit "
  439. "--ref <40-character commit SHA> to change its source or revision.", failure_class="already_installed")
  440. record: dict[str, object] = {
  441. "pinned": requested_revision is not None,
  442. "revision": installed_revision,
  443. "source": source,
  444. }
  445. # Saved update_url tag (settled: claims vs provenance): the
  446. # manifest's update_url is COPIED into the row at install. Check
  447. # time compares manifest vs tag; a mismatch is needs-fixing and
  448. # only `hermes plugins trust-update-url` moves the tag.
  449. if manifest.get("update_url"):
  450. from hermes_cli.plugins_updates import https_update_url
  451. try:
  452. record["update_url"] = https_update_url(manifest["update_url"])
  453. except ValueError as exc:
  454. raise _pc().PluginOperationError(f"Plugin '{plugin_name}' {exc}", failure_class="manifest_invalid") from exc
  455. if catalog:
  456. # ``sha`` = the commit checked out; ``pin`` = the reviewed catalog sha it satisfies (the
  457. # annotated-tag object for a tag pin), empty when installed off-pin via ``--ref``.
  458. record["catalog"] = {
  459. **catalog,
  460. "sha": installed_revision,
  461. "pin": reviewed_pin if at_reviewed_pin else "",
  462. }
  463. from hermes_cli.plugins_cmd_catalog import write_catalog_sidecar_record
  464. write_catalog_sidecar_record(tmp_target, catalog, installed_revision)
  465. if allow_removed:
  466. record["allow_removed"] = True
  467. new_metadata = {**old_metadata, plugin_name: record}
  468. from hermes_cli.plugins_transaction import publish_plugin
  469. if tracked_edits:
  470. from hermes_cli.plugins_cmd_catalog import _stash_local_files
  471. # Outside the plugins dir: the discovery scanners recurse into every subdirectory there.
  472. backup = plugins_dir.parent / "plugins-backup" / f"{target.name}-{str(prior.get('revision') or 'old')[:8]}"
  473. _stash_local_files(target, tracked_edits, backup)
  474. _pc()._console().print(
  475. f"[yellow]Local edits to {len(tracked_edits)} tracked file(s) were not carried over; "
  476. f"copies are under {backup} (re-apply by hand).[/yellow]")
  477. try:
  478. publish_plugin(tmp_target, target, old_metadata, new_metadata, require_consent=True,
  479. assume_consent=assume_deps_consent)
  480. except Exception as exc:
  481. raise _pc().PluginOperationError(f"Plugin '{plugin_name}' was not published: {exc}",
  482. failure_class=_publish_failure_class(exc)) from exc
  483. if not _pc()._looks_like_plugin_dir(target):
  484. logger.warning("%s has no plugin.yaml / __init__.py; may not be a valid plugin", plugin_name)
  485. _pc()._copy_example_files(target, _pc()._console())
  486. installed_manifest = _pc()._read_manifest(target)
  487. return target, installed_manifest, installed_manifest.get("name") or target.name
  488. # ---- iuf c1 ----
  489. def _publish_failure_class(exc: BaseException) -> str:
  490. """Why publication failed, from the exception TYPE at this raise site. Publication is the PM
  491. dependency sync (plugins_transaction.publish_plugin -> pm.client.sync_venv): a consent refusal
  492. keeps the class plugins_transaction tagged, a filesystem error keeps its kind, and everything
  493. else PM raised (InstallError, ResolutionConflict, AdmissionRefused, a worker error) is a
  494. dependency failure."""
  495. from hermes_cli.observability.shared_metrics_fields import tagged_failure_class
  496. tagged = tagged_failure_class(exc) if isinstance(exc, _pc().PluginOperationError) else None
  497. if tagged and tagged != "other":
  498. return tagged
  499. if isinstance(exc, PermissionError):
  500. return "permission"
  501. if isinstance(exc, OSError) and not isinstance(exc, (ConnectionError, TimeoutError)):
  502. return "filesystem_error"
  503. return "deps_failed"
  504. # ---- end iuf c1 ----
  505. def recorded_install(install: Callable[[], tuple], *, catalog_name: Optional[str], identifier: str) -> tuple:
  506. """Run one plugin install attempt (a core ``(target, manifest, installed_name)`` call) and record
  507. it as a shared-metrics extension install: failed when it raises, success unless it replaced an
  508. already-installed plugin (a reinstall is not an install)."""
  509. from hermes_cli.observability.shared_metrics_events import record_extension_install
  510. source = "catalog" if catalog_name else ("local" if identifier.startswith("file://") else "url")
  511. before = set(_pc()._read_install_metadata())
  512. try:
  513. result = install()
  514. except Exception as exc:
  515. record_extension_install(kind="plugin", source=source, name=catalog_name, outcome="failed", error=exc)
  516. raise
  517. if result[2] not in before:
  518. record_extension_install(kind="plugin", source=source, name=catalog_name, outcome="success")
  519. return result
  520. def _announce_source(identifier: str, console, *, brief: bool) -> tuple[Optional[Any], str]:
  521. """``(catalog entry or None, install identifier)``, printing where the install comes from: the
  522. catalog pin (plus the entry's description unless *brief*) or the custom-source warning."""
  523. from hermes_cli import plugins_cmd_catalog as catalog
  524. if not catalog.looks_like_catalog_name(identifier):
  525. console.print("[yellow]Warning:[/yellow] custom (unreviewed) source — not from the Hermes catalog.")
  526. return None, identifier
  527. entry = catalog.resolve_catalog_name(identifier, console)
  528. console.print(f"[bold]{entry.name}[/bold] [cyan]\\[{entry.tier}][/cyan] [dim]pinned @ {entry.sha[:8]}[/dim]")
  529. if not brief:
  530. console.print(catalog.entry_capability_summary(entry))
  531. return entry, entry.install_identifier
  532. def cmd_install(
  533. identifier: str,
  534. force: bool = False,
  535. enable: Optional[bool] = None,
  536. ref: Optional[str] = None,
  537. allow_removed: bool = False,
  538. no_deps: bool = False,
  539. yes_deps: bool = False,
  540. brief: bool = False,
  541. ) -> None:
  542. """Install a plugin from the curated catalog (bare name), a Git URL, or owner/repo shorthand.
  543. A catalog hit installs the reviewed pinned SHA and records catalog membership in the shared install
  544. metadata. An explicit different ``--ref`` is a custom pin. URLs/shorthand are custom sources. Every
  545. install is checked against the catalog kill list unless *allow_removed*.
  546. *enable* None prompts "Enable now? [y/N]"; True/False skip the prompt.
  547. *yes_deps* is ``--yes-deps``: the explicit answer to the Python-deps consent
  548. question, so non-interactive installs (SSH automation, CI, Docker entrypoints)
  549. finish in one run instead of being refused and left for an ``enable`` that
  550. cannot recover a refused publication (#122134). The default without it stays
  551. fail-closed in non-interactive sessions.
  552. *brief* is for a caller that already told the user what is being installed and why (first-time
  553. setup): the catalog line, questions, warnings, errors and the outcome print, the catalog
  554. description, clone line and default "Installed" panel do not.
  555. """
  556. from hermes_cli import plugins_cmd_catalog as catalog
  557. console = _pc()._console()
  558. entry, identifier = _announce_source(identifier, console, brief=brief)
  559. if allow_removed:
  560. console.print(
  561. "[bold red]WARNING:[/bold red] [red]--allow-removed set — skipping the catalog kill-list check. "
  562. "This plugin may have been removed for security reasons.[/red]")
  563. try:
  564. git_url, _subdir = _pc()._resolve_git_url(identifier)
  565. if not allow_removed:
  566. catalog.raise_if_removed(identifier, git_url, *((entry.name,) if entry else ()))
  567. except (ValueError, _pc().PluginOperationError) as e:
  568. _pc()._fail(console, f"[red]Error:[/red] {e}")
  569. if git_url.startswith(("http://", "file://")):
  570. console.print(
  571. "[yellow]Warning:[/yellow] Using insecure/local URL scheme. "
  572. "Consider using https:// or git@ for production installs.")
  573. if not brief:
  574. console.print(f"[dim]Cloning {git_url}{f' (subdir: {_subdir})' if _subdir else ''}...[/dim]")
  575. _interactive_scan_decision = interactive_scan_decision(console, "Install")
  576. def _install() -> tuple:
  577. if entry is not None:
  578. return catalog.install_catalog_entry(
  579. entry, force=force, ref=ref, allow_removed=allow_removed, scan_decision_cb=_interactive_scan_decision,
  580. python_deps=not no_deps, assume_deps_consent=yes_deps)
  581. return _pc()._install_plugin_core(
  582. identifier, force=force, ref=ref, scan_decision_cb=_interactive_scan_decision,
  583. python_deps=not no_deps, allow_removed=allow_removed, assume_deps_consent=yes_deps)
  584. try:
  585. target, installed_manifest, installed_name = recorded_install(
  586. _install, catalog_name=entry.name if entry is not None else None, identifier=identifier)
  587. except _pc().PluginOperationError as e:
  588. _pc()._fail(console, f"[red]{'Blocked' if isinstance(e, _pc().PluginScanBlocked) else 'Error'}:[/red] {e}")
  589. if not _pc()._looks_like_plugin_dir(target):
  590. console.print(
  591. f"[yellow]Warning:[/yellow] {installed_name} doesn't contain plugin.yaml, "
  592. f"plugin.json, or __init__.py. It may not be a valid Hermes plugin.")
  593. _prompt_plugin_env_vars(installed_manifest, console)
  594. from pm.workspace import enabled_plugin_dirs
  595. # Active replacements settled consent against the staged tree before PM
  596. # prepared or published it. Do not present a second, ineffective veto.
  597. already_active = target.resolve() in enabled_plugin_dirs()
  598. should_enable = False if no_deps else enable
  599. if no_deps:
  600. console.print("[dim]--no-deps: skipping dependency consent; the plugin stays disabled.[/dim]")
  601. # A memory provider activates through memory.provider alone; the loader never reads plugins.enabled.
  602. # Decide from the installed tree's code (not a text match): catalog category "memory" also holds hooks,
  603. # context engines and skills, and a hook's docstring may name MemoryProvider.
  604. from plugins.memory import _defines_memory_provider
  605. is_memory_provider = _defines_memory_provider(target)
  606. if should_enable is None and not already_active:
  607. should_enable = _pc()._is_tty() and _pc()._ask_yes(
  608. f" Use '{installed_name}' as the memory provider now? [y/N]: " if is_memory_provider
  609. else f" Enable '{installed_name}' now? [y/N]: ")
  610. deps_ok, deps_reason = (True, None)
  611. if should_enable and not already_active:
  612. deps_ok, deps_reason = _install_plugin_python_deps(installed_manifest, target, console,
  613. assume_yes=yes_deps)
  614. _pc()._display_after_install(target, identifier, brief=brief)
  615. # ONE admission transaction for the enable (C13): resolve the candidate
  616. # union (enabled members + this target) and commit the config in the
  617. # same step — env and config change together or not at all. No
  618. # duplicate sync here: nothing was resolved before this point.
  619. if should_enable and not deps_ok:
  620. # Consent declined/skipped: nothing was installed or changed, so
  621. # enabling is refused without touching config or environment.
  622. console.print(
  623. f"[red]✗[/red] Cannot enable [bold]{installed_name}[/bold]: "
  624. f"{deps_reason}"
  625. )
  626. console.print(
  627. "[dim]The plugin stays installed but disabled; re-enable "
  628. "after resolving the conflict.[/dim]"
  629. )
  630. should_enable = False
  631. # already_active is PM's selection (plugins.enabled): it settles dependency consent, not memory.provider.
  632. # An explicit --enable still selects the provider, repairing installs that listed it in plugins.enabled.
  633. activate = bool(enable) # also set by a "y" at the Enable-now prompt below
  634. if already_active and not (is_memory_provider and enable):
  635. console.print("[dim]Replacement installed; plugin selection was not changed.[/dim]")
  636. elif is_memory_provider:
  637. _select_memory_provider(target.name, console, select=should_enable)
  638. elif should_enable:
  639. from hermes_cli.plugins_admission import AdmissionRefused
  640. try:
  641. _pc()._set_plugin_enabled(installed_name, enable=True, console=console)
  642. except AdmissionRefused:
  643. console.print(
  644. "[dim]The plugin stays installed but disabled; re-enable "
  645. "after resolving the conflict.[/dim]"
  646. )
  647. else:
  648. activate = True
  649. console.print(
  650. f"[green]✓[/green] Plugin [bold]{installed_name}[/bold] enabled.",
  651. )
  652. else:
  653. console.print(
  654. f"[dim]Plugin installed but not enabled. "
  655. f"Run `hermes plugins enable {installed_name}` to activate.[/dim]")
  656. from hermes_cli.plugin_provider_requests import requires_auth_notice
  657. if notice := requires_auth_notice(installed_manifest):
  658. console.print(f"[yellow]{notice}[/yellow]")
  659. # Non-interactive installs and declines leave declared capabilities ungranted (fail closed).
  660. declared_caps = _pc()._declared_capabilities_from_manifest(installed_manifest, installed_name)
  661. if declared_caps:
  662. _pc()._run_capability_consent(console, installed_name, declared_caps, context="install")
  663. if activate and not is_memory_provider:
  664. # Loads it into the running gateway now (handlers live) or says what needs a restart (#87770).
  665. # A "y" at the Enable-now prompt counts: without the nudge the gateway never loads the plugin
  666. # (its MCP servers stay absent from every session) and nothing tells the user to restart.
  667. from hermes_cli.plugins_activation import report_activation
  668. report_activation(console, installed_name)
  669. console.print()
  670. def _select_memory_provider(name: str, console, *, select: bool) -> None:
  671. """Make *name* the live memory provider (deps prepared through PM first, as ``hermes memory setup``
  672. does), or say how to; ``plugins enable`` cannot activate one (#119909)."""
  673. if not select:
  674. console.print(
  675. f"[dim]Memory provider installed but not active. Run `hermes memory setup` "
  676. f"(or set memory.provider: {name}) to use it.[/dim]")
  677. return
  678. from hermes_cli.memory_setup import prepare_memory_provider_dependencies
  679. from plugins.memory import find_provider_dir
  680. if find_provider_dir(name) is None: # never save a provider name the loader cannot resolve
  681. console.print(f"[red]✗[/red] {name} does not resolve as a memory provider; memory.provider is unchanged.")
  682. return
  683. try:
  684. prepare_memory_provider_dependencies(name)
  685. except Exception as exc: # resolver conflict, network, PM refusal: report, leave the selection alone
  686. logger.debug("memory provider %s dependency preparation failed", name, exc_info=True)
  687. console.print(f"[red]✗[/red] Could not prepare {name}'s dependencies: {exc}")
  688. console.print("[dim]memory.provider is unchanged; run `hermes memory setup` after resolving it.[/dim]")
  689. return
  690. # The loader refuses a provider parked in plugins.disabled; lift that through the same admission transaction.
  691. from hermes_cli.plugins_admission import AdmissionRefused
  692. expected_config = _pc()._plugin_selection_version()
  693. disabled, aliases = _pc()._get_disabled_set(), _pc()._plugin_aliases(name)
  694. if disabled & aliases:
  695. try:
  696. _pc()._admit_and_save_plugin_sets(_pc()._get_enabled_set(), disabled - aliases,
  697. console=console, action=f"Re-enable '{name}'",
  698. expected_config=expected_config)
  699. except AdmissionRefused:
  700. console.print("[dim]memory.provider is unchanged.[/dim]")
  701. return
  702. previous = _pc()._get_current_memory_provider()
  703. _pc()._save_memory_provider(name)
  704. console.print(
  705. f"[green]✓[/green] [bold]{name}[/bold] set as memory.provider"
  706. f"{f' (replacing {previous})' if previous and previous != name else ''}. "
  707. f"Run `hermes memory setup {name}` to configure it; new sessions use it.")
  708. def _catalog_install_on_disk(catalog_name: str, ref: Optional[str],
  709. inspected_sha: Optional[str] = None) -> Optional[tuple]:
  710. """``(target, manifest, installed_name)`` of the installed, not enabled tree whose install record
  711. names catalog entry *catalog_name*, else None. A refused enable leaves the published clone in
  712. place (there is no rollback), so the card's Try again, or the model asking again, stopped at
  713. "already exists" on a second clone and the plugin could never be turned on from the card.
  714. Like ``hermes plugins enable``, the tree is used at the commit it has; an explicit *ref*, or the
  715. commit an install dialog reviewed (*inspected_sha*), only matches a tree checked out at that commit.
  716. Any other tree is not reused: the fresh install then answers "already exists" instead of enabling
  717. code nobody reviewed."""
  718. from hermes_cli.plugins_cmd_catalog import catalog_install_record
  719. target = _pc()._catalog_installed_dir(catalog_name)
  720. if target is None:
  721. return None
  722. record = catalog_install_record(target) or {}
  723. installed_sha = str(record.get("sha") or "").lower()
  724. if ref and installed_sha != ref.lower():
  725. return None
  726. # The dialog may name the commit or, from the catalog entry, the annotated tag the tree was installed at.
  727. if inspected_sha and inspected_sha.lower() not in {installed_sha, str(record.get("pin") or "").lower()} - {""}:
  728. return None
  729. manifest = _pc()._read_manifest(target)
  730. installed_name = manifest.get("name") or target.name
  731. return None if {installed_name, target.name} & _pc()._get_enabled_set() else (target, manifest, installed_name)
  732. def _resolve_source(identifier: str, catalog_name: Optional[str]) -> tuple:
  733. """``(entry, identifier, warnings, error)``: the catalog entry (None for a custom source), the
  734. identifier to clone, the warnings so far, and the refusal result when there is one."""
  735. from hermes_cli import plugins_cmd_catalog as catalog
  736. warnings: list[str] = []
  737. entry = None
  738. if catalog_name:
  739. entry = catalog.get_live_catalog_entry(catalog_name)
  740. if entry is None:
  741. return None, identifier, warnings, {"ok": False, "error": f"'{catalog_name}' is not in the Hermes plugin catalog."}
  742. warnings.extend(_known_issue_warnings(entry))
  743. identifier = entry.install_identifier
  744. else:
  745. warnings.append("Custom (unreviewed) source — not from the Hermes catalog.")
  746. try:
  747. git_url = _pc()._resolve_git_url(identifier)[0]
  748. if git_url.startswith(("http://", "file://")):
  749. warnings.append("Insecure URL scheme; prefer https:// or git@ for production installs.")
  750. catalog.raise_if_removed(identifier, git_url, *((entry.name,) if entry else ()))
  751. except ValueError:
  752. pass
  753. except _pc().PluginOperationError as exc:
  754. return entry, identifier, warnings, {"ok": False, "error": str(exc)}
  755. return entry, identifier, warnings, None
  756. def _place_tree(entry, identifier: str, *, force: bool, ref: Optional[str], assume_deps_consent: bool,
  757. step: Callable[[InstallPhase], None], inspected_sha: Optional[str] = None) -> tuple | dict:
  758. """``(target, manifest, installed_name)`` of the tree to enable, or the error result. A catalog
  759. entry already on disk and not enabled (an earlier enable was refused) is used as it is, unless
  760. an approved *ref* names another commit; a fresh install clones at *ref* when set, else the pin.
  761. With no *ref*, either source is held to *inspected_sha* when given: a catalog entry re-pinned since
  762. the dialog read it is refused like a moved branch, and only a tree on disk at that commit is reused."""
  763. from hermes_cli import plugins_cmd_catalog as catalog
  764. ref = (ref or "").strip() or None
  765. inspected_sha = None if ref else inspected_sha
  766. on_disk = _catalog_install_on_disk(entry.name, ref, inspected_sha) if entry is not None and not force else None
  767. if on_disk is not None:
  768. return on_disk
  769. def _install() -> tuple:
  770. if entry is not None:
  771. return catalog.install_catalog_entry(entry, force=force, ref=ref, allow_removed=False,
  772. assume_deps_consent=assume_deps_consent, inspected_sha=inspected_sha)
  773. return _pc()._install_plugin_core(identifier, force=force, ref=ref, assume_deps_consent=assume_deps_consent,
  774. inspected_sha=inspected_sha)
  775. step(InstallPhase.downloading)
  776. try:
  777. return recorded_install(_install, catalog_name=entry.name if entry is not None else None,
  778. identifier=identifier)
  779. except _pc().PluginScanBlocked as exc:
  780. return scan_blocked_result(exc)
  781. except _pc().PluginOperationError as exc:
  782. return {"ok": False, "error": str(exc), **({"source_moved": True} if isinstance(exc, _pc().PluginSourceMoved) else {})}
  783. def _enable_placed(installed_name: str, deps, step: Callable[[InstallPhase], None]) -> Optional[dict]:
  784. """None once enabled, else the refusal result. Enabling admits the plugin, and admission resolves
  785. its Python dependencies."""
  786. from hermes_cli.plugins_admission import AdmissionRefused
  787. if deps:
  788. step(InstallPhase.python_packages)
  789. try:
  790. # _set_plugin_enabled serializes per home itself (parallel install-card rows).
  791. _pc()._set_plugin_enabled(installed_name, enable=True)
  792. except AdmissionRefused as exc:
  793. return {"ok": False, "error": f"enable refused: {exc}", "plugin_name": installed_name, "enabled": False}
  794. return None
  795. def dashboard_install_plugin(
  796. identifier: str, *, force: bool, enable: bool, catalog_name: Optional[str] = None,
  797. ref: Optional[str] = None, assume_deps_consent: Optional[bool] = None,
  798. on_step: Optional[Callable[[InstallPhase], None]] = None, inspected_sha: Optional[str] = None,
  799. ) -> dict[str, Any]:
  800. """Non-interactive install for the dashboard/TUI. *catalog_name* installs a curated entry at its
  801. pinned SHA (identifier may be empty); *ref* pins either source to one full commit SHA (same
  802. contract as ``--ref``); every path enforces the kill list (no GUI bypass). *assume_deps_consent*
  803. is consent the caller holds for the Python deps, so no terminal is needed to answer the gate.
  804. None (a user's Install click) is the consent the fresh-install enable already acts on: a plugin
  805. the config already selects (``memory.provider``) would otherwise be refused every time, while
  806. the same plugin unselected installs and enables. A forced replacement still needs explicit consent.
  807. *on_step* hears each slow phase as it starts (the catalog card draws it under its bar). *inspected_sha*
  808. is the commit an install dialog reviewed: a custom source whose branch moved since, or a catalog entry
  809. re-pinned since, is refused."""
  810. if assume_deps_consent is None:
  811. assume_deps_consent = enable and not force
  812. step = on_step or (lambda _phase: None)
  813. if inspected_sha:
  814. # The dialog's inspection is spent either way; re-opening it must read the source again.
  815. from hermes_cli.plugins_cmd_inspect import forget_inspection
  816. forget_inspection(identifier, catalog_name=catalog_name)
  817. entry, identifier, warnings, error = _resolve_source(identifier, catalog_name)
  818. if error is not None:
  819. return error
  820. placed = _place_tree(entry, identifier, force=force, ref=ref, assume_deps_consent=assume_deps_consent, step=step,
  821. inspected_sha=inspected_sha)
  822. if isinstance(placed, dict):
  823. return placed
  824. target, installed_manifest, installed_name = placed
  825. deps = _pc()._python_dependency_summary(target, warnings)
  826. if enable and (refused := _enable_placed(installed_name, deps, step)):
  827. return refused
  828. ap = target / "after-install.md"
  829. # Deps first, then load: the plugin activates in this process (TUI/Desktop server subscribers see it)
  830. # and in the running gateway; ``activation`` says what is live now vs next session (#87770).
  831. from hermes_cli.plugins_activation import activate_plugin_now
  832. if enable:
  833. step(InstallPhase.loading_tools)
  834. activated = activate_plugin_now(installed_name) if enable else {
  835. "gateway_reloaded": False, "activation": None, "restart_required": False}
  836. return {
  837. "ok": True, "plugin_name": installed_name, "warnings": warnings,
  838. "python_dependencies": deps,
  839. "missing_env": [s["name"] for s in _pc()._missing_env_specs(installed_manifest)],
  840. "after_install_path": str(ap) if ap.exists() else None, "enabled": enable, **activated,
  841. "known_issues": list(entry.known_issues) if entry else [],
  842. }