Skip to content

The agent that grows with you

feat(plugins): let plugins register Automation Blueprints via ctx

Tekniuma928a959e33b
diff --git a/apps/desktop/src/api/cron.ts b/apps/desktop/src/api/cron.ts
index 5483ddfb223..61405590c42 100644
--- a/apps/desktop/src/api/cron.ts
+++ b/apps/desktop/src/api/cron.ts
@@ -141,16 +141,15 @@ export function deleteCronJob(jobId: string): Promise<{ ok: boolean }> {
// instantiateAutomationBlueprint fills the slots and creates a real cron job via
// the same create_job path as createCronJob.
//
-// Profile-scoping is intentionally asymmetric: the GET catalog is global (the
-// list endpoint takes no profile — only deliver options are rewritten from the
-// configured gateways), so it carries only the profileScoped() header for
-// routing. instantiate creates a real per-profile job, so it names the target
-// profile explicitly via ?profile=. This mirrors the dashboard's api.ts.
-export function getAutomationBlueprints(): Promise<{ blueprints: AutomationBlueprint[] }> {
+// Both calls name the target profile via ?profile=: the catalog is per profile
+// (built-ins plus that profile's plugin-registered blueprints, deliver options
+// from its gateways), and instantiate creates the job in that profile. Fetch the
+// catalog for the same profile you instantiate into. Mirrors the dashboard's api.ts.
+export function getAutomationBlueprints(profile: string): Promise<{ blueprints: AutomationBlueprint[] }> {
return hermesApi<{ blueprints: AutomationBlueprint[] }>({
...profileScoped(),
...connectionScoped(),
- path: '/api/cron/blueprints',
+ path: `/api/cron/blueprints?profile=${encodeURIComponent(profile)}`,
timeoutMs: STARTUP_REQUEST_TIMEOUT_MS
})
}
diff --git a/apps/desktop/src/app/cron/index.tsx b/apps/desktop/src/app/cron/index.tsx
index 445a20f770e..6ef10bf0a95 100644
--- a/apps/desktop/src/app/cron/index.tsx
+++ b/apps/desktop/src/app/cron/index.tsx
@@ -103,6 +103,13 @@ function cronProfileForScope(scope: string): string {
return scope === ALL_PROFILES ? 'all' : scope
}
+// A blueprint writes a real per-profile job, and "all" is not a writable target —
+// collapse it to 'default', matching the manual create path in handleEditorSave.
+// The catalog is fetched for the same profile: plugin blueprints are per profile.
+function blueprintProfileForScope(scope: string): string {
+ return scope === ALL_PROFILES ? 'default' : scope
+}
+
const SCHEDULE_OPTIONS: ReadonlyArray<ScheduleOption> = [
{ expr: '0 9 * * *', value: 'daily' },
{ expr: '0 9 * * 1-5', value: 'weekdays' },
@@ -407,9 +414,11 @@ export function CronView({ onClose, onOpenSession, setStatusbarItemGroup: _setSt
// Blueprint recipes render in the same list rail, below the jobs — clicking
// one opens the create dialog pre-seeded to that recipe. Same query key as
// the dialog's "Start from" dropdown, so the catalog is fetched once.
+ const blueprintProfile = blueprintProfileForScope(profileScope)
+
const blueprintsQuery = useQuery({
- queryKey: ['cron-blueprints'],
- queryFn: async () => (await getAutomationBlueprints()).blueprints
+ queryKey: ['cron-blueprints', blueprintProfile],
+ queryFn: async () => (await getAutomationBlueprints(blueprintProfile)).blueprints
})
const visibleBlueprints = useMemo(() => {
@@ -609,11 +618,9 @@ export function CronView({ onClose, onOpenSession, setStatusbarItemGroup: _setSt
// Blueprint instantiation is a distinct backend path (fills typed slots, then
// creates the job) so it can't share the raw-cron onSave contract. Merge the
- // created job into $cronJobs like every other create path. A blueprint writes a
- // real per-profile job, and "all" is not a writable target — collapse it to
- // 'default', matching the manual create path in handleEditorSave.
+ // created job into $cronJobs like every other create path.
async function handleBlueprintCreate(blueprint: AutomationBlueprint, values: Record<string, string>) {
- const writableProfile = profileScope === ALL_PROFILES ? 'default' : profileScope
+ const writableProfile = blueprintProfile
const {
value: job,
@@ -692,6 +699,7 @@ export function CronView({ onClose, onOpenSession, setStatusbarItemGroup: _setSt
active={false}
icon="rocket"
key={item.key}
+ meta={item.plugin || undefined}
onSelect={() => setEditor({ blueprintKey: item.key, mode: 'create' })}
rowKey={`blueprint-${item.key}`}
title={item.title}
@@ -734,6 +742,7 @@ export function CronView({ onClose, onOpenSession, setStatusbarItemGroup: _setSt
)}
<CronEditorDialog
+ blueprintProfile={blueprintProfile}
editor={editor}
onBlueprintCreate={handleBlueprintCreate}
onClose={() => setEditor({ mode: 'closed' })}
@@ -1069,11 +1078,13 @@ export function DeliverCheckboxes({
}
function CronEditorDialog({
+ blueprintProfile,
editor,
onBlueprintCreate,
onClose,
onSave
}: {
+ blueprintProfile: string
editor: EditorState
onBlueprintCreate: (blueprint: AutomationBlueprint, values: Record<string, string>) => Promise<void>
onClose: () => void
@@ -1107,8 +1118,8 @@ function CronEditorDialog({
// The blueprint catalog powers the create dialog's "Start from" dropdown; it's
// meaningless when editing an existing job, so skip the fetch there.
const blueprintsQuery = useQuery({
- queryKey: ['cron-blueprints'],
- queryFn: async () => (await getAutomationBlueprints()).blueprints,
+ queryKey: ['cron-blueprints', blueprintProfile],
+ queryFn: async () => (await getAutomationBlueprints(blueprintProfile)).blueprints,
enabled: open && !isEdit
})
@@ -1277,6 +1288,7 @@ function CronEditorDialog({
{blueprintList.map(item => (
<SelectItem key={item.key} value={item.key}>
{item.title}
+ {item.plugin && <span className="ml-1.5 text-muted-foreground">· {item.plugin}</span>}
</SelectItem>
))}
</SelectContent>
diff --git a/apps/desktop/src/app/cron/plugin-blueprints.test.tsx b/apps/desktop/src/app/cron/plugin-blueprints.test.tsx
new file mode 100644
index 00000000000..80279696e61
--- /dev/null
+++ b/apps/desktop/src/app/cron/plugin-blueprints.test.tsx
@@ -0,0 +1,116 @@
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import { atom } from 'nanostores'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import type { AutomationBlueprint, CronJob } from '@/hermes'
+
+const hermes = vi.hoisted(() => ({
+ getAutomationBlueprints: vi.fn(),
+ getCronJobs: vi.fn(),
+ instantiateAutomationBlueprint: vi.fn()
+}))
+
+vi.mock('@/hermes', async importOriginal => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ getAutomationBlueprints: hermes.getAutomationBlueprints,
+ getCronDeliveryTargets: vi.fn(async () => ({ targets: [] })),
+ getCronJobs: hermes.getCronJobs,
+ instantiateAutomationBlueprint: hermes.instantiateAutomationBlueprint
+}))
+
+// The view writes jobs into a named profile; pin the scope instead of booting the gateway store.
+vi.mock('@/store/profile', async importOriginal => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ $profileScope: atom('work')
+}))
+
+const { CronView } = await import('./index')
+
+const pluginBlueprint: AutomationBlueprint = {
+ appUrl: 'hermes://blueprint/teamtools%3Astandup',
+ category: 'work',
+ command: '/blueprint teamtools:standup',
+ description: 'Weekday summary of what changed in a repo.',
+ fields: [
+ {
+ default: '09:15',
+ help: '',
+ label: 'What time?',
+ name: 'time',
+ optional: false,
+ options: [],
+ strict: true,
+ type: 'time'
+ }
+ ],
+ key: 'teamtools:standup',
+ plugin: 'teamtools',
+ source: 'plugin',
+ tags: ['work'],
+ title: 'Team standup digest'
+}
+
+const builtinBlueprint: AutomationBlueprint = {
+ ...pluginBlueprint,
+ appUrl: 'hermes://blueprint/morning-brief',
+ command: '/blueprint morning-brief',
+ key: 'morning-brief',
+ plugin: null,
+ source: 'builtin',
+ title: 'Morning briefing'
+}
+
+function renderView() {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+
+ return render(
+ <QueryClientProvider client={client}>
+ <CronView onClose={() => {}} />
+ </QueryClientProvider>
+ )
+}
+
+beforeEach(() => {
+ hermes.getCronJobs.mockResolvedValue([])
+ hermes.getAutomationBlueprints.mockResolvedValue({ blueprints: [builtinBlueprint, pluginBlueprint] })
+ hermes.instantiateAutomationBlueprint.mockResolvedValue({
+ id: 'job-1',
+ name: 'Team standup digest',
+ prompt: 'Summarize yesterday',
+ schedule: { kind: 'cron', expr: '15 9 * * 1-5' }
+ } as unknown as CronJob)
+})
+
+afterEach(() => {
+ cleanup()
+ vi.clearAllMocks()
+})
+
+describe('plugin-registered automation blueprints', () => {
+ it('lists the plugin blueprint with its plugin label and instantiates it into the scoped profile', async () => {
+ renderView()
+
+ const title = await screen.findByText('Team standup digest')
+ const row = title.closest('button') as HTMLElement
+ // PanelListRow renders `meta` (the plugin name) beside the row's button.
+ expect(within(row.parentElement as HTMLElement).getByText('teamtools')).toBeTruthy()
+ const builtinRow = screen.getByText('Morning briefing').closest('button') as HTMLElement
+ expect(within(builtinRow.parentElement as HTMLElement).queryByText('teamtools')).toBeNull()
+ // The catalog is per profile (plugins load per profile): fetched for the job's target profile.
+ expect(hermes.getAutomationBlueprints).toHaveBeenCalledWith('work')
+
+ fireEvent.click(row)
+ // The dialog's "Start from" select names the plugin next to the title.
+ expect(await screen.findByText('· teamtools')).toBeTruthy()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Schedule it' }))
+
+ await waitFor(() =>
+ expect(hermes.instantiateAutomationBlueprint).toHaveBeenCalledWith(
+ { blueprint: 'teamtools:standup', values: { time: '09:15' } },
+ 'work'
+ )
+ )
+ })
+})
diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.ts
index 171ddc23771..f2a3851404e 100644
--- a/apps/desktop/src/types/hermes.ts
+++ b/apps/desktop/src/types/hermes.ts
@@ -1096,6 +1096,10 @@ export interface AutomationBlueprint {
fields: AutomationBlueprintField[]
command: string
appUrl: string
+ /** Where it comes from; absent on backends that predate plugin blueprints. */
+ source?: 'builtin' | 'plugin'
+ /** The registering plugin's name when source is 'plugin' (key is `<plugin>:<key>`). */
+ plugin?: null | string
}
export interface ProfileCreatePayload {
diff --git a/cron/blueprint_catalog.py b/cron/blueprint_catalog.py
index 4a938e4a3a8..f34e6598fe1 100644
--- a/cron/blueprint_catalog.py
+++ b/cron/blueprint_catalog.py
@@ -16,6 +16,7 @@ __all__ = [
"AutomationBlueprint",
"CATALOG",
"get_blueprint",
+ "list_blueprints",
"blueprint_form_schema",
"blueprint_slash_command",
"blueprint_deeplink",
@@ -80,6 +81,9 @@ class AutomationBlueprint:
deliver_default: str = "origin"
skills: tuple = () # skills the job loads before running
tags: tuple = ()
+ # Registering plugin for a ``ctx.register_automation_blueprint`` entry (key ``<plugin>:<key>``);
+ # empty for the in-repo catalog.
+ plugin: str = ""
# ---------------------------------------------------------------------------
@@ -549,8 +553,23 @@ CATALOG: List[AutomationBlueprint] = [
_CATALOG_BY_KEY = {r.key: r for r in CATALOG}
+def list_blueprints() -> List[AutomationBlueprint]:
+ """The catalog every surface lists: built-ins, then the active profile's plugin blueprints.
+ Resolved per call — plugins load per profile, so one process serving several profiles must not
+ cache this."""
+ from cron.blueprint_plugins import plugin_blueprints
+
+ return [*CATALOG, *plugin_blueprints()]
+
+
def get_blueprint(key: str) -> Optional[AutomationBlueprint]:
- return _CATALOG_BY_KEY.get(key)
+ """Look up a built-in or (``<plugin>:<key>``) one of the active profile's plugin blueprints."""
+ blueprint = _CATALOG_BY_KEY.get(key)
+ if blueprint is None and ":" in (key or ""):
+ from cron.blueprint_plugins import plugin_blueprints
+
+ blueprint = next((b for b in plugin_blueprints() if b.key == key), None)
+ return blueprint
def _slot(
@@ -650,6 +669,8 @@ def blueprint_catalog_entry(blueprint: AutomationBlueprint) -> Dict[str, Any]:
slash command + deep-link URL + human-readable schedule."""
return {
**blueprint_form_schema(blueprint),
+ "source": "plugin" if blueprint.plugin else "builtin",
+ "plugin": blueprint.plugin or None,
"schedule": blueprint.schedule_template,
"scheduleHuman": _humanize_schedule(blueprint),
"command": blueprint_slash_command(blueprint),
diff --git a/cron/blueprint_plugins.py b/cron/blueprint_plugins.py
new file mode 100644
index 00000000000..1687611743b
--- /dev/null
+++ b/cron/blueprint_plugins.py
@@ -0,0 +1,148 @@
+"""Plugin-contributed Automation Blueprints (``ctx.register_automation_blueprint``).
+
+A plugin hands over the same fields an in-repo :class:`~cron.blueprint_catalog.AutomationBlueprint`
+carries; :func:`build_plugin_blueprint` validates them (bad input raises ``ValueError``, which the
+registrar logs and ignores) and namespaces the key as ``<plugin>:<key>``, so a plugin can never
+shadow a built-in. :func:`plugin_blueprints` reads the ACTIVE profile's plugin manager at call time;
+plugins load per profile, so nothing here is cached across profiles.
+"""
+
+from __future__ import annotations
+
+import logging
+import re
+import string
+from dataclasses import fields
+from typing import Any, Iterable, List, Mapping
+
+from cron.blueprint_catalog import AutomationBlueprint, BlueprintSlot, fill_blueprint
+
+logger = logging.getLogger(__name__)
+
+__all__ = ["build_plugin_blueprint", "plugin_blueprints"]
+
+_KEY_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
+_NAMESPACE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$")
+_SLOT_NAME_RE = re.compile(r"^[A-Za-z_]\w{0,63}$")
+_SLOT_FIELDS = frozenset(f.name for f in fields(BlueprintSlot))
+# Placeholders ``_resolve_schedule`` derives itself: minute/hour from the ``time`` slot, dow from a
+# ``recurrence``/``day`` slot (or ``*`` when neither exists).
+_DERIVED_SCHEDULE_FIELDS = {"minute": "time", "hour": "time", "dow": None}
+
+
+def _text(name: str, value: Any) -> str:
+ if not isinstance(value, str) or not value.strip():
+ raise ValueError(f"{name} must be a non-empty string")
+ return value.strip()
+
+
+def _strings(name: str, value: Any) -> tuple:
+ if isinstance(value, str) or not isinstance(value, Iterable):
+ raise ValueError(f"{name} must be a list of strings")
+ items = tuple(value)
+ if not all(isinstance(v, str) and v.strip() for v in items):
+ raise ValueError(f"{name} must be a list of non-empty strings")
+ return items
+
+
+def _slot(raw: Any) -> BlueprintSlot:
+ """Accept a ``BlueprintSlot`` (in-process) or its field mapping (the plugin-host wire form)."""
+ if isinstance(raw, BlueprintSlot):
+ slot = raw
+ elif isinstance(raw, Mapping):
+ unknown = sorted(set(raw) - _SLOT_FIELDS)
+ if unknown:
+ raise ValueError(f"unknown slot field(s): {', '.join(unknown)}")
+ data = dict(raw)
+ if "options" in data:
+ data["options"] = tuple(data["options"] or ())
+ try:
+ slot = BlueprintSlot(**data)
+ except TypeError as exc: # missing name/type/label
+ raise ValueError(f"slot {data.get('name')!r}: {exc}") from exc
+ else:
+ raise ValueError(f"slot must be a mapping, got {type(raw).__name__}")
+ if not isinstance(slot.name, str) or not _SLOT_NAME_RE.match(slot.name):
+ raise ValueError(f"invalid slot name {slot.name!r}")
+ _text(f"slot {slot.name} label", slot.label)
+ return slot
+
+
+def _placeholders(template: str, what: str) -> List[str]:
+ names = []
+ for _literal, name, _spec, _conv in string.Formatter().parse(template):
+ if name is None:
+ continue
+ if not _SLOT_NAME_RE.match(name):
+ raise ValueError(f"{what} placeholder {{{name}}} must be a plain slot name")
+ names.append(name)
+ return names
+
+
+def _validate(blueprint: AutomationBlueprint) -> None:
+ by_name = {s.name: s for s in blueprint.slots}
+ if len(by_name) != len(blueprint.slots):
+ raise ValueError("slot names must be unique")
+ for name in _placeholders(blueprint.prompt_template, "prompt_template"):
+ slot = by_name.get(name)
+ if slot is None:
+ raise ValueError(f"prompt_template uses {{{name}}} but there is no slot named {name!r}")
+ if slot.optional and slot.default in (None, ""):
+ raise ValueError(f"prompt_template uses optional slot {name!r} that has no default")
+ for name in _placeholders(blueprint.schedule_template, "schedule_template"):
+ if name in _DERIVED_SCHEDULE_FIELDS:
+ needed = _DERIVED_SCHEDULE_FIELDS[name]
+ if needed and needed not in by_name:
+ raise ValueError(f"schedule_template uses {{{name}}}, which needs a slot named {needed!r}")
+ elif name not in by_name:
+ raise ValueError(f"schedule_template uses {{{name}}} but there is no slot named {name!r}")
+ # When every required slot has a default, fill it now so a broken template or schedule fails at
+ # registration instead of on the user's first "Schedule it".
+ if all(s.optional or s.default not in (None, "") for s in blueprint.slots):
+ from cron.jobs import parse_schedule
+
+ parse_schedule(fill_blueprint(blueprint, {})["schedule"])
+
+
+def build_plugin_blueprint(
+ plugin: str, key: str, *, title: str, description: str, schedule_template: str,
+ prompt_template: str, category: str = "general", slots: Iterable[Any] = (),
+ deliver_default: str = "origin", skills: Iterable[str] = (), tags: Iterable[str] = (),
+) -> AutomationBlueprint:
+ """Validated blueprint keyed ``<plugin>:<key>``; raises ``ValueError`` on malformed input."""
+ if not isinstance(plugin, str) or not _NAMESPACE_RE.match(plugin):
+ raise ValueError(f"plugin name {plugin!r} cannot namespace a blueprint key")
+ if not isinstance(key, str) or not _KEY_RE.match(key):
+ raise ValueError(
+ f"invalid key {key!r}: use lowercase letters, digits, '-' or '_' (the "
+ f"'{plugin}:' namespace is added automatically)"
+ )
+ if isinstance(slots, (str, Mapping)) or not isinstance(slots, Iterable):
+ raise ValueError("slots must be a list")
+ blueprint = AutomationBlueprint(
+ key=f"{plugin}:{key}",
+ title=_text("title", title),
+ description=_text("description", description),
+ category=_text("category", category),
+ schedule_template=_text("schedule_template", schedule_template),
+ prompt_template=_text("prompt_template", prompt_template),
+ slots=[_slot(s) for s in slots],
+ deliver_default=_text("deliver_default", deliver_default),
+ skills=_strings("skills", skills),
+ tags=_strings("tags", tags),
+ plugin=plugin,
+ )
+ _validate(blueprint)
+ return blueprint
+
+
+def plugin_blueprints() -> List[AutomationBlueprint]:
+ """Blueprints the active profile's enabled plugins registered (resolved per call)."""
+ try:
+ from hermes_cli.plugins import discover_plugins, get_plugin_manager
+
+ discover_plugins() # idempotent; servers that never import model_tools still see plugins
+ return get_plugin_manager().list_automation_blueprints()
+ except Exception:
+ logger.warning("plugin automation blueprints unavailable", exc_info=True)
+ return []
diff --git a/hermes_cli/blueprint_cmd.py b/hermes_cli/blueprint_cmd.py
index 778d801bae1..54d57eba87c 100644
--- a/hermes_cli/blueprint_cmd.py
+++ b/hermes_cli/blueprint_cmd.py
@@ -71,19 +71,25 @@ def match_blueprint(query: str) -> Tuple[Optional[Any], List[Any]]:
it's picked): exact key first, then case-insensitive prefix on key or title, then substring
anywhere in key/title/description, then a difflib fuzzy pass on keys.
"""
- from cron.blueprint_catalog import CATALOG, get_blueprint
+ from cron.blueprint_catalog import list_blueprints
q = (query or "").strip().lower()
if not q:
return None, []
- exact = get_blueprint(q)
+ catalog = list_blueprints()
+ by_key = {r.key.lower(): r for r in catalog}
+ exact = by_key.get(q)
if exact is not None:
return exact, []
+ # Plugin keys are ``<plugin>:<key>``: the bare ``<key>`` half is what people type.
+ def _keys(r):
+ return (r.key.lower(), r.key.lower().rpartition(":")[2])
+
passes = (
- lambda: [r for r in CATALOG if r.key.lower().startswith(q) or any(w.lower().startswith(q) for w in r.title.split())],
- lambda: [r for r in CATALOG if q in r.key.lower() or q in r.title.lower() or q in r.description.lower()],
- lambda: [get_blueprint(k) for k in difflib.get_close_matches(q, [r.key for r in CATALOG], n=3, cutoff=0.6)],
+ lambda: [r for r in catalog if any(k.startswith(q) for k in _keys(r)) or any(w.lower().startswith(q) for w in r.title.split())],
+ lambda: [r for r in catalog if q in r.key.lower() or q in r.title.lower() or q in r.description.lower()],
+ lambda: [by_key[k] for k in difflib.get_close_matches(q, list(by_key), n=3, cutoff=0.6)],
)
for candidates in passes:
picked = _pick(candidates())
@@ -142,10 +148,11 @@ def build_blueprint_seed(blueprint) -> str:
def _fmt_catalog() -> str:
- from cron.blueprint_catalog import CATALOG
+ from cron.blueprint_catalog import list_blueprints
lines = ["Automation Blueprints — `/blueprint <name>` and I'll ask you what I need:\n"]
- for r in CATALOG:
- lines.append(f" • {r.key} — {r.title}")
+ for r in list_blueprints():
+ source = f" (plugin: {r.plugin})" if r.plugin else ""
+ lines.append(f" • {r.key} — {r.title}{source}")
lines.append(f" {r.description}")
lines.append(
"\nTip: `/blueprint <name>` walks you through it. Power users can "
@@ -162,8 +169,8 @@ def _fmt_candidates(query: str, candidates: List[Any]) -> str:
def _fmt_no_match(query: str) -> str:
- from cron.blueprint_catalog import CATALOG
- close = difflib.get_close_matches((query or "").lower(), [r.key for r in CATALOG], n=3, cutoff=0.4)
+ from cron.blueprint_catalog import list_blueprints
+ close = difflib.get_close_matches((query or "").lower(), [r.key for r in list_blueprints()], n=3, cutoff=0.4)
msg = f"No automation blueprint matches '{query}'."
if close:
msg += " Did you mean: " + ", ".join(close) + "?"
diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.py
index a806686f860..50615143a47 100644
--- a/hermes_cli/plugins.py
+++ b/hermes_cli/plugins.py
@@ -1010,38 +1010,7 @@ class PluginContext:
self._manager._subscribe_event(self.plugin_id, event, callback)
logger.debug("Plugin %s subscribed to event: %s", self.manifest.name, event)
- @_serialized_replacement
- def register_skill(
- self, name: str, path: Path, description: str = "",
- frontmatter: Optional[Mapping[str, Any]] = None,
- ) -> PluginRegistration:
- """Register a read-only skill resolvable as ``'<plugin_name>:<name>'`` via ``skill_view()``
- and listed by ``skills_list``. Not copied into ``~/.hermes/skills/`` and not in the system
- prompt's ``<available_skills>``. Raises ``ValueError`` (``':'``/invalid chars) or
- ``FileNotFoundError``."""
- from agent.skill_utils import _NAMESPACE_RE
- if ":" in name:
- raise ValueError(f"Skill name '{name}' must not contain ':' (the namespace is derived from the "
- f"plugin name '{self.manifest.name}' automatically).")
- if not name or not _NAMESPACE_RE.match(name):
- raise ValueError(f"Invalid skill name '{name}'. Must match [a-zA-Z0-9_-]+.")
- # Plugin register() helpers commonly pass the SKILL.md location as str
- # (PluginManifest.path is stored as str); the registry and find_plugin_skill()
- # promise a Path downstream.
- path = Path(path)
- if not path.exists():
- raise FileNotFoundError(f"SKILL.md not found at {path}")
- namespace = self.manifest.skill_namespace or self.manifest.name
- qualified = f"{namespace}:{name}"
- if self.manifest.portable and qualified in self._manager._plugin_skills:
- raise ValueError(f"Plugin skill '{qualified}' is already registered")
- entry = {
- "path": path, "plugin": namespace, "plugin_key": self.plugin_id, "bare_name": name,
- "description": description, "frontmatter": dict(frontmatter or {}),
- }
- return self._register_entry("skill", qualified, self._manager._plugin_skills, entry,
- "Plugin %s registered skill: %s", qualified)
-
+ from hermes_cli.plugins_content import register_automation_blueprint, register_skill
# -- scoped provider registrars ------------------------------------------------------------------
# Every ``register_<category>_provider`` shares one body (:meth:`PluginContext._register_scoped_provider`):
@@ -1218,6 +1187,7 @@ class PluginManager(PluginLoaderMixin, PluginDispatchMixin, PluginLedgerMixin):
self._plugin_commands: Dict[str, dict] = {}
self._system_prompt_sections: Dict[str, PluginSystemPromptSection] = {}
self._plugin_skills: Dict[str, Dict[str, Any]] = {}
+ self._automation_blueprints: Dict[str, Any] = {} # "<plugin>:<key>" -> AutomationBlueprint
self._portable_mcp_servers: Dict[str, Dict[str, Any]] = {}
self._portable_mcp_server_plugins: Dict[str, str] = {}
self._aux_tasks: Dict[str, Dict[str, Any]] = {}
@@ -1591,6 +1561,10 @@ class PluginManager(PluginLoaderMixin, PluginDispatchMixin, PluginLedgerMixin):
} for qualified, entry in sorted(self._plugin_skills.items())
]
+ def list_automation_blueprints(self) -> List[Any]:
+ """Plugin-registered ``AutomationBlueprint``s, sorted by key."""
+ return [bp for _key, bp in sorted(self._automation_blueprints.items())]
+
def has_portable_mcp_servers(self) -> bool:
return bool(self._portable_mcp_servers)
diff --git a/hermes_cli/plugins_content.py b/hermes_cli/plugins_content.py
new file mode 100644
index 00000000000..404a9d92a09
--- /dev/null
+++ b/hermes_cli/plugins_content.py
@@ -0,0 +1,79 @@
+"""Content registrars on ``PluginContext``: plugin skills and Automation Blueprints.
+
+Bound into the class body (``from hermes_cli.plugins_content import ...``), so they are ordinary
+``ctx.register_*`` methods and get the same abandoned-load guard as every other registrar.
+"""
+
+from __future__ import annotations
+
+import logging
+from pathlib import Path
+from typing import Any, Iterable, Mapping, Optional
+
+from hermes_cli.plugins_ledger import PluginRegistration
+from hermes_cli.plugins_loader import _serialized_replacement
+
+# Same logger as the rest of the ctx surface, so plugin-load diagnostics stay in one place.
+logger = logging.getLogger("hermes_cli.plugins")
+
+__all__ = ["register_automation_blueprint", "register_skill"]
+
+
+@_serialized_replacement
+def register_skill(
+ self, name: str, path: Path, description: str = "",
+ frontmatter: Optional[Mapping[str, Any]] = None,
+) -> PluginRegistration:
+ """Register a read-only skill resolvable as ``'<plugin_name>:<name>'`` via ``skill_view()``
+ and listed by ``skills_list``. Not copied into ``~/.hermes/skills/`` and not in the system
+ prompt's ``<available_skills>``. Raises ``ValueError`` (``':'``/invalid chars) or
+ ``FileNotFoundError``."""
+ from agent.skill_utils import _NAMESPACE_RE
+ if ":" in name:
+ raise ValueError(f"Skill name '{name}' must not contain ':' (the namespace is derived from the "
+ f"plugin name '{self.manifest.name}' automatically).")
+ if not name or not _NAMESPACE_RE.match(name):
+ raise ValueError(f"Invalid skill name '{name}'. Must match [a-zA-Z0-9_-]+.")
+ # Plugin register() helpers commonly pass the SKILL.md location as str
+ # (PluginManifest.path is stored as str); the registry and find_plugin_skill()
+ # promise a Path downstream.
+ path = Path(path)
+ if not path.exists():
+ raise FileNotFoundError(f"SKILL.md not found at {path}")
+ namespace = self.manifest.skill_namespace or self.manifest.name
+ qualified = f"{namespace}:{name}"
+ if self.manifest.portable and qualified in self._manager._plugin_skills:
+ raise ValueError(f"Plugin skill '{qualified}' is already registered")
+ entry = {
+ "path": path, "plugin": namespace, "plugin_key": self.plugin_id, "bare_name": name,
+ "description": description, "frontmatter": dict(frontmatter or {}),
+ }
+ return self._register_entry("skill", qualified, self._manager._plugin_skills, entry,
+ "Plugin %s registered skill: %s", qualified)
+
+def register_automation_blueprint(
+ self, key: str, *, title: str, description: str, schedule_template: str,
+ prompt_template: str, category: str = "general", slots: Iterable[Any] = (),
+ deliver_default: str = "origin", skills: Iterable[str] = (), tags: Iterable[str] = (),
+) -> Optional[PluginRegistration]:
+ """Add an Automation Blueprint to this profile's catalog as ``'<plugin_name>:<key>'``
+ (``/blueprint``, the dashboard/Desktop gallery). Fields mirror
+ :class:`cron.blueprint_catalog.AutomationBlueprint`; ``slots`` are ``BlueprintSlot`` field
+ mappings. Malformed input or a duplicate key logs a warning and returns ``None``."""
+ from cron.blueprint_plugins import build_plugin_blueprint
+ try:
+ blueprint = build_plugin_blueprint(
+ self.manifest.name, key, title=title, description=description,
+ schedule_template=schedule_template, prompt_template=prompt_template, category=category,
+ slots=slots, deliver_default=deliver_default, skills=skills, tags=tags,
+ )
+ except ValueError as exc:
+ logger.warning("Plugin '%s' automation blueprint %r rejected: %s", self.manifest.name, key, exc)
+ return None
+ if blueprint.key in self._manager._automation_blueprints:
+ logger.warning("Plugin '%s' automation blueprint %r is already registered",
+ self.manifest.name, blueprint.key)
+ return None
+ return self._register_entry("automation_blueprint", blueprint.key,
+ self._manager._automation_blueprints, blueprint,
+ "Plugin %s registered automation blueprint: %s", blueprint.key)
diff --git a/hermes_cli/plugins_ledger.py b/hermes_cli/plugins_ledger.py
index 9577f0aec6c..d616de63c06 100644
--- a/hermes_cli/plugins_ledger.py
+++ b/hermes_cli/plugins_ledger.py
@@ -288,7 +288,7 @@ class PluginLedgerMixin:
for container in (
self._ownership_ledger, self._plugins, self._hooks, self._middleware,
self._plugin_tool_names, self._plugin_platform_names, self._cli_commands,
- self._plugin_commands, self._plugin_skills, self._portable_mcp_servers,
+ self._plugin_commands, self._plugin_skills, self._automation_blueprints, self._portable_mcp_servers,
self._portable_mcp_server_plugins, self._aux_tasks, self._system_prompt_sections, self._approval_transports,
self._slack_action_handlers, self._predeclared_modules, self._predeclared_tools,
self._platform_handler_factories,
diff --git a/hermes_cli/web_routers/cron.py b/hermes_cli/web_routers/cron.py
index ebfaa5e5ff9..c66ad68d806 100644
--- a/hermes_cli/web_routers/cron.py
+++ b/hermes_cli/web_routers/cron.py
@@ -827,34 +827,39 @@ async def cron_fire_webhook(request: Request):
return JSONResponse(gateway_body, status_code=status_code, headers=headers)
[email protected]("/api/cron/blueprints")
-async def list_cron_blueprints(profile: Optional[str] = None):
- """Blueprint catalog as form schemas; the ``deliver`` slot's options are
- rewritten from the actually configured gateway platforms."""
- try:
- from cron.blueprint_catalog import CATALOG, blueprint_catalog_entry
-
+def _blueprint_catalog_sync(profile: Optional[str]) -> list:
+ """Built-in + ``profile``'s plugin blueprints, with the ``deliver`` slot's options rewritten
+ from that profile's configured gateway platforms. Plugin discovery can import plugin code, so
+ this runs off the event loop, inside the profile scope that picks the plugin manager."""
+ from cron.blueprint_catalog import blueprint_catalog_entry, list_blueprints
+
+ with _config_profile_scope(profile): # an unknown ?profile= raises the scope's 404
+ catalog = list_blueprints()
deliver_options = None
try:
from cron.scheduler_delivery import cron_delivery_targets
- with _config_profile_scope(profile):
- platforms = [t["id"] for t in cron_delivery_targets() if t.get("id")]
+ platforms = [t["id"] for t in cron_delivery_targets() if t.get("id")]
deliver_options = ["origin", "local", *platforms]
- except HTTPException:
- raise # an unknown ?profile= is the scope's 404, not a reason for static options
- except Exception:
+ except Exception: # health: allow BLE001 -- gateway targets are optional; static options are the fallback
_log.debug("cron_delivery_targets unavailable; using static deliver options", exc_info=True)
- entries = []
- for r in CATALOG:
- entry = blueprint_catalog_entry(r)
- if deliver_options:
- for f in entry.get("fields", []):
- if f.get("name") == "deliver":
- f["options"] = deliver_options
- entries.append(entry)
- return {"blueprints": entries}
+ entries = []
+ for r in catalog:
+ entry = blueprint_catalog_entry(r)
+ if deliver_options:
+ for f in entry.get("fields", []):
+ if f.get("name") == "deliver":
+ f["options"] = deliver_options
+ entries.append(entry)
+ return entries
+
+
[email protected]("/api/cron/blueprints")
+async def list_cron_blueprints(profile: Optional[str] = None):
+ """Blueprint catalog (built-ins + the profile's plugin blueprints) as form schemas."""
+ try:
+ return {"blueprints": await _run_cron_dashboard_io(_blueprint_catalog_sync, profile)}
except HTTPException:
raise
except Exception as e:
@@ -862,13 +867,20 @@ async def list_cron_blueprints(profile: Optional[str] = None):
raise HTTPException(status_code=500, detail=str(e))
+def _blueprint_for_profile(key: str, profile: Optional[str]):
+ from cron.blueprint_catalog import get_blueprint
+
+ with _config_profile_scope(profile):
+ return get_blueprint(key)
+
+
@router.post("/api/cron/blueprints/instantiate")
async def instantiate_blueprint(body: AutomationBlueprintInstantiate, profile: str = "default"):
"""Fill a blueprint's slots and create the cron job (form-submit path)."""
try:
- from cron.blueprint_catalog import BlueprintFillError, fill_blueprint, get_blueprint
+ from cron.blueprint_catalog import BlueprintFillError, fill_blueprint
- blueprint = get_blueprint(body.blueprint)
+ blueprint = await _run_cron_dashboard_io(_blueprint_for_profile, body.blueprint, profile)
if blueprint is None:
raise HTTPException(status_code=404, detail=f"Unknown blueprint: {body.blueprint}")
try:
diff --git a/tests/plugins/test_plugin_automation_blueprints.py b/tests/plugins/test_plugin_automation_blueprints.py
new file mode 100644
index 00000000000..32756a53fa6
--- /dev/null
+++ b/tests/plugins/test_plugin_automation_blueprints.py
@@ -0,0 +1,202 @@
+"""Plugins register Automation Blueprints via ``ctx.register_automation_blueprint``.
+
+Contracts: a registered blueprint is listed next to the built-ins (``/blueprint`` and
+``/api/cron/blueprints``) under a ``<plugin>:<key>`` key with a plugin source, instantiates
+into a normal job, can never shadow a built-in, and is visible only in the profile whose
+plugin registered it.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import textwrap
+from pathlib import Path
+
+import pytest
+
+import hermes_cli.web_models as _web_models
+import hermes_cli.web_routers.cron as _rt_cron
+
+_STANDUP = textwrap.dedent(
+ """
+ def register(ctx):
+ ctx.register_automation_blueprint(
+ "standup",
+ title="Team standup digest",
+ description="Weekday summary of what changed in a repo.",
+ category="work",
+ schedule_template="{minute} {hour} * * 1-5",
+ prompt_template="Summarize yesterday's commits for {repo}.",
+ slots=[
+ {"name": "repo", "type": "text", "label": "Which repo?", "default": "acme/app"},
+ {"name": "time", "type": "time", "label": "What time?", "default": "09:15"},
+ {"name": "deliver", "type": "enum", "label": "Where?", "default": "origin",
+ "options": ["origin", "local"], "strict": False},
+ ],
+ tags=["work"],
+ )
+ """
+)
+
+
+def _write_plugin(home: Path, name: str, body: str, *, enable: bool = True) -> None:
+ plugin_dir = home / "plugins" / name
+ plugin_dir.mkdir(parents=True, exist_ok=True)
+ (plugin_dir / "plugin.yaml").write_text(f"name: {name}\nversion: 0.1.0\n")
+ (plugin_dir / "__init__.py").write_text(body)
+ # JSON is valid YAML; avoids a yaml import in the test module.
+ plugins = {"enabled": [name]} if enable else {"enabled": [], "disabled": [name]}
+ (home / "config.yaml").write_text(json.dumps({"model": "test-model", "plugins": plugins}))
+
+
+def homes(tmp_path, monkeypatch):
+ """Default profile home (active) plus a second profile home, both isolated."""
+ from hermes_cli import profiles
+
+ default_home = tmp_path / ".hermes"
+ profiles_root = default_home / "profiles"
+ other_home = profiles_root / "other"
+ for home in (default_home, other_home):
+ (home / "cron").mkdir(parents=True, exist_ok=True)
+ (home / "config.yaml").write_text("model: test-model\n")
+ monkeypatch.setenv("HERMES_HOME", str(default_home))
+ monkeypatch.setattr(profiles, "_get_default_hermes_home", lambda: default_home)
+ monkeypatch.setattr(profiles, "_get_profiles_root", lambda: profiles_root)
+ return {"default": default_home, "other": other_home}
+
+
+def _plugin_keys(entries):
+ return {e["key"]: e for e in entries if e.get("source") == "plugin"}
+
+
+def test_plugin_blueprint_is_listed_by_slash_command_and_matches(homes):
+ from hermes_cli.blueprint_cmd import handle_blueprint_command, match_blueprint
+
+ _write_plugin(homes["default"], "teamtools", _STANDUP)
+
+ catalog = handle_blueprint_command("")
+ assert "teamtools:standup" in catalog.text
+ assert "Team standup digest" in catalog.text
+ assert match_blueprint("teamtools:standup")[0].key == "teamtools:standup"
+ assert match_blueprint("standup")[0].key == "teamtools:standup"
+
+
+async def test_plugin_blueprint_in_api_catalog_and_instantiates_real_job(homes):
+ from cron.jobs import load_jobs
+
+ _write_plugin(homes["default"], "teamtools", _STANDUP)
+
+ listed = await _rt_cron.list_cron_blueprints(profile="default")
+ entry = _plugin_keys(listed["blueprints"])["teamtools:standup"]
+ assert entry["plugin"] == "teamtools"
+ assert entry["title"] == "Team standup digest"
+ assert [f["name"] for f in entry["fields"]] == ["repo", "time", "deliver"]
+ builtin = next(e for e in listed["blueprints"] if e["key"] == "morning-brief")
+ assert builtin["source"] == "builtin" and builtin["plugin"] is None
+
+ created = await _rt_cron.instantiate_blueprint(
+ _web_models.AutomationBlueprintInstantiate(
+ blueprint="teamtools:standup",
+ values={"repo": "acme/widgets", "time": "10:05", "deliver": "local"},
+ ),
+ profile="default",
+ )
+ assert created["name"] == "Team standup digest"
+ assert created["profile"] == "default"
+ [job] = [j for j in load_jobs() if j["id"] == created["id"]]
+ assert job["prompt"] == "Summarize yesterday's commits for acme/widgets."
+ assert job["schedule"]["expr"] == "5 10 * * 1-5"
+ assert job["deliver"] == "local"
+
+
+async def test_plugin_blueprints_are_profile_scoped(homes):
+ _write_plugin(homes["default"], "teamtools", _STANDUP)
+
+ # Interleave A -> B -> A: no cached plugin catalog may leak across profiles.
+ a1 = _plugin_keys((await _rt_cron.list_cron_blueprints(profile="default"))["blueprints"])
+ b = _plugin_keys((await _rt_cron.list_cron_blueprints(profile="other"))["blueprints"])
+ a2 = _plugin_keys((await _rt_cron.list_cron_blueprints(profile="default"))["blueprints"])
+ assert set(a1) == set(a2) == {"teamtools:standup"}
+ assert b == {}
+
+ with pytest.raises(_rt_cron.HTTPException) as exc:
+ await _rt_cron.instantiate_blueprint(
+ _web_models.AutomationBlueprintInstantiate(blueprint="teamtools:standup", values={}),
+ profile="other",
+ )
+ assert exc.value.status_code == 404
+
+
+def test_plugin_cannot_shadow_builtin_and_bad_keys_are_rejected(homes, caplog):
+ from cron.blueprint_catalog import get_blueprint, list_blueprints
+
+ body = textwrap.dedent(
+ """
+ def register(ctx):
+ common = dict(title="Mine", description="d", schedule_template="0 9 * * *",
+ prompt_template="hi")
+ ctx.register_automation_blueprint("morning-brief", **common)
+ ctx.register_automation_blueprint("morning-brief", **common) # duplicate
+ ctx.register_automation_blueprint("other:spoof", **common) # namespace spoof
+ """
+ )
+ _write_plugin(homes["default"], "teamtools", body)
+
+ with caplog.at_level(logging.WARNING, logger="hermes_cli.plugins"):
+ keys = [bp.key for bp in list_blueprints()]
+ assert keys.count("morning-brief") == 1
+ builtin, mine = get_blueprint("morning-brief"), get_blueprint("teamtools:morning-brief")
+ assert builtin is not None and builtin.plugin == "" # still the built-in
+ assert mine is not None and mine.title == "Mine"
+ assert keys.count("teamtools:morning-brief") == 1
+ assert not any(k.endswith("spoof") for k in keys)
+ assert "already registered" in caplog.text
+ assert "other:spoof" in caplog.text
+
+
+ "fields, reason",
+ [
+ ({"prompt_template": "hello {nobody}"}, "nobody"),
+ ({"slots": [{"name": "x", "type": "colour", "label": "X"}]}, "type"),
+ ({"schedule_template": "not a schedule"}, "schedule"),
+ ({"schedule_template": "{minute} {hour} * * *"}, "time"),
+ ({"title": ""}, "title"),
+ ],
+)
+def test_malformed_plugin_blueprint_is_warned_and_ignored(homes, caplog, fields, reason):
+ from cron.blueprint_catalog import list_blueprints
+
+ base = dict(title="T", description="d", schedule_template="0 9 * * *", prompt_template="hi")
+ base.update(fields)
+ _write_plugin(homes["default"], "teamtools", f"def register(ctx):\n ctx.register_automation_blueprint('bad', **{base!r})\n")
+
+ with caplog.at_level(logging.WARNING, logger="hermes_cli.plugins"):
+ keys = [bp.key for bp in list_blueprints()]
+ assert "teamtools:bad" not in keys
+ assert "teamtools" in caplog.text and reason in caplog.text
+
+
+async def test_job_from_plugin_blueprint_survives_plugin_disable(homes):
+ from cron.jobs import load_jobs
+ from hermes_cli.plugins import _reset_plugin_managers_for_tests
+
+ _write_plugin(homes["default"], "teamtools", _STANDUP)
+ created = await _rt_cron.instantiate_blueprint(
+ _web_models.AutomationBlueprintInstantiate(blueprint="teamtools:standup", values={}),
+ profile="default",
+ )
+
+ _write_plugin(homes["default"], "teamtools", _STANDUP, enable=False)
+ _reset_plugin_managers_for_tests()
+
+ listed = await _rt_cron.list_cron_blueprints(profile="default")
+ assert _plugin_keys(listed["blueprints"]) == {}
+ [job] = [j for j in load_jobs() if j["id"] == created["id"]]
+ assert job["prompt"] == "Summarize yesterday's commits for acme/app."
+ assert job["schedule"]["expr"] == "15 9 * * 1-5"
diff --git a/web/src/components/AutomationBlueprints.tsx b/web/src/components/AutomationBlueprints.tsx
index 6d5a6a44ca2..76eeccad294 100644
--- a/web/src/components/AutomationBlueprints.tsx
+++ b/web/src/components/AutomationBlueprints.tsx
@@ -10,7 +10,7 @@ import { Badge } from "@nous-research/ui/ui/components/badge";
import { useToast } from "@nous-research/ui/hooks/use-toast";
import { Toast } from "@nous-research/ui/ui/components/toast";
import { api } from "@/lib/api";
-import type { AutomationBlueprint, AutomationBlueprintField } from "@/lib/api";
+import type { AutomationBlueprint, AutomationBlueprintField } from "@/lib/automation-blueprints";
import { cn, themedBody } from "@/lib/utils";
import { errorMessage } from "@/lib/api-error";
@@ -113,6 +113,9 @@ function BlueprintCard({
</div>
<p className="mt-1 text-sm opacity-70">{blueprint.description}</p>
<div className="mt-2 flex flex-wrap gap-1">
+ {blueprint.plugin ? (
+ <Badge tone="outline">plugin: {blueprint.plugin}</Badge>
+ ) : null}
{blueprint.tags.map((t) => (
<Badge key={t} tone="secondary">
{t}
diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts
index 380ddd74633..e0b7e265491 100644
--- a/web/src/lib/api.ts
+++ b/web/src/lib/api.ts
@@ -32,6 +32,7 @@ import {
clearDashboardTokenReloadAttempt,
} from "@/lib/dashboard-auth-reload";
import { apiErrorFromNetworkFailure, apiErrorFromResponse } from "@/lib/api-error";
+import type { AutomationBlueprint } from "@/lib/automation-blueprints";
// Ephemeral session token for protected endpoints.
// Injected into index.html by the server — never fetched via API.
@@ -2477,29 +2478,6 @@ export interface CronDeliveryTarget {
home_env_var: string | null;
}
-export interface AutomationBlueprintField {
- name: string;
- type: "time" | "enum" | "text" | "weekdays";
- label: string;
- default: string | null;
- options: string[];
- optional: boolean;
- /** When false, options are suggestions — any value is accepted. */
- strict?: boolean;
- help: string;
-}
-
-export interface AutomationBlueprint {
- key: string;
- title: string;
- description: string;
- category: string;
- tags: string[];
- fields: AutomationBlueprintField[];
- command: string;
- appUrl: string;
-}
-
export interface SkillInfo {
name: string;
description: string;
diff --git a/web/src/lib/automation-blueprints.ts b/web/src/lib/automation-blueprints.ts
new file mode 100644
index 00000000000..53da4514cf7
--- /dev/null
+++ b/web/src/lib/automation-blueprints.ts
@@ -0,0 +1,28 @@
+// Shapes of /api/cron/blueprints catalog entries (cron/blueprint_catalog.py blueprint_catalog_entry).
+
+export interface AutomationBlueprintField {
+ name: string
+ type: 'time' | 'enum' | 'text' | 'weekdays'
+ label: string
+ default: string | null
+ options: string[]
+ optional: boolean
+ /** When false, options are suggestions — any value is accepted. */
+ strict?: boolean
+ help: string
+}
+
+export interface AutomationBlueprint {
+ key: string
+ title: string
+ description: string
+ category: string
+ tags: string[]
+ fields: AutomationBlueprintField[]
+ command: string
+ appUrl: string
+ /** Absent on backends that predate plugin blueprints. */
+ source?: 'builtin' | 'plugin'
+ /** Registering plugin's name when source is "plugin" (key is `<plugin>:<key>`). */
+ plugin?: string | null
+}
diff --git a/website/docs/developer-guide/plugins/index.md b/website/docs/developer-guide/plugins/index.md
index 57794fd5e9d..d85ff3e3fcd 100644
--- a/website/docs/developer-guide/plugins/index.md
+++ b/website/docs/developer-guide/plugins/index.md
@@ -1502,6 +1502,39 @@ def register(ctx):
ctx.register_hook("pre_tool_call", guard)
```
+### Add Automation Blueprints
+
+`ctx.register_automation_blueprint(key, *, title, description, schedule_template, prompt_template, category="general", slots=(), deliver_default="origin", skills=(), tags=())` adds a fill-in-the-blanks automation to the [Automation Blueprints catalog](../../reference/automation-blueprints-catalog.mdx). It appears next to the built-ins in `/blueprint` (CLI, TUI, messengers), the dashboard's Blueprints tab, and the Desktop Cron page, labelled with your plugin's name. The arguments are the fields of the built-in `AutomationBlueprint` (`cron/blueprint_catalog.py`); each slot is a dict of `BlueprintSlot` fields.
+
+```python
+def register(ctx):
+ ctx.register_automation_blueprint(
+ "standup",
+ title="Team standup digest",
+ description="Every weekday, summarize what changed in a repo since yesterday.",
+ category="work",
+ schedule_template="{minute} {hour} * * 1-5",
+ prompt_template="Summarize yesterday's commits and open PRs for {repo} as a short standup digest.",
+ slots=[
+ {"name": "repo", "type": "text", "label": "Which repo?", "default": "acme/app"},
+ {"name": "time", "type": "time", "label": "What time?", "default": "09:15"},
+ {"name": "deliver", "type": "enum", "label": "Where to deliver?", "default": "origin",
+ "options": ["origin", "local"], "strict": False},
+ ],
+ tags=["work", "daily"],
+ )
+```
+
+Users then run `/blueprint teamtools:standup` (or just `/blueprint standup`) or pick it in the Desktop/dashboard form.
+
+- **Keys are namespaced.** The catalog key is `<plugin>:<key>` (`teamtools:standup`), so a plugin can never replace a built-in or another plugin's blueprint. Pass the bare key; a key containing `:` is rejected.
+- **Slots and templates.** Slot `type` is `time` (`HH:MM`), `enum`, `weekdays`, or `text`. `prompt_template` may use any slot as `{name}`. `schedule_template` may use slot names plus `{minute}`/`{hour}` (from a slot named `time`) and `{dow}` (from a `recurrence`/`day` slot, else `*`). A slot named `deliver` gets the profile's real delivery targets in the Desktop and dashboard forms.
+- **Validated at registration.** An unknown placeholder, bad slot type, duplicate key, or schedule that does not parse logs a warning and skips that blueprint; the rest of your plugin still loads. When every slot has a default, Hermes fills the blueprint once at load, so a broken template fails then instead of on the user's first *Schedule it*.
+- **Per profile.** Plugins load per profile, so the blueprint is listed only in profiles where your plugin is enabled.
+- **Jobs outlive the plugin.** Scheduling a blueprint creates an ordinary cron job with the prompt and schedule already filled in. Disabling or uninstalling the plugin removes the blueprint from the catalog but leaves those jobs running. If a job's `skills` name a skill your plugin bundles, the job skips that skill (and logs it) while the plugin is disabled.
+
+This needs no manifest capability. It also works under plugin host isolation, because slots are plain dicts.
+
### Handle Slack Block Kit button clicks
Plugins that post Block Kit messages with interactive elements (buttons, overflow menus, datepickers, etc.) can register the click handlers directly with the Slack adapter — no monkey-patching of `slack_bolt.AsyncApp` required.
diff --git a/website/docs/reference/automation-blueprints-catalog.mdx b/website/docs/reference/automation-blueprints-catalog.mdx
index 820f5d87199..89a880ed874 100644
--- a/website/docs/reference/automation-blueprints-catalog.mdx
+++ b/website/docs/reference/automation-blueprints-catalog.mdx
@@ -28,9 +28,24 @@ is created. Manage created jobs anytime with `/cron`.
<AutomationBlueprintsCatalog />
+## Blueprints from plugins
+
+Plugins can add their own blueprints. They show up in the same catalog as the
+built-ins: in `/blueprint`, the dashboard's Blueprints tab, and the desktop Cron
+page, labelled with the plugin's name. Their keys are prefixed with the plugin
+name (`/blueprint teamtools:standup`), so a plugin can never replace a built-in.
+Plugins load per profile, so a plugin blueprint is listed only in profiles where
+that plugin is enabled.
+
+A job you create from a plugin blueprint is an ordinary cron job. Disabling the
+plugin removes the blueprint from the catalog, but jobs you already created keep
+running.
+
## Writing your own
A blueprint is just a skill with a `metadata.hermes.blueprint` block in its
`SKILL.md` frontmatter. See
[Creating Skills → Automation Blueprints](../developer-guide/creating-skills.md) for the
-slot schema and how to publish one.
+slot schema and how to publish one. Plugin authors can register one directly
+with `ctx.register_automation_blueprint()`; see
+[Build a Plugin → Add Automation Blueprints](../developer-guide/plugins/index.md#add-automation-blueprints).