plugins_cmd_remove.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. """``hermes plugins remove``: tree + install-metadata removal kept consistent, config bookkeeping, and the
  2. dashboard/TUI remove path.
  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 os
  8. import tempfile
  9. from pathlib import Path
  10. from typing import Any
  11. def _pc():
  12. """The facade, read at call time: tests patch ``plugins_cmd.<name>`` and sibling calls must see it."""
  13. from hermes_cli import plugins_cmd
  14. return plugins_cmd
  15. _PENDING_DELETE_DIR = "plugin-pending-delete"
  16. def _pending_delete_root() -> Path:
  17. """``<HERMES_HOME>/cache/plugin-pending-delete``: trees a running process still held at removal."""
  18. from hermes_constants import get_hermes_home
  19. return get_hermes_home() / "cache" / _PENDING_DELETE_DIR
  20. def sweep_pending_plugin_deletes() -> None:
  21. """Delete what an earlier remove parked because another process held it; cheap when empty.
  22. A ``<name>.path`` note names a stripped tree that could not even be moved out of ``plugins/``."""
  23. root = _pending_delete_root()
  24. if not root.is_dir():
  25. return
  26. for entry in root.iterdir():
  27. if entry.suffix == ".path" and entry.is_file():
  28. held = Path(entry.read_text(encoding="utf-8-sig").strip())
  29. _pc().rmtree_readonly(held, ignore_errors=True)
  30. if not held.exists():
  31. entry.unlink(missing_ok=True)
  32. else:
  33. _pc().rmtree_readonly(entry, ignore_errors=True)
  34. def _discard_tree(tree: Path) -> None:
  35. """Delete *tree*. On Windows a running gateway / plugin host that loaded the plugin keeps its
  36. native modules mapped and its open files locked (WinError 5/32), and deleting stops at the first
  37. one. The rest is then moved out of ``plugins/`` into the pending-delete area, so nothing loadable
  38. stays behind, and the sweep at the next start finishes the job."""
  39. try:
  40. _pc().rmtree_readonly(tree)
  41. return
  42. except PermissionError:
  43. if os.name != "nt" or not tree.exists():
  44. raise
  45. root = _pending_delete_root()
  46. root.mkdir(parents=True, exist_ok=True)
  47. parked = Path(tempfile.mkdtemp(prefix=f"{tree.name}-", dir=root)) / "plugin"
  48. try:
  49. os.replace(tree, parked) # same volume (both under HERMES_HOME): a rename, allowed on mapped DLLs
  50. except OSError:
  51. # A held directory itself (a process's cwd, an open handle on it) cannot even be renamed. Strip
  52. # its manifests so the remnant no longer loads, and leave the files to the next start.
  53. for name in ("plugin.yaml", "plugin.yml", "plugin.json", "__init__.py"):
  54. (tree / name).unlink(missing_ok=True)
  55. (root / f"{tree.parent.name}-{tree.name}.path").write_text(str(tree), encoding="utf-8")
  56. def _remove_plugin_core(target: Path) -> None:
  57. """Remove one plugin and its metadata without splitting their state."""
  58. if target.name not in _pc()._read_install_metadata():
  59. _discard_tree(target)
  60. return
  61. staging = Path(tempfile.mkdtemp(prefix=f".{target.name}.remove-", dir=target.parent))
  62. backup = staging / "plugin"
  63. try:
  64. os.replace(target, backup)
  65. except PermissionError:
  66. _pc().rmtree_readonly(staging, ignore_errors=True)
  67. if os.name != "nt":
  68. raise
  69. # Windows refuses to rename a directory another process holds open; record removal first
  70. # (the plugin is uninstalled from this point), then discard the tree in place.
  71. _pc()._update_install_record(target.name, lambda _current: None)
  72. _discard_tree(target)
  73. return
  74. try:
  75. _pc()._update_install_record(target.name, lambda _current: None)
  76. except Exception:
  77. try:
  78. os.replace(backup, target)
  79. except OSError as restore_exc:
  80. raise _pc().PluginOperationError(
  81. f"Plugin metadata update failed and '{target.name}' could not be "
  82. f"restored automatically; recovery copy remains at {backup}."
  83. ) from restore_exc
  84. _pc().rmtree_readonly(staging, ignore_errors=True)
  85. raise
  86. _discard_tree(staging)
  87. def cmd_remove(name: str) -> None:
  88. """Remove an installed plugin by name."""
  89. console = _pc()._console()
  90. plugins_dir = _pc()._plugins_dir()
  91. target = _pc()._require_installed_plugin(name, plugins_dir, console)
  92. try:
  93. result = _remove_user_plugin(plugins_dir, name, target)
  94. except (OSError, _pc().PluginOperationError) as exc:
  95. _pc()._fail(console, f"[red]Error:[/red] Could not remove plugin '{name}': {exc}")
  96. console.print()
  97. console.print(f"[red]✗[/red] Plugin [bold]{name}[/bold] removed from {plugins_dir}")
  98. if result.get("cleared_memory_provider"):
  99. console.print("[yellow]memory.provider pointed at this plugin and was reset; "
  100. "run `hermes memory setup` to pick another.[/yellow]")
  101. console.print()
  102. def _remove_user_plugin(plugins_dir: Path, name: str, target: Path) -> dict[str, Any]:
  103. """Shared ``remove`` tail for the CLI, the dashboard and the ``plugins.manage`` RPC.
  104. *target* is the resolved directory; when ``plugins_dir/name`` itself is a symlink only the link
  105. goes — the tree it points at may be another installed plugin (a dev alias to a sibling checkout),
  106. and following it deleted that plugin plus its install metadata while the alias stayed dangling.
  107. Config bookkeeping (aliases, toolset) is gathered before the tree disappears.
  108. """
  109. link = plugins_dir / name.strip("/")
  110. if link.is_symlink():
  111. link.unlink()
  112. return {"ok": True, "name": name, **_pc()._forget_plugin_config({link.name})}
  113. entry = next((e for e in _pc()._discover_all_plugins() if Path(str(e[4])) == target), None)
  114. key = entry[5] if entry else target.name
  115. aliases = _pc()._plugin_aliases(key) | {target.name}
  116. from hermes_cli.plugin_oauth import forget_plugin_grants, plugin_key
  117. grant_key = plugin_key(target) # grants are stored by directory key, which the manifest name may not match
  118. _pc()._toggle_plugin_toolset(key, enable=False)
  119. _remove_plugin_core(target)
  120. forget_plugin_grants(grant_key) # a later plugin installed under the same key must not inherit the sign-in
  121. return {"ok": True, "name": name, **_pc()._forget_plugin_config(aliases)}
  122. def dashboard_remove_user_plugin(name: str) -> dict[str, Any]:
  123. """Delete a plugin tree under ``~/.hermes/plugins/`` only."""
  124. plugins_dir = _pc()._plugins_dir()
  125. if any(n == name and src == "bundled" for n, _ver, _d, src, _path, _key in _pc()._discover_all_plugins()):
  126. return {"ok": False, "error": "Bundled plugins cannot be removed from the dashboard."}
  127. target = _pc()._user_installed_plugin_dir(name)
  128. if target is None:
  129. return {"ok": False, "error": f"Plugin '{name}' was not found under {plugins_dir}."}
  130. try:
  131. return _remove_user_plugin(plugins_dir, name, target)
  132. except (OSError, _pc().PluginOperationError) as exc:
  133. return {"ok": False, "error": f"Could not remove plugin '{name}': {exc}"}