plugins_cmd.py 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161
  1. """``hermes plugins`` CLI subcommand — install, update, remove, and list plugins.
  2. Facade: shared primitives (errors, console/config helpers, manifest reading, discovery, enable/disable
  3. selection) and the dispatch table live here; each verb family lives in a ``plugins_cmd_<topic>.py``
  4. sibling (install, update, remove, git, capabilities, toggle, listing, catalog)."""
  5. from __future__ import annotations
  6. import functools
  7. import logging
  8. import os
  9. import shutil
  10. import sys
  11. import threading
  12. from pathlib import Path
  13. from typing import Any, NoReturn, Optional
  14. from hermes_constants import get_hermes_home, hermes_home_key
  15. from hermes_cli.config import cfg_get
  16. from hermes_cli.plugin_capabilities import _child_dict
  17. # Tests patch these two on the facade; the install/remove siblings read them through it.
  18. from hermes_cli.secret_prompt import masked_secret_prompt
  19. from utils import rmtree_readonly
  20. # Topical siblings. The facade re-exports what other modules, tests and the old updater import from
  21. # ``hermes_cli.plugins_cmd``; sibling bodies read those names back through the facade at call time.
  22. from hermes_cli.plugins_cmd_capabilities import (
  23. _declared_capabilities_for_key, _declared_capabilities_from_manifest, _resolve_tool_override_grant,
  24. _run_capability_consent, cmd_capabilities,
  25. )
  26. from hermes_cli.plugins_cmd_git import (
  27. _EXACT_COMMIT_RE, _canonical_source, _checkout_exact_revision, _clone_plugin_repo, _git_head_revision,
  28. _git_or_raise, _git_pull_plugin_dir, _git_resolve_commit, _normalize_exact_revision, _pin_annotation,
  29. _read_install_metadata, _run_plugin_git, _safe_git_error, _scrub_cloned_origin, _update_install_record,
  30. _write_install_metadata, pinned_revision,
  31. )
  32. from hermes_cli.plugins_cmd_install import (
  33. _check_manifest_version, _consent_python_deps, _display_after_install, _install_plugin_core,
  34. _install_plugin_python_deps, _prompt_plugin_env_vars, _python_dependency_summary,
  35. _read_manifest_for_install, cmd_install, dashboard_install_plugin,
  36. )
  37. from hermes_cli.plugins_cmd_listing import (
  38. _filter_plugin_entries, cmd_list, cmd_show,
  39. )
  40. from hermes_cli.plugins_cmd_remove import (
  41. _remove_plugin_core, cmd_remove, dashboard_remove_user_plugin,
  42. )
  43. from hermes_cli.plugins_cmd_toggle import (
  44. _discover_context_engines, _persist_plugin_selection, _provider_categories, _run_composite_fallback,
  45. cmd_toggle,
  46. )
  47. from hermes_cli.plugins_cmd_update import (
  48. _clear_plugin_bytecode, cmd_adopt, cmd_check_updates, cmd_trust_update_url, cmd_update,
  49. dashboard_update_user_plugin,
  50. )
  51. logger = logging.getLogger(__name__)
  52. _DEFAULT_CLONE_TIMEOUT_SECONDS = 300
  53. _MAX_CLONE_TIMEOUT_SECONDS = 3600
  54. _CLONE_TIMEOUT_HINT = "On a slow connection, raise plugins.clone_timeout_seconds in config.yaml."
  55. @functools.lru_cache(maxsize=1)
  56. def _resolve_git_executable() -> Optional[str]:
  57. """Resolve a git binary for subprocess use when ``PATH`` may be minimal."""
  58. found = shutil.which("git")
  59. if found:
  60. return found
  61. if os.name == "nt":
  62. roots = [
  63. os.environ.get("ProgramFiles", r"C:\Program Files"),
  64. os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)"),
  65. ]
  66. local = os.environ.get("LOCALAPPDATA", "")
  67. if local:
  68. roots.append(os.path.join(local, "Programs"))
  69. candidates = [os.path.join(r, "Git", sub, "git.exe") for r in roots for sub in ("cmd", "bin")]
  70. else:
  71. candidates = ["/usr/bin/git", "/usr/local/bin/git", "/bin/git"]
  72. return next((c for c in candidates if c and os.path.isfile(c)), None)
  73. class PluginOperationError(Exception):
  74. """Recoverable plugin install/update failure (CLI exits; HTTP maps to 4xx).
  75. ``failure_class`` names the raise site for the extension-install metric (a closed name from
  76. ``shared_metrics_contract.EXTENSION_PLUGIN_FAILURE_CLASSES``); untagged sites read ``other``.
  77. """
  78. failure_class = "other"
  79. def __init__(self, *args, failure_class: Optional[str] = None):
  80. super().__init__(*args)
  81. if failure_class is not None:
  82. self.failure_class = failure_class
  83. class PluginSourceMoved(PluginOperationError):
  84. """The source is no longer at the commit the install dialog reviewed. Clients answer it by reading
  85. the source again (``plugins.manage`` error ``data.reason == "source_moved"``), never by resending."""
  86. failure_class = "clone_failed"
  87. class PluginScanBlocked(PluginOperationError):
  88. """Plugin failed the security scan and was not installed."""
  89. failure_class = "scan_blocked"
  90. def __init__(self, message: str, scan_result=None):
  91. super().__init__(message)
  92. self.scan_result = scan_result
  93. def _console():
  94. """A fresh Rich console (rich is imported lazily)."""
  95. from rich.console import Console
  96. return Console()
  97. def _table(columns, **kwargs):
  98. """A Rich ``Table(**kwargs)`` with ``(header, style)`` *columns* added in order."""
  99. from rich.table import Table
  100. table = Table(**kwargs)
  101. for header, style in columns:
  102. table.add_column(header, style=style)
  103. return table
  104. def _is_tty() -> bool:
  105. return sys.stdin.isatty() and sys.stdout.isatty()
  106. def _fail(console, message: str) -> NoReturn:
  107. """Print *message* and exit 1."""
  108. console.print(message)
  109. sys.exit(1)
  110. def _ask_yes(prompt: str, reader=input) -> bool:
  111. """One y/N question; EOF / Ctrl-C count as "no"."""
  112. try:
  113. answer = reader(prompt).strip().lower()
  114. except (EOFError, KeyboardInterrupt):
  115. return False
  116. return answer in {"y", "yes"}
  117. def _config_value(*keys: str, default: Any) -> Any:
  118. """Read ``keys`` from config.yaml; *default* on a missing key or any load failure."""
  119. try:
  120. from hermes_cli.config import load_config
  121. return cfg_get(load_config(), *keys, default=default)
  122. except Exception:
  123. return default
  124. def _clone_timeout_seconds() -> int:
  125. """Deadline for plugin clone and pinned fetch, scoped to the active profile."""
  126. value = _config_value("plugins", "clone_timeout_seconds", default=_DEFAULT_CLONE_TIMEOUT_SECONDS)
  127. if isinstance(value, bool) or not isinstance(value, int) or value < 1:
  128. logger.warning("plugins.clone_timeout_seconds must be a positive integer; using %ss",
  129. _DEFAULT_CLONE_TIMEOUT_SECONDS)
  130. return _DEFAULT_CLONE_TIMEOUT_SECONDS
  131. if value > _MAX_CLONE_TIMEOUT_SECONDS:
  132. logger.warning("plugins.clone_timeout_seconds exceeds %ss; clamping", _MAX_CLONE_TIMEOUT_SECONDS)
  133. return _MAX_CLONE_TIMEOUT_SECONDS
  134. return value
  135. def _config_name_set(*keys: str) -> set:
  136. """A list-valued config key as a set (empty on any failure or non-list)."""
  137. value = _config_value(*keys, default=[])
  138. return set(value) if isinstance(value, list) else set()
  139. def _config_str(*keys: str, default: str) -> str:
  140. """A string config key; empty/missing/failed reads coerce to *default*."""
  141. return _config_value(*keys, default=default) or default
  142. def _write_config_value(section: str, key: str, value: Any) -> None:
  143. """Persist ``config[section][key] = value`` to config.yaml (creating the section)."""
  144. from hermes_cli.config import load_config, save_config
  145. config = load_config()
  146. config.setdefault(section, {})[key] = value
  147. save_config(config)
  148. def _scan_on_install_enabled() -> bool:
  149. """Install/update-time security scanning; on by default, off via ``plugins.scan_on_install: false``."""
  150. return bool(_config_value("plugins", "scan_on_install", default=True))
  151. def _scan_plugin_tree(plugin_dir: Path, identifier: str, *, force: bool, scan_decision_cb=None,
  152. reviewed_pin: bool = False):
  153. """Scan *plugin_dir* and enforce the install policy.
  154. Verdicts: safe → proceed; caution → needs confirmation (``force=True`` or a truthy
  155. ``scan_decision_cb(result)``); dangerous → always blocked (:class:`PluginScanBlocked`).
  156. *reviewed_pin* marks a tree checked out at a curated-catalog sha: that exact tree passed
  157. the same scanner at admission with a human reading the caution findings, so caution is
  158. accepted without a prompt (the Desktop has none). Dangerous still blocks — a signature
  159. added after review is exactly the case the backstop exists for.
  160. Returns the ScanResult, or None when scanning is disabled.
  161. """
  162. if not _scan_on_install_enabled():
  163. return None
  164. from tools.plugin_guard import format_scan_report, scan_plugin, should_allow_plugin_install
  165. result = scan_plugin(plugin_dir, source=identifier)
  166. allowed, reason = should_allow_plugin_install(result, force=force)
  167. if allowed is None and reviewed_pin:
  168. allowed, reason = True, "Caution verdict accepted: reviewed catalog pin"
  169. if allowed is None and scan_decision_cb is not None:
  170. try:
  171. if scan_decision_cb(result):
  172. allowed = True
  173. reason = "Caution verdict accepted by user"
  174. except Exception:
  175. logger.exception("plugin scan decision callback failed")
  176. if allowed is not True:
  177. raise PluginScanBlocked(
  178. f"Security scan blocked plugin install: {reason}\n\n"
  179. f"{format_scan_report(result)}\n"
  180. "Review the findings above. Install only plugins from sources "
  181. "you trust. (Scanning can be configured via "
  182. "plugins.scan_on_install in config.yaml.)",
  183. scan_result=result)
  184. logger.info("plugin scan passed for %s: %s", plugin_dir.name, reason)
  185. return result
  186. def _preserved_files_note(exc: PluginScanBlocked, merged: list[str]) -> str:
  187. """Scan-block text for a tree that also holds user files preserved from the installed copy."""
  188. preserved = set(merged)
  189. findings = exc.scan_result.findings if exc.scan_result is not None else ()
  190. hits = sorted({f.file for f in findings if f.file in preserved})
  191. if hits:
  192. note = ("These findings come from user files preserved from the installed copy: "
  193. f"{', '.join(hits)}. Move or remove them and retry the update.")
  194. else:
  195. note = "The scanned tree included user files preserved from the installed copy."
  196. return f"{exc}\n\n{note}"
  197. def _scan_merged_tree(plugin_dir: Path, identifier: str, merged: Optional[list[str]], **kwargs):
  198. """:func:`_scan_plugin_tree` for a candidate that may hold carried user files (*merged*).
  199. A block then names the findings that sit in those files, so user data does not read as a
  200. malicious upstream revision; the original block stays chained as the cause.
  201. """
  202. try:
  203. return _scan_plugin_tree(plugin_dir, identifier, **kwargs)
  204. except PluginScanBlocked as exc:
  205. if not merged:
  206. raise
  207. raise PluginScanBlocked(_preserved_files_note(exc, merged), scan_result=exc.scan_result) from exc
  208. def _plugins_dir() -> Path:
  209. """Return the user plugins directory, creating it if needed."""
  210. plugins = get_hermes_home() / "plugins"
  211. plugins.mkdir(parents=True, exist_ok=True)
  212. return plugins
  213. def _sanitize_plugin_name(name: str, plugins_dir: Path, *, allow_subdir: bool = False) -> Path:
  214. """Validate a plugin name and return the safe target path inside *plugins_dir*.
  215. Raises ``ValueError`` on traversal or a target outside the plugins directory. ``allow_subdir``
  216. permits forward slashes so category keys like ``web/firecrawl`` can be looked up
  217. (``..`` and backslashes stay rejected); install paths keep ``False`` — a clone lands top-level.
  218. """
  219. if allow_subdir and name:
  220. name = name.strip("/")
  221. if not name:
  222. raise ValueError("Plugin name must not be empty.")
  223. if name in {".", ".."}:
  224. raise ValueError(f"Invalid plugin name '{name}': must not reference the plugins directory itself.")
  225. for bad in ("\\", "..") if allow_subdir else ("/", "\\", ".."):
  226. if bad in name:
  227. raise ValueError(f"Invalid plugin name '{name}': must not contain '{bad}'.")
  228. target = (plugins_dir / name).resolve()
  229. plugins_resolved = plugins_dir.resolve()
  230. if target == plugins_resolved:
  231. raise ValueError(f"Invalid plugin name '{name}': resolves to the plugins directory itself.")
  232. if plugins_resolved not in target.parents:
  233. raise ValueError(f"Invalid plugin name '{name}': resolves outside the plugins directory.")
  234. return target
  235. _GITHUB_BROWSER_SEGMENTS = {
  236. "actions", "blob", "commit", "commits", "issues", "pull", "pulls", "releases", "tree", "wiki",
  237. }
  238. _URL_SCHEMES = ("https://", "http://", "git@", "ssh://", "file://")
  239. def _resolve_git_url(identifier: str) -> tuple[str, Optional[str]]:
  240. """Turn an identifier into a cloneable Git URL and optional subdirectory.
  241. ``http://`` and ``file://`` are accepted but trigger a security warning at install time.
  242. """
  243. if identifier.startswith(_URL_SCHEMES):
  244. if identifier.startswith("https://github.com/"):
  245. path = identifier[len("https://github.com/") :]
  246. path = path.split("?", 1)[0].split("#", 1)[0].strip("/")
  247. parts = path.split("/")
  248. if len(parts) >= 3 and all(parts[:2]) and parts[2] in _GITHUB_BROWSER_SEGMENTS:
  249. repo = parts[1].removesuffix(".git")
  250. subdir = None
  251. if parts[2] == "tree" and len(parts) >= 5:
  252. subdir = "/".join(p for p in parts[4:] if p).strip("/") or None
  253. return f"https://github.com/{parts[0]}/{repo}.git", subdir
  254. # Explicit ``#subdir`` fragment — unambiguous for any scheme.
  255. if "#" in identifier:
  256. git_url, _, frag = identifier.partition("#")
  257. return git_url, (frag.strip("/") or None)
  258. # Natural ``.git/`` boundary (GitHub-style URLs).
  259. git_url, marker, subdir = identifier.partition(".git/")
  260. if marker:
  261. return git_url + ".git", (subdir.strip("/") or None)
  262. return identifier, None
  263. # owner/repo[/subdir...] or owner/repo#subdir shorthand (the catalog spells subdirs with ``#``).
  264. identifier, _, fragment = identifier.partition("#")
  265. parts = [p for p in identifier.strip("/").split("/") if p]
  266. if len(parts) >= 2:
  267. subdir = "/".join([*parts[2:], *fragment.split("/")]).strip("/")
  268. return f"https://github.com/{parts[0]}/{parts[1]}.git", (subdir or None)
  269. raise ValueError(
  270. f"Invalid plugin identifier: '{identifier}'. "
  271. "Use a Git URL or 'owner/repo' shorthand (optionally with a subdirectory: "
  272. "'owner/repo/path/to/plugin').")
  273. def _resolve_subdir_within(clone_root: Path, subdir: str) -> Path:
  274. """Resolve ``subdir`` inside ``clone_root``; ``..``, absolute paths and symlinks may not
  275. escape the clone. Raises ``PluginOperationError`` if it escapes, is missing, or is a file."""
  276. clone_root = clone_root.resolve()
  277. candidate = (clone_root / subdir).resolve()
  278. if candidate != clone_root and clone_root not in candidate.parents:
  279. raise PluginOperationError(f"Plugin subdirectory '{subdir}' escapes the repository.",
  280. failure_class="invalid_source")
  281. if not candidate.exists():
  282. raise PluginOperationError(f"Plugin subdirectory '{subdir}' does not exist in the repository.",
  283. failure_class="invalid_source")
  284. if not candidate.is_dir():
  285. raise PluginOperationError(f"Plugin subdirectory '{subdir}' is not a directory.",
  286. failure_class="invalid_source")
  287. return candidate
  288. def _repo_name_from_url(url: str) -> str:
  289. """Repo name from a Git URL (last path component; ssh-style ``git@host:repo`` splits on ':')."""
  290. name = url.rstrip("/").removesuffix(".git").rsplit("/", 1)[-1]
  291. if ":" in name:
  292. name = name.rsplit(":", 1)[-1].rsplit("/", 1)[-1]
  293. return name
  294. def _native_manifest_file(plugin_dir: Path) -> Optional[Path]:
  295. """``plugin.yaml`` (or ``plugin.yml``) under *plugin_dir*, or None when neither exists."""
  296. from pm.plugin_declarations import native_manifest_file
  297. try:
  298. return native_manifest_file(plugin_dir)
  299. except ValueError as exc:
  300. raise PluginOperationError(str(exc), failure_class="manifest_invalid") from exc
  301. def _has_portable_manifest(plugin_dir: Path) -> bool:
  302. """True when ``plugin.json`` exists (or is a symlink, even dangling) under *plugin_dir*."""
  303. portable_file = plugin_dir / "plugin.json"
  304. return portable_file.exists() or portable_file.is_symlink()
  305. def _load_yaml_manifest(manifest_file: Path):
  306. """``yaml.safe_load`` of *manifest_file* (``{}`` when empty); raises on any read/parse error."""
  307. from pm.plugin_declarations import read_native_manifest
  308. return read_native_manifest(manifest_file)
  309. def _read_manifest(plugin_dir: Path) -> dict:
  310. """Read a native or portable manifest, preferring native YAML."""
  311. manifest_file = _native_manifest_file(plugin_dir)
  312. if manifest_file is None:
  313. if not _has_portable_manifest(plugin_dir):
  314. return {}
  315. try:
  316. from hermes_cli.agent_plugins import read_agent_plugin_manifest
  317. return read_agent_plugin_manifest(plugin_dir)[0]
  318. except Exception as e:
  319. logger.warning("Failed to read plugin.json in %s: %s", plugin_dir, e)
  320. return {}
  321. try:
  322. return _load_yaml_manifest(manifest_file)
  323. except Exception as e:
  324. logger.warning("Failed to read plugin.yaml in %s: %s", plugin_dir, e)
  325. return {}
  326. def _looks_like_plugin_dir(target: Path) -> bool:
  327. """True when *target* has a native/portable manifest or a package ``__init__.py``."""
  328. return (
  329. _native_manifest_file(target) is not None
  330. or (target / "plugin.json").exists()
  331. or (target / "__init__.py").exists())
  332. def _copy_example_files(plugin_dir: Path, console) -> None:
  333. """Copy ``*.example`` files to their real names (``config.yaml.example`` -> ``config.yaml``),
  334. never overwriting an existing file so reinstall keeps user config."""
  335. for example_file in plugin_dir.glob("*.example"):
  336. real_name = example_file.stem
  337. real_path = plugin_dir / real_name
  338. if real_path.exists():
  339. continue
  340. try:
  341. shutil.copy2(example_file, real_path)
  342. console.print(f"[dim] Created {real_name} from {example_file.name}[/dim]")
  343. except OSError as e:
  344. console.print(f"[yellow]Warning:[/yellow] Failed to copy {example_file.name}: {e}")
  345. def _missing_env_specs(manifest: dict) -> list[dict]:
  346. """``requires_env`` entries (plain names or ``{name, description, url, secret}`` dicts,
  347. normalised to dicts; nameless entries dropped) whose variable is unset in ``~/.hermes/.env``."""
  348. env_specs = [
  349. {"name": entry} if isinstance(entry, str) else entry
  350. for entry in manifest.get("requires_env") or []
  351. if isinstance(entry, str) or (isinstance(entry, dict) and entry.get("name"))
  352. ]
  353. if not env_specs:
  354. return []
  355. from hermes_cli.config import get_env_value
  356. return [s for s in env_specs if not get_env_value(s["name"])]
  357. def _clone_failure_message(git_url: str, git_error: str) -> str:
  358. """Plain-words clone failure: what to check (address, network, private repo), raw git text last.
  359. The text reaches ``_fail`` -> Rich ``console.print``: escape the git output so ``[...]`` in it is
  360. not parsed as markup."""
  361. from rich.markup import escape
  362. return (f"Could not download the plugin from {git_url}. Check the address (browse the catalog "
  363. "with `hermes plugins search`), check your internet connection, or, if the repository "
  364. "is private, sign in first with `gh auth login` (or set GITHUB_TOKEN in your .env).\n"
  365. f"Details: {escape(git_error.strip())}")
  366. def _require_installed_plugin(name: str, plugins_dir: Path, console) -> Path:
  367. """The plugin path if it exists; else exit 1 (invalid name, or a listing of installed plugins)."""
  368. try:
  369. target = _sanitize_plugin_name(name, plugins_dir, allow_subdir=True)
  370. except ValueError as e:
  371. _fail(console, f"[red]Error:[/red] {e}")
  372. if not target.exists():
  373. target = _resolved_user_plugin_dir(name)
  374. if target is None:
  375. _fail(console, _unknown_plugin_message(name, downloaded_only=True))
  376. return target
  377. def _unknown_plugin_message(name: str, *, downloaded_only: bool = False) -> str:
  378. """``No plugin named ...`` with the exact-name rule and the two commands that resolve it."""
  379. scope = (" This command only works on downloaded plugins; bundled ones can only be enabled or disabled."
  380. if downloaded_only else " Bundled plugins can only be enabled or disabled.")
  381. from hermes_cli.left_core_migration import moved_plugin_hint
  382. if moved := moved_plugin_hint(name):
  383. return f"[red]No plugin named '{name}'.[/red] {moved}"
  384. return (f"[red]No plugin named '{name}'.[/red] Run `hermes plugins list` to see the exact names "
  385. f"(nested plugins use their full key, e.g. web/firecrawl).{scope} "
  386. "To add one: `hermes plugins install <owner/repo>`.")
  387. # ``plugins.disabled`` is an explicit deny-list that wins over the ``plugins.enabled`` allow-list.
  388. _get_disabled_set = functools.partial(_config_name_set, "plugins", "disabled")
  389. _get_enabled_set = functools.partial(_config_name_set, "plugins", "enabled")
  390. def _save_enabled_set(enabled: set) -> None:
  391. """Frozen old-updater import: never resurrect a raw plugin-selection write."""
  392. from hermes_cli._old_updater import stop_for_relaunch
  393. stop_for_relaunch()
  394. def _plugin_selection_version() -> str:
  395. from hermes_cli.runtime_state import _digest
  396. return _digest(get_hermes_home() / "config.yaml") or "missing"
  397. def _admit_and_save_plugin_sets(
  398. enabled: set, disabled: set, *, extra_dirs=(), console=None, action: str = "enable", expected_config=None,
  399. plugin: Optional[str] = None, settled=(),
  400. ) -> None:
  401. """ONE admission authority for proposed enabled/disabled sets (C13):
  402. the candidate union is resolved against the ACTIVE environment and
  403. the config commits inside the same worker-owned PM transaction — a refusal or a config-write failure
  404. publishes nothing: previous config bytes AND previous environment
  405. stay exactly in place. Raises :class:`AdmissionRefused` (UI callers
  406. catch and surface it — admission never auto-disables to fit); a resolver
  407. conflict raises its :class:`DependencyConflict` subclass naming *plugin*."""
  408. from rich.markup import escape
  409. from hermes_cli.plugins_admission import AdmissionRefused, DependencyConflict, admit_plugin_set_change
  410. try:
  411. admit_plugin_set_change(
  412. enabled, disabled, active_plugins_dir=_plugins_dir(), extra_dirs=extra_dirs, expected_config=expected_config,
  413. plugin=plugin, settled=settled,
  414. )
  415. except DependencyConflict as exc:
  416. # `hermes pm install` cannot fix a conflict, so the retry hint below would mislead here.
  417. if console is not None:
  418. console.print(f"[red]✗[/red] {escape(str(exc))}")
  419. console.print("[dim]config.yaml and the active environment are unchanged.[/dim]")
  420. raise
  421. except AdmissionRefused as exc:
  422. if console is not None:
  423. console.print(f"[red]✗[/red] {action} refused: {exc}")
  424. console.print(
  425. "[dim]config.yaml and the active environment are unchanged. "
  426. "Run `hermes pm install` to resolve dependencies, then retry.[/dim]"
  427. )
  428. raise
  429. _BASIC_AUTH_PLUGIN_KEYS = frozenset({"basic", "dashboard_auth/basic"})
  430. def ensure_basic_auth_plugin_enabled_in_config(cfg: dict) -> bool:
  431. """Drop the bundled basic dashboard-auth plugin from ``plugins.disabled`` in *cfg*.
  432. ``hermes setup`` / ``hermes plugins disable basic`` can park it there while
  433. ``dashboard.basic_auth`` is configured, and password auth then silently fails.
  434. Returns True when modified.
  435. """
  436. plugins_cfg = cfg.get("plugins")
  437. disabled = plugins_cfg.get("disabled") if isinstance(plugins_cfg, dict) else None
  438. if not isinstance(disabled, list) or not (set(disabled) & _BASIC_AUTH_PLUGIN_KEYS):
  439. return False
  440. plugins_cfg["disabled"] = sorted(set(disabled) - _BASIC_AUTH_PLUGIN_KEYS)
  441. return True
  442. def _discard_key_and_leaf(names: set, key: str) -> None:
  443. """Drop *key* and its bare leaf (``web/exa`` -> ``exa``) from *names*, so a
  444. stale legacy bare-name entry can't keep vetoing the canonical key."""
  445. names.discard(key)
  446. names.discard(key.split("/")[-1])
  447. def _plugin_aliases(key: str, entries: Optional[list] = None) -> set:
  448. """Every spelling a config list may hold for *key*: the key, its bare leaf and the manifest name.
  449. The loader matches BOTH the canonical key (``web/firecrawl``) and the manifest name
  450. (``web-firecrawl``), so a stale entry under any form vetoes an enable ("explicit disable wins").
  451. Pass *entries* to reuse one :func:`_discover_all_plugins` scan across several keys."""
  452. from hermes_cli.left_core_migration import legacy_plugin_keys
  453. names = {key, key.split("/")[-1], *legacy_plugin_keys(key)}
  454. names.update(e[0] for e in (_discover_all_plugins() if entries is None else entries) if e[5] == key)
  455. return names
  456. def _activate_key(key: str, *, enable: bool, console=None) -> bool:
  457. """Transactionally persist canonical *key*, purging aliases from the opposing list.
  458. False when the lists already say so (nothing written). PM owns the selection and dependency
  459. publication together, so every CLI/dashboard activation surface goes through the same admission
  460. transaction instead of writing ``config.yaml`` directly."""
  461. enabled, disabled = _get_enabled_set(), _get_disabled_set()
  462. aliases = _plugin_aliases(key)
  463. target, other = (enabled, disabled) if enable else (disabled, enabled)
  464. # A plugin an update disabled is retried by later updates; disabling it yourself stops that.
  465. if key in target and not (aliases & other) and not (not enable and _disabled_by_update(key, aliases)):
  466. return False
  467. _set_plugin_enabled(key, enable=enable, aliases=aliases, console=console)
  468. return True
  469. def _disabled_by_update(key: str, aliases) -> bool:
  470. """Whether an update disabled this plugin and will retry it (``pm.plugin_eviction`` records it)."""
  471. from pm.plugins_state import RECORD
  472. from pm.plugins_state import read_home_selection
  473. record = ((read_home_selection(get_hermes_home()) or {}).get("plugins") or {}).get(RECORD)
  474. return isinstance(record, dict) and bool({key, *aliases} & set(record))
  475. def _forget_plugin_config(aliases: set) -> dict[str, Any]:
  476. """Drop every trace of a removed plugin (its :func:`_plugin_aliases`, taken BEFORE the tree went)
  477. from config.yaml: allow/deny-list entries, ``plugins.entries.<id>`` grants and a ``memory.provider``
  478. selection naming it. A later reinstall under the same name must start from the "Enable now?"
  479. decision, not inherit a stale enable or grant (#54336); a dangling ``memory.provider`` would make
  480. the next agent init re-clone the plugin from the catalog, silently undoing the uninstall.
  481. Returns ``{"cleared_memory_provider": True}`` when the selection was reset."""
  482. from hermes_cli.config import load_config, save_config
  483. config = load_config()
  484. changed = False
  485. result: dict[str, Any] = {}
  486. plugins_cfg = config.get("plugins")
  487. if isinstance(plugins_cfg, dict):
  488. for list_key in ("enabled", "disabled"):
  489. names = plugins_cfg.get(list_key)
  490. if isinstance(names, list) and aliases & set(names):
  491. plugins_cfg[list_key] = sorted(set(names) - aliases)
  492. changed = True
  493. entries = plugins_cfg.get("entries")
  494. if isinstance(entries, dict) and aliases & set(entries):
  495. for alias in aliases & set(entries):
  496. del entries[alias]
  497. changed = True
  498. memory_cfg = config.get("memory")
  499. if isinstance(memory_cfg, dict) and str(memory_cfg.get("provider") or "").strip() in aliases:
  500. memory_cfg["provider"] = ""
  501. changed, result = True, {"cleared_memory_provider": True}
  502. if changed:
  503. save_config(config)
  504. return result
  505. # One lock per Hermes home. The Desktop install card enables several plugins at once, each on its own
  506. # thread; without it every thread read the same config version and all but the first commit were
  507. # refused as stale. The version check in PM stays: it still catches an edit from another process.
  508. _SELECTION_LOCKS: dict[str, threading.Lock] = {}
  509. _SELECTION_LOCKS_GUARD = threading.Lock()
  510. def _selection_lock() -> threading.Lock:
  511. with _SELECTION_LOCKS_GUARD:
  512. return _SELECTION_LOCKS.setdefault(hermes_home_key(), threading.Lock())
  513. def _set_plugin_enabled(name: str, *, enable: bool, aliases=(), console=None) -> None:
  514. """Submit the command's delta with the version of the selection it read."""
  515. from pm.plugins_state import read_home_selection
  516. with _selection_lock():
  517. expected_config = _plugin_selection_version()
  518. config = read_home_selection(get_hermes_home()) or {}
  519. plugins = config.get("plugins") or {}
  520. enabled = set(plugins.get("enabled") or ())
  521. disabled = set(plugins.get("disabled") or ())
  522. _apply_activation(enabled, disabled, name, aliases, enable=enable)
  523. _admit_and_save_plugin_sets(enabled, disabled, console=console,
  524. action=f"{'Enable' if enable else 'Disable'} '{name}'",
  525. expected_config=expected_config, plugin=name if enable else None,
  526. settled=(name, *aliases))
  527. def _apply_activation(enabled: set, disabled: set, key: str, aliases, *, enable: bool) -> None:
  528. """Add canonical *key* to the target list and purge it, its bare leaf and *aliases* from the other."""
  529. removed = disabled if enable else enabled
  530. _discard_key_and_leaf(removed, key)
  531. removed.difference_update(aliases)
  532. (enabled if enable else disabled).add(key)
  533. def _resolve_plugin_key(name: str) -> Optional[str]:
  534. """Canonical registry key for a manifest name / directory name / path key, or ``None``.
  535. The single normalization point so enable/disable write the key ``PluginManager`` gates on."""
  536. resolved = _resolve_plugin_key_and_source(name)
  537. return resolved[0] if resolved else None
  538. def _catalog_installed_dir(name: str) -> Optional[Path]:
  539. """Install dir whose installer-owned record names catalog entry *name* (``hermes-memory-wiki`` is
  540. installed as ``plugins/memory-wiki``), else None (also when two dirs claim it). Read through
  541. :func:`catalog_install_record` (``.install-metadata.json``), never the tree, so a URL-installed
  542. repo cannot claim a catalog entry's name."""
  543. from hermes_cli.plugins_cmd_catalog import catalog_install_record
  544. try:
  545. keys = list(_read_install_metadata())
  546. except PluginOperationError:
  547. return None
  548. hits = [target for key in keys if (target := _plugins_dir() / key).is_dir()
  549. and (record := catalog_install_record(target)) and record["catalog_name"] == name]
  550. return hits[0] if len(hits) == 1 else None
  551. def _find_plugin_entry(name: str) -> Optional[tuple]:
  552. """THE plugin name resolver for every verb (enable/disable/show/capabilities/remove/update, the
  553. dashboard and the Desktop hub): the discovered ``(name, version, description, source, dir_path, key)``
  554. entry for a canonical key or manifest name; else a bare leaf (``exa`` ->
  555. ``web/exa``) only when unique; else the catalog name the plugin was installed under.
  556. Never guesses between two candidates."""
  557. entries = _discover_all_plugins()
  558. from hermes_cli.left_core_migration import legacy_plugin_alias
  559. target = legacy_plugin_alias(name) or name # ``observability/langfuse`` -> its catalog plugin
  560. exact = next((entry for entry in entries if target in (entry[0], entry[5])), None)
  561. if exact is not None:
  562. return exact
  563. leaf_matches = [entry for entry in entries if name == entry[5].split("/")[-1]]
  564. if leaf_matches:
  565. return leaf_matches[0] if len(leaf_matches) == 1 else None
  566. target = _catalog_installed_dir(name)
  567. return next((entry for entry in entries if target is not None and entry[4] and Path(str(entry[4])) == target),
  568. None)
  569. def _resolve_plugin_key_and_source(name: str) -> Optional[tuple]:
  570. """Resolve *name* to ``(canonical_key, source)`` or ``None`` through :func:`_find_plugin_entry`."""
  571. entry = _find_plugin_entry(name)
  572. return (entry[5], entry[3]) if entry else None
  573. def cmd_enable(name: str, allow_tool_override: Optional[bool] = None) -> None:
  574. """Add a plugin to the enabled allow-list (and remove it from disabled).
  575. Non-bundled plugins request consent for declared capabilities. The legacy
  576. ``allow_tool_override`` grant changes only with an explicit True/False flag;
  577. None leaves it unchanged. Bundled plugins are trusted.
  578. """
  579. from hermes_cli.relay_plugin_cutover import LEGACY_RELAY_PLUGIN_KEYS, RELAY_PLUGINS_CONFIG_ENV
  580. console = _console()
  581. def _refuse_legacy_relay(plugin: str) -> None:
  582. if plugin in LEGACY_RELAY_PLUGIN_KEYS:
  583. _fail(console, (
  584. f"[red]Plugin '{plugin}' was removed.[/red] Relay lifecycle is owned "
  585. "by Hermes core; configure a standard user or system Relay plugins.toml, or use "
  586. f"{RELAY_PLUGINS_CONFIG_ENV} for an explicit user-file override."))
  587. _refuse_legacy_relay(name)
  588. resolved = _resolve_plugin_key_and_source(name)
  589. if resolved is None:
  590. _fail(console, _unknown_plugin_message(name))
  591. key, source = resolved
  592. _refuse_legacy_relay(key)
  593. if source != "bundled":
  594. # Activating recalled code is the same act as installing it (`plugins/AGENTS.md`: kill list).
  595. from hermes_cli import plugins_cmd_catalog as catalog
  596. try:
  597. catalog.refuse_if_installed_removed(key, _user_installed_plugin_dir(key.rsplit("/", 1)[-1]))
  598. except PluginOperationError as exc:
  599. _fail(console, f"[red]Error:[/red] {exc}")
  600. changed = _activate_key(key, enable=True, console=console)
  601. if changed:
  602. from hermes_cli.plugins_activation import report_activation
  603. console.print(f"[green]✓[/green] Plugin [bold]{key}[/bold] enabled.") # the hint says when it applies
  604. report_activation(console, key)
  605. else:
  606. console.print(f"[dim]Plugin '{key}' is already enabled.[/dim]")
  607. if source != "bundled":
  608. _enable_consent(console, key, allow_tool_override)
  609. if changed: # after consent: register() sees the grants; same saved-list edit as the Desktop toggle
  610. _toggle_plugin_toolset(key, enable=True)
  611. def _enable_consent(console, key: str, allow_tool_override: Optional[bool]) -> None:
  612. """Capability consent and the legacy tool-override grant for a non-bundled plugin's enable."""
  613. # When the manifest declares capabilities the consent screen is the canonical grant path
  614. # (it covers tools.override too); the legacy prompt then only runs on an explicit flag.
  615. # See #64228.
  616. declared_caps = _declared_capabilities_for_key(key)
  617. if declared_caps:
  618. _run_capability_consent(console, key, declared_caps, context="enable")
  619. # Enabling a plugin is not a request for undeclared privileges. Keep existing
  620. # grants unchanged unless the operator explicitly grants or revokes one.
  621. if allow_tool_override is not None:
  622. _resolve_tool_override_grant(console, key, allow_tool_override)
  623. def cmd_disable(name: str) -> None:
  624. """Remove a plugin from the enabled allow-list (and add to disabled)."""
  625. console = _console()
  626. key = _resolve_plugin_key(name)
  627. if key is None:
  628. _fail(console, _unknown_plugin_message(name))
  629. toolset_key = _saved_list_toolset_key(key) # resolve while the plugin still loads
  630. if not _activate_key(key, enable=False, console=console):
  631. console.print(f"[dim]Plugin '{key}' is already disabled.[/dim]")
  632. return
  633. _toggle_plugin_toolset(key, enable=False, toolset_key=toolset_key)
  634. from hermes_cli.plugins_activation import gateway_reload_hint, reload_running_gateway
  635. console.print(f"[yellow]⊘[/yellow] Plugin [bold]{key}[/bold] disabled.")
  636. console.print(f"[dim]{gateway_reload_hint(reload_running_gateway(), key)}[/dim]")
  637. def _read_manifest_info(d: Path, prefix: str):
  638. """Read a native or portable manifest and return display metadata."""
  639. manifest_file = _native_manifest_file(d)
  640. if manifest_file is None:
  641. if not _has_portable_manifest(d):
  642. return None
  643. try:
  644. from hermes_cli.agent_plugins import read_agent_plugin_manifest
  645. manifest = read_agent_plugin_manifest(d)[0]
  646. name = manifest["name"]
  647. except Exception:
  648. return None
  649. else:
  650. # Unreadable YAML (or no yaml module) degrades to the directory name, silently.
  651. try:
  652. manifest = _load_yaml_manifest(manifest_file)
  653. except Exception:
  654. manifest = {}
  655. if not isinstance(manifest, dict):
  656. manifest = {}
  657. name = manifest.get("name", d.name)
  658. key = f"{prefix}/{d.name}" if prefix else name
  659. return name, manifest.get("version", ""), manifest.get("description", ""), key
  660. def _is_portable_plugin_dir(dir_path) -> bool:
  661. """True for an Agent Plugins v1 package (``plugin.json`` only; native ``plugin.yaml`` wins)."""
  662. try:
  663. d = Path(dir_path)
  664. return d.is_dir() and _native_manifest_file(d) is None and _has_portable_manifest(d)
  665. except OSError:
  666. return False
  667. # Manifest kinds active-by-default when bundled (backends auto-load, platforms register lazily,
  668. # model providers go through providers/ discovery). Standalone/exclusive kinds stay opt-in.
  669. _BUNDLED_DEFAULT_ON_KINDS = frozenset({"backend", "platform", "model-provider"})
  670. def _default_on(dir_path, source: str) -> bool:
  671. """True when a plugin is active without a ``plugins.enabled`` entry (portable ``plugin.json``
  672. packages have no kind, so never). Bundled default-on kinds always; a user model provider only
  673. where providers/ discovery loads it (``providers._scan_home_layer``): a
  674. ``plugins/model-providers/<name>/`` child whose kind is model-provider, or a flat
  675. ``plugins/<name>/`` child declaring exactly ``kind: model-provider``. Discovery imports any other
  676. ``model-providers/`` child too, but nothing calls its ``register(ctx)``, so it is not on.
  677. Entry-point rows store ``module:attr`` in the path slot. That string is not a directory;
  678. opening it as one is WinError 123 on Windows and aborts the whole plugin list.
  679. """
  680. path = Path(dir_path)
  681. if not path.is_dir():
  682. return False
  683. if source != "bundled":
  684. from providers import _declares_model_provider_kind
  685. root = _plugins_dir()
  686. if path.name.startswith(("_", ".")) or path.parent not in (root, root / "model-providers"):
  687. return False
  688. if path.parent == root:
  689. return _declares_model_provider_kind(path)
  690. manifest_file = _native_manifest_file(path)
  691. if manifest_file is None:
  692. return False
  693. try:
  694. kind = str(_load_yaml_manifest(manifest_file).get("kind", "standalone")).strip().lower()
  695. except Exception:
  696. return False
  697. return kind == "model-provider" or (source == "bundled" and kind in _BUNDLED_DEFAULT_ON_KINDS)
  698. def _scan_level(base: Path, source: str, skip_names: set, prefix: str, depth: int, seen: dict) -> None:
  699. """Recursive directory scan matching PluginManager._scan_directory_level."""
  700. if not base.is_dir():
  701. return
  702. try:
  703. children = sorted(base.iterdir())
  704. except OSError as exc:
  705. logger.warning("Skipping unreadable plugin directory %s: %s", base, exc)
  706. return
  707. for d in children:
  708. try:
  709. if not d.is_dir() or (depth == 0 and skip_names and d.name in skip_names):
  710. continue
  711. info = _read_manifest_info(d, prefix)
  712. except (OSError, PluginOperationError) as exc:
  713. # The PM declaration reader wraps unreadable manifests for install callers;
  714. # listing still skips them rather than hiding every other plugin.
  715. logger.warning("Skipping unreadable plugin directory %s: %s", d, exc)
  716. continue
  717. if info is None:
  718. if depth == 0:
  719. _scan_level(d, source, set(), f"{prefix}/{d.name}" if prefix else d.name, 1, seen)
  720. continue
  721. name, version, description, key = info
  722. if key in seen and source == "bundled":
  723. continue
  724. src_label = "git" if source == "user" and (d / ".git").exists() else source
  725. seen[key] = (name, version, description, src_label, d, key)
  726. def _discover_all_plugins() -> list:
  727. """``(name, version, description, source, dir_path, key)`` for every plugin the loader sees,
  728. in ``PluginManager.discover_and_load`` order: bundled, user, then entry points — which never
  729. displace a directory plugin of the same key (see ``PluginManager._discover_and_load_inner``)."""
  730. seen: dict = {}
  731. # memory/, context_engine/, computer_use/, model-providers/ and config_backends/ load through dedicated
  732. # paths, not the PluginManager opt-in surface, so listing them as toggleable plugins would mislead.
  733. from hermes_cli.plugins import discover_entrypoint_manifests, get_bundled_plugins_dir
  734. for base, source, skip in (
  735. (get_bundled_plugins_dir(), "bundled", {"memory", "context_engine", "computer_use", "model-providers", "config_backends"}),
  736. (_plugins_dir(), "user", set()),
  737. ):
  738. _scan_level(base, source, skip, "", 0, seen)
  739. # Entry-point plugins are installed as Python packages, so they have no plugin directory.
  740. for m in discover_entrypoint_manifests():
  741. seen.setdefault(m.name, (m.name, m.version, m.description, "entrypoint", m.path, m.name))
  742. return list(seen.values())
  743. def _category_active_names() -> set:
  744. """Provider names switched on through ``<category>.provider`` config rather than
  745. ``plugins.enabled`` (the live memory provider), so status never calls them "not enabled"."""
  746. return {n for n in (_get_current_memory_provider(),) if n}
  747. def _plugin_status(name: str, enabled: set, disabled: set, key: str = "", *, source: str = "",
  748. dir_path=None, active: frozenset | set = frozenset()) -> str:
  749. """User-facing activation state for a plugin name or key. Mirrors ``gate_manifest``: an explicit
  750. disable wins, then the allow-list, then the activations that need no list entry — bundled
  751. backends/platforms and model providers from any source (*source* + *dir_path*) and category-selected providers
  752. (*active*, see :func:`_category_active_names`)."""
  753. names = {name, key}
  754. if names & disabled:
  755. return "disabled"
  756. if names & enabled or names & active:
  757. return "enabled"
  758. if dir_path is not None and _default_on(dir_path, source):
  759. return "enabled"
  760. return "not enabled"
  761. # ── Provider category config accessors ──────────────────────────────────────────────────────
  762. # memory.provider ("" = built-in) and context.engine config accessors.
  763. _get_current_memory_provider = functools.partial(_config_str, "memory", "provider", default="")
  764. _get_current_context_engine = functools.partial(_config_str, "context", "engine", default="compressor")
  765. _save_memory_provider = functools.partial(_write_config_value, "memory", "provider")
  766. _save_context_engine = functools.partial(_write_config_value, "context", "engine")
  767. def _get_plugin_toolset_key(name: str) -> Optional[str]:
  768. """Toolset key a plugin registers its tools under, or None: from the live registry (plugin
  769. already loaded), else from ``provides_tools`` in plugin.yaml looked up in the registry."""
  770. try:
  771. from tools.registry import registry
  772. except Exception:
  773. return None
  774. def _first_toolset(tool_names) -> Optional[str]:
  775. return next((e.toolset for t in tool_names if (e := registry.get_entry(t)) and e.toolset), None)
  776. def _from_loaded_plugin() -> Optional[str]:
  777. from hermes_cli.plugins import discover_plugins, get_plugin_manager
  778. discover_plugins() # idempotent — ensures plugins are loaded
  779. for _key, loaded in get_plugin_manager()._plugins.items():
  780. if loaded.manifest.name == name or _key == name:
  781. return _first_toolset(loaded.tools_registered)
  782. return None
  783. def _from_manifest_on_disk() -> Optional[str]:
  784. from hermes_cli.plugins import get_bundled_plugins_dir
  785. return next((
  786. toolset for base in (get_bundled_plugins_dir(), _plugins_dir())
  787. if base.is_dir() and (base / name).is_dir()
  788. and (toolset := _first_toolset(_read_manifest(base / name).get("provides_tools") or []))
  789. ), None)
  790. for lookup in (_from_loaded_plugin, _from_manifest_on_disk):
  791. try:
  792. if toolset := lookup():
  793. return toolset
  794. except Exception:
  795. continue
  796. return None
  797. def _saved_list_toolset_key(name: str) -> Optional[str]:
  798. """The plugin's toolset key, or None without loading any plugin when no platform has a SAVED
  799. ``platform_toolsets`` list (the only lists :func:`_toggle_plugin_toolset` edits)."""
  800. from hermes_cli.config import load_config
  801. from hermes_cli.toolset_validation import parse_platform_toolsets_value
  802. saved = load_config().get("platform_toolsets")
  803. if not isinstance(saved, dict) or all(parse_platform_toolsets_value(v) is None for v in saved.values()):
  804. return None
  805. return _get_plugin_toolset_key(name)
  806. def _toggle_plugin_toolset(name: str, *, enable: bool, toolset_key: Optional[str] = None) -> None:
  807. """Add/remove a plugin's toolset in every SAVED ``platform_toolsets`` list (no-op when the plugin
  808. provides no tools). Platforms with no saved list are left alone: a plugin toolset is already on
  809. there by default, and seeding ``[<plugin_ts>]`` would replace the core composite and strip every
  810. built-in tool. The key resolves only while the plugin is loaded, so enable calls this after the
  811. plugin loads and disable resolves *toolset_key* before the disable is written."""
  812. toolset_key = toolset_key or _saved_list_toolset_key(name)
  813. if not toolset_key:
  814. return
  815. from hermes_cli.config import load_config, save_config
  816. from hermes_cli.toolset_validation import parse_platform_toolsets_value
  817. config = load_config()
  818. platform_toolsets = _child_dict(config, "platform_toolsets")
  819. changed = False
  820. for platform, raw in list(platform_toolsets.items()):
  821. # A list-literal string (older `hermes config set`) is the user's real selection; toggling
  822. # it re-saves the entry as a proper list so the string never persists.
  823. ts_list = parse_platform_toolsets_value(raw)
  824. if ts_list is not None and enable != (toolset_key in ts_list):
  825. (ts_list.append if enable else ts_list.remove)(toolset_key)
  826. platform_toolsets[platform] = ts_list
  827. changed = True
  828. if changed:
  829. save_config(config)
  830. def dashboard_set_agent_plugin_enabled(name: str, *, enabled: bool) -> dict[str, Any]:
  831. """Enable or disable a plugin in ``config.yaml`` (runtime allow/deny lists). *name* may be the
  832. canonical key, the manifest name or a unique bare leaf; the canonical key is what gets written
  833. (the loader never matches a bare leaf, and a stale key in ``disabled`` outranks a manifest-name
  834. entry in ``enabled`` — so writing the raw identifier reported success while the plugin stayed off)."""
  835. key = _resolve_plugin_key(name)
  836. if key is None:
  837. return {"ok": False, "error": f"Plugin '{name}' is not installed or bundled."}
  838. from hermes_cli.plugins_admission import AdmissionRefused
  839. toolset_key = None if enabled else _saved_list_toolset_key(key)
  840. try:
  841. changed = _activate_key(key, enable=enabled)
  842. except AdmissionRefused as exc:
  843. return {
  844. "ok": False,
  845. "error": str(exc),
  846. "name": key,
  847. "unchanged": True,
  848. "restart_required": False,
  849. }
  850. if changed and enabled:
  851. # Load it now, here and in the running gateway; ``activation`` tells the UI what is live vs
  852. # deferred, and ``restart_required`` only survives when no gateway answered (#87770).
  853. from hermes_cli.plugins_activation import activate_plugin_now
  854. result = {"ok": True, "name": key, "unchanged": False, **activate_plugin_now(key)}
  855. # Only now is the plugin loaded here, so its toolset key resolves: a backend that scanned
  856. # while the plugin was off held a placeholder and the toolset was never re-added.
  857. _toggle_plugin_toolset(key, enable=True)
  858. return result
  859. if changed:
  860. _toggle_plugin_toolset(key, enable=False, toolset_key=toolset_key)
  861. # Disable is config-only: there is no un-wire primitive, so a running gateway keeps the plugin's
  862. # handlers until restart and every UI says so — #71595/#54941.
  863. return {"ok": True, "name": key, "unchanged": not changed, "restart_required": changed}
  864. def _user_installed_plugin_dir(name: str) -> Optional[Path]:
  865. """Resolved path under ``~/.hermes/plugins/<name>`` if it exists, else the user install
  866. :func:`_find_plugin_entry` resolves *name* to (its manifest or catalog name)."""
  867. try:
  868. target = _sanitize_plugin_name(name, _plugins_dir(), allow_subdir=True)
  869. except ValueError:
  870. return None
  871. return target if target.is_dir() else _resolved_user_plugin_dir(name)
  872. def _resolved_user_plugin_dir(name: str) -> Optional[Path]:
  873. """Dir of the user install :func:`_find_plugin_entry` resolves *name* to (manifest or catalog name)."""
  874. entry = _find_plugin_entry(name)
  875. found = Path(str(entry[4])) if entry and entry[3] in ("user", "git") and entry[4] else None
  876. return found if found is not None and found.is_dir() else None
  877. def cmd_plugin_doctor(target: str = ".", *, ci: bool = False) -> None:
  878. """Validate one plugin through runtime discovery and registration."""
  879. from hermes_cli.plugin_dev import doctor_plugin
  880. report = doctor_plugin(target)
  881. _console().print(report.format_text())
  882. if ci and not report.ok:
  883. raise SystemExit(1)
  884. def _tri_state_flag(args, yes_attr: str, no_attr: str) -> Optional[bool]:
  885. """Map an argparse ``--x`` / ``--no-x`` pair to True / False / None (neither given)."""
  886. return True if getattr(args, yes_attr, False) else (False if getattr(args, no_attr, False) else None)
  887. def _catalog():
  888. from hermes_cli import plugins_cmd_catalog
  889. return plugins_cmd_catalog
  890. def _action_update(args):
  891. if args.name:
  892. if getattr(args, "yes", False):
  893. _fail(_console(), "[red]Error:[/red] --yes only applies to `hermes plugins update` with no name.")
  894. cmd_update(args.name, force=getattr(args, "force", False))
  895. return
  896. if getattr(args, "force", False):
  897. _fail(_console(), "[red]Error:[/red] --force applies to one named plugin: `hermes plugins update <name> --force`.")
  898. from hermes_cli.plugins_cmd_update_all import cmd_update_all
  899. cmd_update_all(yes=getattr(args, "yes", False))
  900. def _action_auto_update(args):
  901. from hermes_cli.plugins_auto_update import auto_update_state, set_auto_update
  902. console = _console()
  903. state = getattr(args, "state", None)
  904. try:
  905. current = auto_update_state() if state is None else set_auto_update(state == "on")
  906. except PluginOperationError as exc:
  907. _fail(console, f"[red]Error:[/red] {exc}")
  908. word = "[green]on[/green]" if current["auto_apply"] else "[dim]off[/dim]"
  909. cadence = (f"checked every {current['check_hours']:g}h by the gateway" if current["check_hours"] > 0
  910. else "the gateway's check is off: plugins.auto_update_check_hours is 0")
  911. console.print(f"Plugin auto-update: {word} ({cadence}; updates load in new sessions)")
  912. def _action_pack(args):
  913. from hermes_cli.plugin_packs import pack_command
  914. pack_command(args)
  915. # Tri-state flags: neither --x nor --no-x given == None == interactive prompt.
  916. _PLUGIN_ACTIONS = {
  917. "install": lambda args: cmd_install(
  918. args.identifier,
  919. force=getattr(args, "force", False),
  920. enable=_tri_state_flag(args, "enable", "no_enable"),
  921. ref=getattr(args, "ref", None),
  922. allow_removed=getattr(args, "allow_removed", False),
  923. no_deps=getattr(args, "no_deps", False),
  924. yes_deps=getattr(args, "yes_deps", False)),
  925. "search": lambda args: _catalog().cmd_search(
  926. getattr(args, "term", "") or "", json_output=getattr(args, "json", False)),
  927. "browse": lambda args: _catalog().cmd_search(""),
  928. "validate": lambda args: _catalog().cmd_validate(
  929. args.path, as_json=getattr(args, "json", False), install_deps=getattr(args, "install_deps", False)),
  930. "update": _action_update,
  931. "auto-update": _action_auto_update,
  932. "autoupdate": _action_auto_update,
  933. "adopt": lambda args: cmd_adopt(args.name),
  934. "trust-update-url": lambda args: cmd_trust_update_url(args.name),
  935. "check-updates": lambda args: cmd_check_updates(args),
  936. "check": lambda args: cmd_check_updates(args),
  937. "remove": lambda args: cmd_remove(args.name),
  938. "rm": lambda args: cmd_remove(args.name),
  939. "uninstall": lambda args: cmd_remove(args.name),
  940. "enable": lambda args: cmd_enable(
  941. args.name,
  942. allow_tool_override=_tri_state_flag(args, "allow_tool_override", "no_allow_tool_override")),
  943. "disable": lambda args: cmd_disable(args.name),
  944. "capabilities": lambda args: cmd_capabilities(getattr(args, "name", None)),
  945. "list": lambda args: cmd_list(args),
  946. "ls": lambda args: cmd_list(args),
  947. "doctor": lambda args: cmd_plugin_doctor(args.target, ci=getattr(args, "ci", False)),
  948. "pack": _action_pack,
  949. "show": lambda args: cmd_show(args.name),
  950. "info": lambda args: _catalog().cmd_info(args.name),
  951. None: lambda args: cmd_toggle(),
  952. }
  953. def plugins_command(args) -> None:
  954. """Dispatch hermes plugins subcommands."""
  955. action = getattr(args, "plugins_action", None)
  956. handler = _PLUGIN_ACTIONS.get(action)
  957. if handler is None:
  958. _fail(_console(), f"[red]Unknown plugins action: {action}[/red]")
  959. handler(args)