plugins_content.py 5.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. """Content registrars on ``PluginContext``: plugin skills and Automation Blueprints.
  2. Bound into the class body (``from hermes_cli.plugins_content import ...``), so they are ordinary
  3. ``ctx.register_*`` methods and get the same abandoned-load guard as every other registrar.
  4. """
  5. from __future__ import annotations
  6. import logging
  7. from pathlib import Path
  8. from typing import Any, Iterable, Mapping, Optional
  9. from hermes_cli.plugins_ledger import PluginRegistration
  10. from hermes_cli.plugins_loader import _serialized_replacement
  11. # Same logger as the rest of the ctx surface, so plugin-load diagnostics stay in one place.
  12. logger = logging.getLogger("hermes_cli.plugins")
  13. __all__ = ["register_automation_blueprint", "register_skill"]
  14. def plugin_skill_owners(manager, qualified: str) -> set[str]:
  15. """The names ``plugins.enabled``/``plugins.disabled`` may use for the plugin that registered
  16. *qualified*: its key and manifest name. A portable plugin's skill prefix is a slug of its name
  17. (``foo.bar`` -> ``foo-bar``), so the prefix alone can name a different plugin."""
  18. entry = manager._plugin_skills.get(qualified) or {}
  19. owners = {entry.get("plugin_key"), entry.get("plugin_name")} - {None, ""}
  20. return owners or {qualified.partition(":")[0]}
  21. @_serialized_replacement
  22. def register_skill(
  23. self, name: str, path: Path, description: str = "",
  24. frontmatter: Optional[Mapping[str, Any]] = None,
  25. ) -> PluginRegistration:
  26. """Register a read-only skill resolvable as ``'<plugin_name>:<name>'`` via ``skill_view()``,
  27. listed by ``skills_list`` and in the system prompt's ``<available_skills>`` while the plugin
  28. is enabled. Not copied into ``~/.hermes/skills/``. Raises ``ValueError`` (``':'``/invalid
  29. chars) or ``FileNotFoundError``."""
  30. from agent.skill_utils import _NAMESPACE_RE
  31. from hermes_cli.plugins_manifest import _portable_slug
  32. if ":" in name:
  33. raise ValueError(f"Skill name '{name}' must not contain ':' (the namespace is derived from the "
  34. f"plugin name '{self.manifest.name}' automatically).")
  35. if not name or not _NAMESPACE_RE.match(name):
  36. raise ValueError(f"Invalid skill name '{name}'. Must match [a-zA-Z0-9_-]+.")
  37. # Plugin register() helpers commonly pass the SKILL.md location as str
  38. # (PluginManifest.path is stored as str); the registry and find_plugin_skill()
  39. # promise a Path downstream.
  40. path = Path(path)
  41. if not path.exists():
  42. raise FileNotFoundError(f"SKILL.md not found at {path}")
  43. namespace = _portable_slug(self.manifest.name) if self.manifest.portable else self.manifest.name
  44. qualified = f"{namespace}:{name}"
  45. existing = self._manager._plugin_skills.get(qualified)
  46. # Native-over-native keeps last-wins replacement; a clash involving a portable plugin is refused
  47. # either way round, so one plugin's instructions never load under another's name.
  48. if existing and (self.manifest.portable
  49. or (existing.get("portable") and existing.get("plugin_key") != self.plugin_id)):
  50. raise ValueError(f"Plugin skill '{qualified}' is already registered by plugin '{existing.get('plugin_key')}'")
  51. entry = {
  52. "path": path, "plugin": namespace, "plugin_key": self.plugin_id, "plugin_name": self.manifest.name,
  53. "portable": self.manifest.portable, "bare_name": name,
  54. "description": description, "frontmatter": dict(frontmatter or {}),
  55. }
  56. return self._register_entry("skill", qualified, self._manager._plugin_skills, entry,
  57. "Plugin %s registered skill: %s", qualified)
  58. def register_automation_blueprint(
  59. self, key: str, *, title: str, description: str, schedule_template: str,
  60. prompt_template: str, category: str = "general", slots: Iterable[Any] = (),
  61. deliver_default: str = "origin", skills: Iterable[str] = (), tags: Iterable[str] = (),
  62. ) -> Optional[PluginRegistration]:
  63. """Add an Automation Blueprint to this profile's catalog as ``'<plugin_name>:<key>'``
  64. (``/blueprint``, the dashboard/Desktop gallery). Fields mirror
  65. :class:`cron.blueprint_catalog.AutomationBlueprint`; ``slots`` are ``BlueprintSlot`` field
  66. mappings. Malformed input or a duplicate key logs a warning and returns ``None``."""
  67. from cron.blueprint_plugins import build_plugin_blueprint
  68. try:
  69. blueprint = build_plugin_blueprint(
  70. self.manifest.name, key, title=title, description=description,
  71. schedule_template=schedule_template, prompt_template=prompt_template, category=category,
  72. slots=slots, deliver_default=deliver_default, skills=skills, tags=tags,
  73. )
  74. except ValueError as exc:
  75. logger.warning("Plugin '%s' automation blueprint %r rejected: %s", self.manifest.name, key, exc)
  76. return None
  77. if blueprint.key in self._manager._automation_blueprints:
  78. logger.warning("Plugin '%s' automation blueprint %r is already registered",
  79. self.manifest.name, blueprint.key)
  80. return None
  81. return self._register_entry("automation_blueprint", blueprint.key,
  82. self._manager._automation_blueprints, blueprint,
  83. "Plugin %s registered automation blueprint: %s", blueprint.key)