plugins_auto_update.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. """Unattended plugin updates shared by every surface: the opt-in ``plugins.auto_apply`` switch, the
  2. one-click "update all" (Desktop, dashboard, ``/plugins update``), the one-updater-per-plugin lock,
  3. and the notice ``hermes update`` prints when it moved catalog pins.
  4. Sibling of :mod:`hermes_cli.plugins_cmd` (the facade is imported late, never at module level).
  5. """
  6. from __future__ import annotations
  7. import logging
  8. import threading
  9. from contextlib import ExitStack, contextmanager
  10. from pathlib import Path
  11. from typing import Any, Iterator
  12. logger = logging.getLogger(__name__)
  13. # A second updater of the same plugin is refused rather than queued: the first one's result already
  14. # answers the second's question, and a queued pull would run against a tree the first just replaced.
  15. _LOCK_WAIT_SECONDS = 1.0
  16. _lock_holders: dict[str, threading.local] = {}
  17. _lock_holders_guard = threading.Lock()
  18. def _pc():
  19. from hermes_cli import plugins_cmd
  20. return plugins_cmd
  21. def _holder(key: str) -> threading.local:
  22. with _lock_holders_guard:
  23. return _lock_holders.setdefault(key, threading.local())
  24. @contextmanager
  25. def plugin_update_lock(target: Path) -> Iterator[None]:
  26. """Hold the one-updater lock for the plugin at *target*, across threads and processes (the
  27. gateway's auto-apply tick, a terminal ``hermes plugins update``, Desktop and the dashboard).
  28. A busy lock raises ``PluginOperationError`` after a short wait, so every caller reports it like
  29. any other refusal (nothing changed); reentrant per thread."""
  30. from hermes_cli.auth import _file_lock
  31. from hermes_constants import get_hermes_home
  32. lock = get_hermes_home() / "cache" / "plugin-update-locks" / f"{target.name}.lock"
  33. stack = ExitStack()
  34. try:
  35. stack.enter_context(_file_lock(lock, _holder(str(lock)), _LOCK_WAIT_SECONDS, "plugin update busy"))
  36. except TimeoutError as exc:
  37. raise _pc().PluginOperationError(
  38. f"Plugin '{target.name}' is already being updated by another Hermes process; "
  39. "nothing was changed. Try again when that update finishes.") from exc
  40. with stack:
  41. yield
  42. # ── installs the user held ────────────────────────────────────────────────────────────────────
  43. HELD_WITH_REF = "held with --ref (installed off the catalog pin); `hermes plugins update {name}` moves it"
  44. class HeldWithRef(Exception):
  45. """An unattended update found the plugin held with ``--ref`` once it owned the plugin's update lock
  46. (the hold was recorded after the check that offered the update). Nothing was changed."""
  47. def held_with_ref(record: Any) -> bool:
  48. """A catalog install the user put on a commit of their choosing (``install <name> --ref <sha>``:
  49. ``pinned`` with an empty ``catalog.pin``). Only an explicit ``hermes plugins update <name>`` moves
  50. it: unattended paths would otherwise silently undo a deliberate rollback."""
  51. block = record.get("catalog") if isinstance(record, dict) else None
  52. return isinstance(block, dict) and record.get("pinned") is True and not block.get("pin")
  53. def unattended_gate(name: str, target: Path):
  54. """The unattended-update policy, checked under the plugin's update lock: raise :class:`HeldWithRef`
  55. when the CURRENT install record is held (an ``install --ref`` that finished during the check), else
  56. return the ``surface_gate(manifest, tree)`` a Git update runs on its candidate before publication.
  57. The gate raises ``RepinConsentRequired`` when the candidate adds tools, hooks, capabilities or
  58. other surface the installed plugin lacks, the same review a widened catalog pin gets."""
  59. from hermes_cli.plugins_cmd_catalog import RepinConsentRequired, plugin_surface, surface_delta
  60. pc = _pc()
  61. if held_with_ref(pc._read_install_metadata().get(target.name)):
  62. raise HeldWithRef(HELD_WITH_REF.format(name=name))
  63. installed = plugin_surface(pc._read_manifest(target), target)
  64. def gate(manifest: dict, tree: Path) -> None:
  65. delta = surface_delta(installed, plugin_surface(manifest, tree))
  66. if delta:
  67. raise RepinConsentRequired(name, "", delta)
  68. return gate
  69. def apply_unattended(name: str) -> None:
  70. """The gateway auto-apply tick's update of one plugin: ``update_one`` with no terminal. Refusals
  71. raise (``RepinConsentRequired`` for a widened pin, ``PluginOperationError``) so the tick can tell
  72. a pending review from a failure; ``cmd_update`` would turn both into an exit. :class:`HeldWithRef`
  73. when the install was held after the check."""
  74. from hermes_cli.plugins_cmd_update import update_one
  75. pc = _pc()
  76. target = pc._user_installed_plugin_dir(name)
  77. if target is None:
  78. raise pc.PluginOperationError(f"Plugin '{name}' is no longer installed.")
  79. update_one(name, target, pc._console(), interactive=False, unattended=True)
  80. # ── the auto-update switch ────────────────────────────────────────────────────────────────────
  81. def auto_update_state() -> dict[str, Any]:
  82. """``{"auto_apply", "check_hours"}`` for the active profile."""
  83. from hermes_cli.plugins_cadence import auto_apply_enabled, check_interval_hours
  84. return {"auto_apply": auto_apply_enabled(), "check_hours": check_interval_hours()}
  85. def set_auto_update(enabled: bool) -> dict[str, Any]:
  86. """Write ``plugins.auto_apply`` for the active profile and return the new state. Turning it on also
  87. clears the check marker, so the gateway's next housekeeping tick checks and applies instead of
  88. waiting out the rest of the interval."""
  89. from hermes_cli.config import get_config_path, is_managed
  90. from hermes_cli.config_backend import write_config_key
  91. from hermes_constants import get_hermes_home
  92. if is_managed():
  93. raise _pc().PluginOperationError(
  94. "This Hermes install's configuration is managed by a package manager; set plugins.auto_apply there.")
  95. write_config_key(get_config_path(), "plugins.auto_apply", bool(enabled))
  96. if enabled:
  97. _clear_check_marker(get_hermes_home())
  98. return auto_update_state()
  99. def _clear_check_marker(home: Path) -> None:
  100. from hermes_cli.plugins_cadence import _MARKERS_DIR
  101. (home / _MARKERS_DIR / "last-run").unlink(missing_ok=True)
  102. # ── update all, unattended ────────────────────────────────────────────────────────────────────
  103. def _apply_one(name: str) -> dict[str, str]:
  104. """One plan row through the dashboard's non-interactive update. A widened plugin (catalog pin or
  105. Git update) or a caution scan of a git update is NOT accepted on the user's behalf: the row comes
  106. back ``needs_review`` (a catalog re-pin accepts caution: a reviewer read that pin at admission).
  107. An install held with ``--ref`` after the check comes back ``held``."""
  108. from hermes_cli.plugins_cmd_update import dashboard_update_user_plugin
  109. try:
  110. res = dashboard_update_user_plugin(name, unattended=True)
  111. except Exception as exc: # per-plugin batch boundary: one crash must not stop the rest
  112. logger.warning("update of plugin %s failed", name, exc_info=True)
  113. return {"name": name, "status": "failed", "detail": f"{type(exc).__name__}: {exc}"}
  114. if res.get("held"):
  115. return {"name": name, "status": "held", "detail": str(res.get("error") or "")}
  116. if res.get("consent_required") or res.get("scan_blocked"):
  117. return {"name": name, "status": "needs_review", "detail": str(res.get("error") or "")}
  118. if not res.get("ok"):
  119. return {"name": name, "status": "failed", "detail": str(res.get("error") or "")}
  120. return {"name": str(res.get("name") or name), "status": "current" if res.get("unchanged") else "updated",
  121. "detail": ""}
  122. def update_all_unattended() -> dict[str, Any]:
  123. """Check every installed plugin, then update each one ``hermes plugins update`` would move (same
  124. plan: catalog re-pins and tracked Git pulls; pinned, held and pip rows are skipped with why).
  125. Returns ``{"results": [{name, status, detail}], "skipped": [{name, reason}], "current": n}``;
  126. status is ``updated`` / ``current`` / ``failed`` / ``needs_review`` (nothing changed; the
  127. plugin's own Update action walks the consent or scan review)."""
  128. from hermes_cli.plugins_cadence import record_check_results, snapshot_installs
  129. from hermes_cli.plugins_cmd_update_all import plan_update_all
  130. from hermes_cli.plugins_updates import run_checks
  131. plugins_dir = _pc()._plugins_dir()
  132. checked = snapshot_installs(plugins_dir)
  133. results = run_checks(plugins_dir)
  134. record_check_results(results, checked)
  135. plan = plan_update_all(results, checked)
  136. applied = [_apply_one(row.name) for row in plan.movable]
  137. return {"results": [r for r in applied if r["status"] != "held"],
  138. "skipped": [{"name": row.name, "reason": reason} for row, reason in plan.skipped]
  139. + [{"name": r["name"], "reason": r["detail"]} for r in applied if r["status"] == "held"],
  140. "current": plan.current}
  141. _STATUS_MARKS = {"updated": "✓ updated", "current": "= already current", "failed": "✗ failed",
  142. "needs_review": "! needs review"}
  143. def summary_lines(outcome: dict[str, Any]) -> list[str]:
  144. """Plain-text lines for an :func:`update_all_unattended` result (``/plugins update``)."""
  145. lines = [f" {_STATUS_MARKS[r['status']]} {r['name']}" + (f" ({r['detail']})" if r["detail"] else "")
  146. for r in outcome["results"]]
  147. lines += [f" - skipped {s['name']}: {s['reason']}" for s in outcome["skipped"]]
  148. if not outcome["results"]:
  149. lines.append(" No plugin updates to apply.")
  150. if any(r["status"] == "needs_review" for r in outcome["results"]):
  151. lines.append(" Review those with `hermes plugins update <name>` in a terminal.")
  152. if any(r["status"] == "updated" for r in outcome["results"]):
  153. lines.append(" Updated plugins were reloaded: MCP servers and skills are live now, Python tools load in new sessions.")
  154. return lines
  155. def plugins_slash_action(parts: list[str]) -> list[str]:
  156. """``/plugins update`` (update every plugin with an update, unattended) and ``/plugins auto-update
  157. [on|off]`` for the classic CLI, and ``auto-update`` for the TUI's slash worker. The TUI sends
  158. ``/plugins update`` to ``plugins.manage update_all`` instead: the batch outlives the worker's 45 s."""
  159. if parts[0] == "update":
  160. if len(parts) > 1: # not `hermes plugins update <name>`: this form updates every plugin
  161. return ["Usage: /plugins update (updates every plugin that has an update; "
  162. "update one with `hermes plugins update <name>` in a terminal)"]
  163. return ["Plugin updates:", *summary_lines(update_all_unattended())]
  164. arg = parts[1].lower() if len(parts) > 1 else ""
  165. if arg not in ("", "on", "off"):
  166. return ["Usage: /plugins auto-update [on|off]"]
  167. try:
  168. state = auto_update_state() if not arg else set_auto_update(arg == "on")
  169. except _pc().PluginOperationError as exc:
  170. return [f" {exc}"]
  171. word = "on" if state["auto_apply"] else "off"
  172. return [f"Plugin auto-update: {word} (gateway check every {state['check_hours']:g}h; "
  173. "updates load in new sessions)"]
  174. # ── after `hermes update` ─────────────────────────────────────────────────────────────────────
  175. def catalog_pins_behind(home: Path) -> list[str]:
  176. """Catalog installs under *home* whose installed pin is not the in-tree catalog's pin. Offline:
  177. reads the install records and the catalog shipped with this checkout. An install held with
  178. ``--ref`` is not behind: the user chose that commit."""
  179. from hermes_cli.plugin_catalog import get_catalog_entry
  180. from hermes_cli.plugins_cmd_catalog import at_catalog_pin
  181. from hermes_cli.plugins_provenance import read_sidecar_rows
  182. behind = []
  183. for name, row in read_sidecar_rows(home / "plugins").items():
  184. block = row.get("catalog") if isinstance(row, dict) else None
  185. if not isinstance(block, dict) or not block.get("name") or held_with_ref(row):
  186. continue
  187. entry = get_catalog_entry(str(block["name"]))
  188. if entry is not None and not at_catalog_pin(block, entry.sha):
  189. behind.append(str(name))
  190. return sorted(behind)
  191. def report_catalog_updates_after_hermes_update(home: Path, sibling_homes: list[tuple[str, Path]]) -> None:
  192. """An update can move catalog pins; installed plugins stay on their old pin until updated. Name
  193. them per profile, and clear that profile's check marker so its gateway re-checks on the next tick
  194. (which applies them when that profile opted into ``plugins.auto_apply``)."""
  195. for label, profile_home in [("this profile", home), *sibling_homes]:
  196. behind = catalog_pins_behind(profile_home)
  197. if not behind:
  198. continue
  199. _clear_check_marker(profile_home)
  200. print(f" → {len(behind)} plugin update(s) from the new catalog in {label}: {', '.join(behind)}")
  201. print(" apply: hermes plugins update (or turn on: hermes plugins auto-update on)")