blueprint_plugins.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. """Plugin-contributed Automation Blueprints (``ctx.register_automation_blueprint``).
  2. A plugin hands over the same fields an in-repo :class:`~cron.blueprint_catalog.AutomationBlueprint`
  3. carries; :func:`build_plugin_blueprint` validates them (bad input raises ``ValueError``, which the
  4. registrar logs and ignores) and namespaces the key as ``<plugin>:<key>``, so a plugin can never
  5. shadow a built-in. :func:`plugin_blueprints` reads the ACTIVE profile's plugin manager at call time;
  6. plugins load per profile, so nothing here is cached across profiles.
  7. """
  8. from __future__ import annotations
  9. import logging
  10. import re
  11. import string
  12. from dataclasses import fields
  13. from typing import Any, Iterable, List, Mapping
  14. from cron.blueprint_catalog import AutomationBlueprint, BlueprintSlot, fill_blueprint
  15. logger = logging.getLogger(__name__)
  16. __all__ = ["build_plugin_blueprint", "plugin_blueprints"]
  17. _KEY_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
  18. _NAMESPACE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$")
  19. _SLOT_NAME_RE = re.compile(r"^[A-Za-z_]\w{0,63}$")
  20. _SLOT_FIELDS = frozenset(f.name for f in fields(BlueprintSlot))
  21. # Placeholders ``_resolve_schedule`` derives itself: minute/hour from the ``time`` slot, dow from a
  22. # ``recurrence``/``day`` slot (or ``*`` when neither exists).
  23. _DERIVED_SCHEDULE_FIELDS = {"minute": "time", "hour": "time", "dow": None}
  24. def _text(name: str, value: Any) -> str:
  25. if not isinstance(value, str) or not value.strip():
  26. raise ValueError(f"{name} must be a non-empty string")
  27. return value.strip()
  28. def _strings(name: str, value: Any) -> tuple:
  29. if isinstance(value, str) or not isinstance(value, Iterable):
  30. raise ValueError(f"{name} must be a list of strings")
  31. items = tuple(value)
  32. if not all(isinstance(v, str) and v.strip() for v in items):
  33. raise ValueError(f"{name} must be a list of non-empty strings")
  34. return items
  35. def _slot(raw: Any) -> BlueprintSlot:
  36. """Accept a ``BlueprintSlot`` (in-process) or its field mapping (the plugin-host wire form)."""
  37. if isinstance(raw, BlueprintSlot):
  38. slot = raw
  39. elif isinstance(raw, Mapping):
  40. unknown = sorted(set(raw) - _SLOT_FIELDS)
  41. if unknown:
  42. raise ValueError(f"unknown slot field(s): {', '.join(unknown)}")
  43. data = dict(raw)
  44. if "options" in data:
  45. data["options"] = tuple(data["options"] or ())
  46. try:
  47. slot = BlueprintSlot(**data)
  48. except TypeError as exc: # missing name/type/label
  49. raise ValueError(f"slot {data.get('name')!r}: {exc}") from exc
  50. else:
  51. raise ValueError(f"slot must be a mapping, got {type(raw).__name__}")
  52. if not isinstance(slot.name, str) or not _SLOT_NAME_RE.match(slot.name):
  53. raise ValueError(f"invalid slot name {slot.name!r}")
  54. _text(f"slot {slot.name} label", slot.label)
  55. return slot
  56. def _placeholders(template: str, what: str) -> list[str]:
  57. names = []
  58. for _literal, name, _spec, _conv in string.Formatter().parse(template):
  59. if name is None:
  60. continue
  61. if not _SLOT_NAME_RE.match(name):
  62. raise ValueError(f"{what} placeholder {{{name}}} must be a plain slot name")
  63. names.append(name)
  64. return names
  65. def _validate(blueprint: AutomationBlueprint) -> None:
  66. by_name = {s.name: s for s in blueprint.slots}
  67. if len(by_name) != len(blueprint.slots):
  68. raise ValueError("slot names must be unique")
  69. for name in _placeholders(blueprint.prompt_template, "prompt_template"):
  70. slot = by_name.get(name)
  71. if slot is None:
  72. raise ValueError(f"prompt_template uses {{{name}}} but there is no slot named {name!r}")
  73. if slot.optional and slot.default in (None, ""):
  74. raise ValueError(f"prompt_template uses optional slot {name!r} that has no default")
  75. for name in _placeholders(blueprint.schedule_template, "schedule_template"):
  76. if name in _DERIVED_SCHEDULE_FIELDS:
  77. needed = _DERIVED_SCHEDULE_FIELDS[name]
  78. if needed and needed not in by_name:
  79. raise ValueError(f"schedule_template uses {{{name}}}, which needs a slot named {needed!r}")
  80. elif name not in by_name:
  81. raise ValueError(f"schedule_template uses {{{name}}} but there is no slot named {name!r}")
  82. # When every required slot has a default, fill it now so a broken template or schedule fails at
  83. # registration instead of on the user's first "Schedule it".
  84. if all(s.optional or s.default not in (None, "") for s in blueprint.slots):
  85. from cron.jobs import parse_schedule
  86. parse_schedule(fill_blueprint(blueprint, {})["schedule"])
  87. def build_plugin_blueprint(
  88. plugin: str, key: str, *, title: str, description: str, schedule_template: str,
  89. prompt_template: str, category: str = "general", slots: Iterable[Any] = (),
  90. deliver_default: str = "origin", skills: Iterable[str] = (), tags: Iterable[str] = (),
  91. ) -> AutomationBlueprint:
  92. """Validated blueprint keyed ``<plugin>:<key>``; raises ``ValueError`` on malformed input."""
  93. if not isinstance(plugin, str) or not _NAMESPACE_RE.match(plugin):
  94. raise ValueError(f"plugin name {plugin!r} cannot namespace a blueprint key")
  95. if not isinstance(key, str) or not _KEY_RE.match(key):
  96. raise ValueError(
  97. f"invalid key {key!r}: use lowercase letters, digits, '-' or '_' (the "
  98. f"'{plugin}:' namespace is added automatically)"
  99. )
  100. if isinstance(slots, (str, Mapping)) or not isinstance(slots, Iterable):
  101. raise ValueError("slots must be a list")
  102. blueprint = AutomationBlueprint(
  103. key=f"{plugin}:{key}",
  104. title=_text("title", title),
  105. description=_text("description", description),
  106. category=_text("category", category),
  107. schedule_template=_text("schedule_template", schedule_template),
  108. prompt_template=_text("prompt_template", prompt_template),
  109. slots=[_slot(s) for s in slots],
  110. deliver_default=_text("deliver_default", deliver_default),
  111. skills=_strings("skills", skills),
  112. tags=_strings("tags", tags),
  113. plugin=plugin,
  114. )
  115. _validate(blueprint)
  116. return blueprint
  117. def plugin_blueprints() -> list[AutomationBlueprint]:
  118. """Blueprints the active profile's enabled plugins registered (resolved per call)."""
  119. try:
  120. from hermes_cli.plugins import discover_plugins, get_plugin_manager
  121. discover_plugins() # idempotent; servers that never import model_tools still see plugins
  122. return get_plugin_manager().list_automation_blueprints()
  123. except Exception:
  124. logger.warning("plugin automation blueprints unavailable", exc_info=True)
  125. return []