__init__.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. """Memory provider plugin discovery: bundled ``plugins/memory/<name>/``, user
  2. ``$HERMES_HOME/plugins/<name>/``, project ``./.hermes/plugins/<name>/`` (opt-in via
  3. HERMES_ENABLE_PROJECT_PLUGINS), then ``hermes_agent.memory_providers`` entry points.
  4. Precedence is deliberately the REVERSE of PluginManager's later-source-wins:
  5. bundled wins, then user, project, entry point — a provider is activated by name
  6. (``memory.provider``, one at a time), so a directory dropped into the working tree
  7. must never shadow a shipped provider. Changing this order is a breaking change.
  8. """
  9. from __future__ import annotations
  10. import ast
  11. import hashlib
  12. import importlib.metadata
  13. import importlib.util
  14. import logging
  15. import sys
  16. from pathlib import Path
  17. from types import SimpleNamespace
  18. from typing import List, Optional, Tuple, TYPE_CHECKING
  19. from hermes_cli.config import cfg_get
  20. from plugins import plugin_loader as _loader
  21. if TYPE_CHECKING:
  22. from agent.memory_provider import MemoryProvider
  23. logger = logging.getLogger(__name__)
  24. _MEMORY_PLUGINS_DIR = Path(__file__).parent
  25. ENTRY_POINTS_GROUP = "hermes_agent.memory_providers"
  26. # Per Hermes home (plugin managers are per home too): pruning under one multiplexed profile must
  27. # only retract that profile's provider skills, never a sibling profile's.
  28. _REGISTERED_MEMORY_PROVIDER_SKILLS: dict[str, dict[str, Path]] = {}
  29. # Native extensions whose first import must not race another thread (#58083 warm-up).
  30. _NATIVE_WARM_IMPORTS: tuple[str, ...] = ("numpy",)
  31. def _registered_skills_for_active_home() -> dict[str, Path]:
  32. from hermes_constants import hermes_home_key
  33. return _REGISTERED_MEMORY_PROVIDER_SKILLS.setdefault(hermes_home_key(), {})
  34. # Synthetic parent package so user-installed providers don't collide with bundled ones.
  35. _USER_NAMESPACE = "_hermes_user_memory"
  36. _register_synthetic_package = _loader.register_synthetic_package
  37. _get_user_plugins_dir = _loader.user_plugins_dir
  38. def _get_project_plugins_dir() -> Optional[Path]:
  39. """``./.hermes/plugins/`` or None. Gated on HERMES_ENABLE_PROJECT_PLUGINS like the
  40. PluginManager scan: a repo you merely ``cd`` into must not offer a memory backend."""
  41. try:
  42. from hermes_cli.plugins import _env_enabled
  43. if not _env_enabled("HERMES_ENABLE_PROJECT_PLUGINS"):
  44. return None
  45. d = Path.cwd() / ".hermes" / "plugins"
  46. return d if d.is_dir() else None
  47. except Exception:
  48. return None
  49. def _is_memory_provider_dir(path: Path) -> bool:
  50. """Cheap text heuristic (no import): ``__init__.py`` mentions the memory provider contract.
  51. A miss in the first 8 KB falls back to parsing, so a long module docstring cannot hide a provider."""
  52. init_file = path / "__init__.py"
  53. try:
  54. if not init_file.exists():
  55. return False
  56. source = init_file.read_text(errors="replace", encoding="utf-8-sig")[:8192]
  57. return "register_memory_provider" in source or "MemoryProvider" in source or _defines_memory_provider(path)
  58. except OSError as exc: # one mode-000 / ACL-denied child must not abort discovery
  59. logger.warning("Skipping unreadable plugin directory %s: %s", path, exc)
  60. return False
  61. def _defines_memory_provider(path: Path) -> bool:
  62. """Parse (never import) the package's top-level modules for what ``_load_provider_from_dir`` can load:
  63. a ``register_memory_provider(...)`` call or a ``MemoryProvider`` subclass. Unlike the discovery
  64. heuristic, a docstring or comment naming the contract does not count."""
  65. for module in sorted(path.glob("*.py")):
  66. try:
  67. tree = ast.parse(module.read_text(errors="replace", encoding="utf-8-sig"))
  68. except (OSError, SyntaxError, ValueError):
  69. continue
  70. bases = {"MemoryProvider"} | {a.asname for n in ast.walk(tree) if isinstance(n, ast.ImportFrom)
  71. for a in n.names if a.name == "MemoryProvider" and a.asname}
  72. for node in ast.walk(tree):
  73. if isinstance(node, ast.Call) and "register_memory_provider" in (
  74. getattr(node.func, "attr", None), getattr(node.func, "id", None)):
  75. return True
  76. if isinstance(node, ast.ClassDef) and any(
  77. (getattr(b, "attr", None) or getattr(b, "id", None)) in bases for b in node.bases):
  78. return True
  79. return False
  80. def _is_bundled(provider_dir: Path) -> bool:
  81. return _MEMORY_PLUGINS_DIR in provider_dir.parents or provider_dir.parent == _MEMORY_PLUGINS_DIR
  82. def _module_name(provider_dir: Path, name: str) -> str:
  83. """``plugins.memory.<name>`` for bundled providers, else under the synthetic user namespace."""
  84. if _is_bundled(provider_dir):
  85. return f"plugins.memory.{name}"
  86. # Separate package trees, including relative imports, across homes/sources.
  87. digest = hashlib.sha256(str(provider_dir.resolve()).encode()).hexdigest()[:16]
  88. return f"{_USER_NAMESPACE}.{name}__source_{digest}"
  89. def _external_source_dirs() -> list[Path]:
  90. """User then project plugin roots that exist (precedence order)."""
  91. return [d for d in (_get_user_plugins_dir(), _get_project_plugins_dir()) if d]
  92. def _iter_provider_dirs() -> list[tuple[str, Path]]:
  93. """``(name, path)`` for bundled, then user-installed, then project-local; first-seen wins."""
  94. dirs = [(child.name, child) for child in _loader.iter_plugin_dirs(_MEMORY_PLUGINS_DIR)]
  95. seen = {name for name, _ in dirs}
  96. for source_dir in _external_source_dirs():
  97. for child in sorted(source_dir.iterdir()):
  98. if (
  99. child.is_dir()
  100. and not child.name.startswith(("_", "."))
  101. and child.name not in seen
  102. and _is_memory_provider_dir(child)
  103. ):
  104. seen.add(child.name)
  105. dirs.append((child.name, child))
  106. return dirs
  107. def _iter_entry_points():
  108. """Yield pip-installed memory provider entry points."""
  109. try:
  110. eps = importlib.metadata.entry_points()
  111. if hasattr(eps, "select"):
  112. return list(eps.select(group=ENTRY_POINTS_GROUP))
  113. return list(eps.get(ENTRY_POINTS_GROUP, [])) if isinstance(eps, dict) else [ep for ep in eps if ep.group == ENTRY_POINTS_GROUP]
  114. except Exception as exc:
  115. logger.debug("Memory provider entry-point scan failed: %s", exc)
  116. return []
  117. def find_provider_dir(name: str) -> Optional[Path]:
  118. """Provider name -> directory: bundled, user, project, then a pip entry point's
  119. package dir. The entry-point case matters because ``config_schema.py`` and
  120. ``cli.py`` are read from disk, not imported; without a directory a pip-installed
  121. provider silently loses its dashboard panel and ``hermes <provider>`` commands."""
  122. bundled = _MEMORY_PLUGINS_DIR / name
  123. if bundled.is_dir() and (bundled / "__init__.py").exists():
  124. return bundled
  125. for source_dir in _external_source_dirs():
  126. candidate = source_dir / name
  127. if candidate.is_dir() and _is_memory_provider_dir(candidate):
  128. return candidate
  129. return _entry_point_package_dir(find_provider_entry_point(name))
  130. def _entry_point_package_dir(entry_point) -> Optional[Path]:
  131. """Directory of an entry point's module, resolved WITHOUT importing it (discovery
  132. runs from the dashboard/argparse before a provider is selected; importing every
  133. candidate would run arbitrary code). Only package entry points yield a
  134. directory — a bare ``module.py`` has nowhere for a sibling ``config_schema.py``."""
  135. if entry_point is None:
  136. return None
  137. try:
  138. from hermes_cli.plugins import resolve_module_origin
  139. module_name = (entry_point.value or "").split(":")[0].strip()
  140. origin = resolve_module_origin(module_name)
  141. if not origin:
  142. return None
  143. path = Path(origin)
  144. return path.parent if path.name == "__init__.py" else None
  145. except Exception as exc:
  146. logger.debug("Could not resolve directory for entry point '%s': %s",
  147. getattr(entry_point, "name", "?"), exc)
  148. return None
  149. def find_provider_entry_point(name: str):
  150. """Resolve a provider name to a pip entry point, if installed."""
  151. return next((ep for ep in _iter_entry_points() if ep.name == name), None)
  152. def list_memory_provider_names() -> list[str]:
  153. """Cheap name-only listing (directory scan + entry-point enumeration, no import or
  154. availability check) — safe at module-import time (dashboard dropdown)."""
  155. names = {name for name, _ in _iter_provider_dirs()}
  156. names.update(ep.name for ep in _iter_entry_points())
  157. return sorted(names)
  158. def discover_memory_providers() -> list[tuple[str, str, bool]]:
  159. """``[(name, description, is_available), ...]``; bundled wins on name collisions,
  160. then user directories, then pip."""
  161. results = [
  162. (name, _loader.read_plugin_description(child),
  163. _loader.probe_availability(lambda c=child: _load_provider_from_dir(c, register_skills=False)))
  164. for name, child in _iter_provider_dirs()
  165. ]
  166. seen = {name for name, _, _ in results}
  167. for entry_point in _iter_entry_points():
  168. if entry_point.name not in seen:
  169. seen.add(entry_point.name)
  170. results.append((entry_point.name, "", _loader.probe_availability(
  171. lambda ep=entry_point: _load_provider_from_entry_point(ep, register_skills=False)
  172. )))
  173. return results
  174. def load_memory_provider(name: str, *, register_skills: Optional[bool] = None) -> Optional[MemoryProvider]:
  175. """Load a MemoryProvider by name (bundled, user, project, then pip entry point);
  176. None if not found or failing to load. Skills register only for the configured
  177. active provider unless ``register_skills`` is explicit, so inspecting inactive
  178. providers leaves no registry side effects."""
  179. if register_skills is None:
  180. register_skills = name == _get_active_memory_provider()
  181. provider_dir = find_provider_dir(name)
  182. entry_point = None if provider_dir else find_provider_entry_point(name)
  183. if not provider_dir and entry_point is None:
  184. logger.debug("Memory provider '%s' not found in bundled, user plugins, or entry points", name)
  185. return None
  186. if provider_dir is not None and _explicitly_disabled(name, provider_dir):
  187. # The Plugins hub / `hermes plugins disable` (or an update that could not install it) park a
  188. # user-installed provider in ``plugins.disabled``; the loader must honour it or "disabled" is a lie.
  189. logger.warning("%s", parked_provider_notice(name))
  190. return None
  191. def _load(_dir):
  192. if provider_dir:
  193. return _load_provider_from_dir(provider_dir, register_skills=register_skills)
  194. from hermes_cli.plugin_isolation import in_process_import_refusal
  195. refusal = in_process_import_refusal(f"pip-installed memory provider {name!r}")
  196. if refusal:
  197. logger.warning("%s", refusal)
  198. return None
  199. return _load_provider_from_entry_point(entry_point, register_skills=register_skills)
  200. return _loader.load_named(name, provider_dir, _load, kind="Memory provider", noun="provider", logger=logger)
  201. def import_memory_provider_module(name: Optional[str] = None) -> bool:
  202. """Import the provider's module (default: the configured ``memory.provider``) WITHOUT
  203. constructing a provider — the later ``load_memory_provider`` then hits ``sys.modules``
  204. instead of a fresh native extension load. Exists so ``hermes acp`` can pay the heavy
  205. import (numpy / ML stack) on the main thread before any other thread starts: on Windows
  206. a first-time native import racing another thread's import chain deadlocked
  207. ``session/new`` (#58083). False when no provider is configured, the provider is
  208. unknown or its import fails (agent init reports that)."""
  209. name = name or _get_active_memory_provider()
  210. if not name:
  211. return False
  212. from hermes_cli.plugin_isolation import ISOLATION_HOST, isolation_mode
  213. if isolation_mode() == ISOLATION_HOST and not _is_bundled(find_provider_dir(name) or Path("/")):
  214. return False # third-party code runs in the plugin host; nothing to warm in this process
  215. imported = False
  216. try:
  217. if provider_dir := find_provider_dir(name):
  218. imported = _load_package(provider_dir, name) is not None
  219. elif (entry_point := find_provider_entry_point(name)) is not None:
  220. entry_point.load()
  221. imported = True
  222. except Exception:
  223. logger.debug("memory provider '%s' warm-up import failed", name, exc_info=True)
  224. if imported:
  225. # The deadlock is numpy's lazy ``_core`` init; embedding-backed providers (e.g. the
  226. # hindsight plugin) defer that import to ``is_available()`` (sentence_transformers), so
  227. # the provider module alone leaves it unwarmed. Every reporter's workaround was a plain ``import numpy`` up front.
  228. for module in _NATIVE_WARM_IMPORTS:
  229. try:
  230. importlib.import_module(module)
  231. except Exception:
  232. logger.debug("warm-up import of %s skipped", module, exc_info=True)
  233. return imported
  234. def _load_package(provider_dir: Path, name: str):
  235. """Import the provider package at *provider_dir* under the module name the loader owns
  236. (``plugins.memory.<name>`` bundled, synthetic user namespace otherwise); None on failure."""
  237. return _loader.load_plugin_module(
  238. _module_name(provider_dir, name), provider_dir,
  239. parents=("plugins", "plugins.memory"),
  240. logger=logger,
  241. synthetic_namespace=None if _is_bundled(provider_dir) else _USER_NAMESPACE,
  242. )
  243. def import_provider_module(name: str, submodule: Optional[str] = None):
  244. """The package (or ``<package>.<submodule>``) of whichever copy of provider *name* is installed.
  245. Host-side code (dashboard host-block storage, OAuth routes, doctor, profile clone) used to
  246. ``import plugins.memory.<name>.<submodule>``, which only exists for the bundled copy; a
  247. catalog install under ``$HERMES_HOME/plugins/`` loads under the synthetic user namespace,
  248. so those surfaces 500'd/404'd the moment the bundled copy left core. Resolving through
  249. ``find_provider_dir`` makes bundled and user-dir copies behave identically. Raises
  250. ``ImportError`` when the provider is not installed or lacks the submodule.
  251. """
  252. provider_dir = find_provider_dir(name)
  253. if provider_dir is None:
  254. raise ImportError(f"memory provider {name!r} is not installed")
  255. package = _load_package(provider_dir, name)
  256. if package is None:
  257. raise ImportError(f"memory provider {name!r} failed to import")
  258. return importlib.import_module(f"{package.__name__}.{submodule}") if submodule else package
  259. def _instantiate_subclass(namespace) -> Optional[MemoryProvider]:
  260. """First instantiable ``MemoryProvider`` subclass found among *namespace*'s attributes."""
  261. from agent.memory_provider import MemoryProvider
  262. for attr_name in dir(namespace):
  263. attr = getattr(namespace, attr_name, None)
  264. if isinstance(attr, type) and issubclass(attr, MemoryProvider) and attr is not MemoryProvider:
  265. try:
  266. return attr()
  267. except Exception:
  268. pass
  269. return None
  270. def _load_provider_from_entry_point(entry_point, *, register_skills: bool = True) -> Optional[MemoryProvider]:
  271. """Import a provider entry point and extract the MemoryProvider instance: an
  272. instance, a subclass, a module with ``register(ctx)``, a factory / ``register``
  273. callable, or a namespace holding a subclass — in that order."""
  274. from agent.memory_provider import MemoryProvider
  275. loaded = entry_point.load()
  276. if isinstance(loaded, MemoryProvider):
  277. return loaded
  278. if isinstance(loaded, type) and issubclass(loaded, MemoryProvider):
  279. try:
  280. return loaded()
  281. except Exception:
  282. pass
  283. if hasattr(loaded, "register"):
  284. collector = _ProviderCollector(entry_point.name, register_skills=register_skills)
  285. collector.collect(loaded.register, source=getattr(loaded, "__file__", None))
  286. if collector.provider:
  287. return collector.provider
  288. if callable(loaded):
  289. try:
  290. provider = loaded()
  291. if isinstance(provider, MemoryProvider):
  292. return provider
  293. except TypeError:
  294. pass
  295. collector = _ProviderCollector(entry_point.name, register_skills=register_skills)
  296. collector.collect(loaded)
  297. return collector.provider
  298. provider = _instantiate_subclass(loaded)
  299. if provider is None:
  300. logger.debug("Memory provider entry point '%s' loaded no provider", entry_point.name)
  301. return provider
  302. def _load_provider_from_dir(provider_dir: Path, *, register_skills: bool = True) -> Optional[MemoryProvider]:
  303. """Import a provider module; ``register(ctx)`` first, else a top-level subclass."""
  304. name = provider_dir.name
  305. from hermes_cli.plugin_isolation import user_plugin_host
  306. host = None if _is_bundled(provider_dir) else user_plugin_host()
  307. if host is not None:
  308. return _ProviderCollector(name, register_skills=register_skills).collect_in_host(
  309. host, provider_dir, _module_name(provider_dir, name))
  310. mod = _load_package(provider_dir, name)
  311. if mod is None:
  312. return None
  313. if hasattr(mod, "register"):
  314. collector = _ProviderCollector(name, register_skills=register_skills)
  315. try:
  316. collector.collect(mod.register, source=mod.__file__)
  317. except Exception as e:
  318. # A raise AFTER register_memory_provider() must not cost us the provider:
  319. # falling through to the subclass scan would hand back a bare second
  320. # instance — a silent downgrade that looks like success.
  321. if collector.provider is None:
  322. logger.debug("register() failed for %s: %s", name, e)
  323. else:
  324. logger.warning(
  325. "Memory provider '%s' raised after registering (%s) — "
  326. "using the registered provider; later registrations were skipped",
  327. name, e,
  328. )
  329. if collector.provider:
  330. return collector.provider
  331. return _instantiate_subclass(mod)
  332. class _ProviderCollector:
  333. """Plugin context for memory providers: captures ``register_memory_provider``
  334. (the one call the activation path owns) and delegates other ``register_*``
  335. calls to a real ``PluginContext`` so providers have the full plugin surface."""
  336. def __init__(self, name: str, *, register_skills: bool = True):
  337. self.name = name
  338. self.provider = None
  339. self._register_skills = register_skills
  340. self._context = None
  341. self._hook_source = None
  342. def collect(self, register, *, source=None):
  343. """Run ``register`` with this collector; hooks it registers form the fallback group that
  344. general discovery of the same source replaces (see ``PluginLedgerMixin``)."""
  345. from hermes_cli.plugins_ledger import _hook_source_of
  346. module = sys.modules.get(getattr(register, "__module__", ""))
  347. self._hook_source = _hook_source_of(self.name, SimpleNamespace(__file__=source) if source else module)
  348. manager = self._plugin_context()._manager
  349. with manager._discovery_lock:
  350. manager._drop_fallback_hooks(self._hook_source)
  351. register(self)
  352. def collect_in_host(self, host, provider_dir: Path, module_name: str):
  353. """``collect`` for a provider whose code runs in the plugin host: the host captures the
  354. provider and forwards every other registration here. The discovery lock is NOT held across
  355. the host call — its registrations arrive on another thread and take the lock themselves."""
  356. from hermes_cli.plugins_ledger import _hook_source_of
  357. self._hook_source = _hook_source_of(self.name, SimpleNamespace(__file__=str(provider_dir / "__init__.py")))
  358. manager = self._plugin_context()._manager
  359. def drop_hooks() -> None: # also before a reload into a restarted host: no stale hook proxies
  360. with manager._discovery_lock:
  361. manager._drop_fallback_hooks(self._hook_source)
  362. drop_hooks()
  363. self.provider = host.load_instance(
  364. provider_dir, module_name=module_name, capture="register_memory_provider",
  365. base_ref="agent.memory_provider:MemoryProvider", ctx=self, before_reload=drop_hooks)
  366. return self.provider
  367. def register_hook(self, hook_name, callback, *, hold_stream=False):
  368. context = self._plugin_context()
  369. with context._manager._discovery_lock:
  370. return context._manager._register_fallback_hook(
  371. context, self._hook_source, hook_name, callback, hold_stream=hold_stream)
  372. def register_memory_provider(self, provider):
  373. self.provider = provider
  374. def register_skill(self, *args, **kwargs):
  375. """Forward skills to the plugin registry, tracking qualified name + path so
  376. switching the active provider can retract the previous one's skills. Gated
  377. on ``register_skills`` so inspecting an inactive provider has no side effects."""
  378. if not self._register_skills:
  379. return
  380. try:
  381. self._plugin_context().register_skill(*args, **kwargs)
  382. qualified_name = f"{self.name}:{args[0] if args else kwargs.get('name')}"
  383. from hermes_cli.plugins import get_plugin_manager
  384. registered_path = get_plugin_manager().find_plugin_skill(qualified_name)
  385. if registered_path is not None:
  386. _registered_skills_for_active_home()[qualified_name] = registered_path
  387. except Exception as exc:
  388. logger.debug("Memory provider '%s' failed to register skill: %s", self.name, exc)
  389. def register_cli_command(self, *args, **kwargs):
  390. pass # CLI registration happens via discover_plugin_cli_commands()
  391. def __getattr__(self, attr: str):
  392. """Delegate any other ``register_*`` call to a real ``PluginContext`` (a
  393. hand-maintained stub drifted: unknown calls raised and cost the provider).
  394. Non-``register_*`` attributes raise normally so a typo still fails loudly."""
  395. if not attr.startswith("register_"):
  396. raise AttributeError(attr)
  397. def _forward(*args, **kwargs):
  398. try:
  399. return self._plugin_context().__getattribute__(attr)(*args, **kwargs)
  400. except Exception as exc:
  401. # A secondary registration must not cost the provider itself.
  402. logger.warning("Memory provider '%s' failed to %s: %s", self.name, attr, exc)
  403. return None
  404. return _forward
  405. def _plugin_context(self):
  406. """A real ``PluginContext``, built once on demand: the common provider that only
  407. calls ``register_memory_provider`` must not pay for importing the plugin manager."""
  408. if self._context is None:
  409. from hermes_cli.plugins import PluginContext, PluginManifest, get_plugin_manager
  410. manifest = PluginManifest(name=self.name, key=self.name)
  411. self._context = PluginContext(manifest, get_plugin_manager())
  412. return self._context
  413. def _get_active_memory_provider() -> Optional[str]:
  414. """Active provider name from config.yaml (``memory.provider``), or None. Reads config only."""
  415. try:
  416. from hermes_cli.config import load_config
  417. config = load_config()
  418. return cfg_get(config, "memory", "provider") or None
  419. except Exception:
  420. return None
  421. def parked_provider_notice(name: str) -> Optional[str]:
  422. """The user-facing reason a configured provider is not loading because ``plugins.disabled`` parks
  423. it, naming the update that did so when there was one; None when it is not parked."""
  424. provider_dir = find_provider_dir(name)
  425. if provider_dir is None or not _explicitly_disabled(name, provider_dir):
  426. return None
  427. from hermes_cli.config import load_config
  428. from pm.plugins_state import RECORD
  429. record = cfg_get(load_config(), "plugins", RECORD)
  430. recorded = record.get(name) if isinstance(record, dict) else None
  431. why = (f" An update turned it off ({recorded.get('reason')}) and a later update retries it."
  432. if isinstance(recorded, dict) and recorded.get("reason") else "")
  433. return (f"⚠ Memory provider '{name}' is turned off: plugins.disabled lists it, so external memory is off "
  434. f"(built-in memory still works).{why} Turn it back on with `hermes plugins enable {name}`.")
  435. def _explicitly_disabled(name: str, provider_dir: Path) -> bool:
  436. """True when a NON-bundled provider is parked in ``plugins.disabled`` under any spelling the
  437. plugin commands write: the provider name, its directory name or its manifest ``name:``."""
  438. if _MEMORY_PLUGINS_DIR in provider_dir.parents:
  439. return False
  440. try:
  441. from hermes_cli.config import load_config
  442. disabled = cfg_get(load_config(), "plugins", "disabled")
  443. except Exception:
  444. return False
  445. if not isinstance(disabled, list):
  446. return False
  447. from pm.plugins_state import plugin_spellings
  448. return bool(plugin_spellings(provider_dir, name) & {v for v in disabled if isinstance(v, str)})
  449. def _prune_inactive_memory_provider_skills(active_provider: Optional[str] = None) -> None:
  450. """Remove tracked skills that no longer belong to the active provider."""
  451. if active_provider is None:
  452. active_provider = _get_active_memory_provider()
  453. from hermes_cli.plugins import get_plugin_manager
  454. manager = get_plugin_manager()
  455. registered = _registered_skills_for_active_home()
  456. for qualified_name, registered_path in list(registered.items()):
  457. if qualified_name.partition(":")[0] == active_provider:
  458. continue
  459. if manager.find_plugin_skill(qualified_name) == registered_path:
  460. manager.remove_plugin_skill(qualified_name)
  461. registered.pop(qualified_name, None)
  462. def discover_plugin_cli_commands() -> list[dict]:
  463. """CLI commands for the **active** memory plugin only. Imports just its ``cli.py``
  464. (``register_cli(subparser)``), never the provider module, so it is safe during
  465. argparse setup. At most one dict: name/help/description/setup_fn/handler_fn/plugin."""
  466. active_provider = _get_active_memory_provider() if _MEMORY_PLUGINS_DIR.is_dir() else None
  467. plugin_dir = find_provider_dir(active_provider) if active_provider else None
  468. if not plugin_dir or not (plugin_dir / "cli.py").exists():
  469. return []
  470. module_name = _module_name(plugin_dir, active_provider) + ".cli"
  471. if not _is_bundled(plugin_dir):
  472. from hermes_cli.plugin_isolation import in_process_import_refusal
  473. if in_process_import_refusal(f"memory provider {active_provider!r} CLI commands"):
  474. return []
  475. try:
  476. cli_mod = sys.modules.get(module_name)
  477. if cli_mod is None:
  478. if not _is_bundled(plugin_dir):
  479. # cli.py imports as _hermes_user_memory.<name>.cli, usually before the
  480. # provider is loaded: register parent packages so its relative imports
  481. # resolve without executing the plugin's __init__.py (the shell has no
  482. # __file__, so _load_provider_from_dir() still loads the real module).
  483. _register_synthetic_package(_USER_NAMESPACE, [])
  484. _register_synthetic_package(_module_name(plugin_dir, active_provider), [str(plugin_dir)])
  485. spec = importlib.util.spec_from_file_location(module_name, str(plugin_dir / "cli.py"))
  486. if not spec or not spec.loader:
  487. return []
  488. cli_mod = importlib.util.module_from_spec(spec)
  489. sys.modules[module_name] = cli_mod
  490. spec.loader.exec_module(cli_mod)
  491. register_cli = getattr(cli_mod, "register_cli", None)
  492. if not callable(register_cli):
  493. return []
  494. desc = _loader.read_plugin_description(plugin_dir)
  495. return [{
  496. "name": active_provider,
  497. "help": desc or f"Manage {active_provider} memory plugin",
  498. "description": desc or "",
  499. "setup_fn": register_cli,
  500. "handler_fn": getattr(cli_mod, f"{active_provider}_command", None),
  501. "plugin": active_provider,
  502. }]
  503. except Exception as e:
  504. logger.debug("Failed to scan CLI for memory plugin '%s': %s", active_provider, e)
  505. return []