blueprint_catalog.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. """Automation Blueprints — one slot-schema definition per automation that every surface renders
  2. natively: dashboard form (``blueprint_form_schema``), pre-filled ``/blueprint`` slash command
  3. (``blueprint_slash_command``), agent seed prompt, docs deep-link. ``fill_blueprint`` validates
  4. values into ``cron.jobs.create_job`` kwargs — there is no second job engine. Users never type raw
  5. cron: ``schedule_template`` fixes the recurrence; only human parts (time, weekdays) are slots.
  6. """
  7. from __future__ import annotations
  8. import re
  9. from dataclasses import dataclass, field
  10. from typing import Any, Dict, List, Optional
  11. __all__ = [
  12. "CATALOG",
  13. "WEEKDAY_PRESETS",
  14. "AutomationBlueprint",
  15. "BlueprintFillError",
  16. "BlueprintSlot",
  17. "blueprint_catalog_entry",
  18. "blueprint_deeplink",
  19. "blueprint_form_schema",
  20. "blueprint_slash_command",
  21. "fill_blueprint",
  22. "get_blueprint",
  23. "list_blueprints",
  24. ]
  25. class BlueprintFillError(ValueError):
  26. """Raised when supplied slot values fail validation."""
  27. # Slot types the renderers understand.
  28. _SLOT_TYPES = frozenset({"time", "enum", "text", "weekdays"})
  29. # Named weekday recurrences -> cron day-of-week field.
  30. WEEKDAY_PRESETS: dict[str, str] = {
  31. "everyday": "*",
  32. "weekdays": "1-5",
  33. "weekends": "0,6",
  34. }
  35. @dataclass(frozen=True)
  36. class BlueprintSlot:
  37. """A single fillable field on a blueprint."""
  38. name: str
  39. type: str
  40. label: str
  41. default: Any = None
  42. options: tuple = () # for type="enum": allowed values
  43. optional: bool = False
  44. help: str = ""
  45. # When False, ``options`` are suggestions rather than a closed set — any value is accepted (e.g.
  46. # the deliver slot, where the real set of valid platforms depends on the user's configured
  47. # gateways and is validated downstream by the cron scheduler).
  48. strict: bool = True
  49. def __post_init__(self) -> None:
  50. if self.type not in _SLOT_TYPES:
  51. raise ValueError(f"unknown slot type {self.type!r} (slot {self.name})")
  52. @dataclass(frozen=True)
  53. class AutomationBlueprint:
  54. """A parameterized automation blueprint."""
  55. key: str
  56. title: str
  57. description: str
  58. category: str
  59. # Cron expression with ``{slot}`` placeholders, e.g. "{minute} {hour} * * {dow}".
  60. # Placeholders are filled from resolved slot values (time -> minute/hour,
  61. # weekdays -> dow). A literal cron string with no placeholders = fixed schedule.
  62. schedule_template: str
  63. # Seed instruction for the agent / the cron job prompt; may contain {slot}s.
  64. prompt_template: str
  65. slots: list[BlueprintSlot] = field(default_factory=list)
  66. deliver_default: str = "origin"
  67. skills: tuple = () # skills the job loads before running
  68. tags: tuple = ()
  69. # Registering plugin for a ``ctx.register_automation_blueprint`` entry (key ``<plugin>:<key>``);
  70. # empty for the in-repo catalog.
  71. plugin: str = ""
  72. # ---------------------------------------------------------------------------
  73. # Curated in-repo catalog
  74. # ---------------------------------------------------------------------------
  75. _TIME = lambda default="08:00": BlueprintSlot(
  76. name="time", type="time", label="What time?", default=default,
  77. help="24h local time, e.g. 08:00",
  78. )
  79. _DELIVER = BlueprintSlot(
  80. name="deliver", type="enum", label="Where to deliver?",
  81. default="origin", options=("origin", "local", "telegram", "discord", "email"),
  82. optional=False, strict=False,
  83. help="origin = the chat you set this up from (or your configured home "
  84. "channel when created from the dashboard); local = save only, no message; "
  85. "or any connected platform name",
  86. )
  87. CATALOG: list[AutomationBlueprint] = [
  88. AutomationBlueprint(
  89. key="morning-brief",
  90. title="Morning briefing",
  91. description="A short daily briefing: today's calendar, weather, and "
  92. "anything urgent waiting on you.",
  93. category="daily",
  94. schedule_template="{minute} {hour} * * *",
  95. prompt_template=(
  96. "Produce a concise morning briefing for the user: today's calendar "
  97. "events, the local weather, and any urgent items. When Gmail/Google "
  98. "Calendar are connected, follow the google-workspace skill's "
  99. "references/daily-brief.md procedure (exact day window, conflict "
  100. "detection, meeting prep, mail-to-meeting links). Keep it short and "
  101. "scannable. If no data sources are connected, give a brief "
  102. "good-morning with the date and offer to connect calendar/email."
  103. ),
  104. slots=[_TIME("08:00"), _DELIVER],
  105. skills=("google-workspace",),
  106. tags=("daily", "briefing"),
  107. ),
  108. AutomationBlueprint(
  109. key="important-mail",
  110. title="Important-mail monitor",
  111. description="Check your inbox periodically and ping you ONLY about mail "
  112. "that actually needs attention.",
  113. category="email",
  114. schedule_template="*/{interval_min} * * * *",
  115. prompt_template=(
  116. "Check the user's inbox for new messages since the last run. Surface "
  117. "ONLY mail matching: {criteria}. Score candidates with the urgency "
  118. "classifier and deliver only what clears the bar; if nothing does, "
  119. "respond with [SILENT]. Requires a connected mail source; if none is "
  120. "configured, explain how to connect one and stop."
  121. ),
  122. slots=[
  123. BlueprintSlot(
  124. name="interval_min", type="enum", label="How often?",
  125. default="30", options=("15", "30", "60"),
  126. help="minutes between checks",
  127. ),
  128. BlueprintSlot(
  129. name="criteria", type="text",
  130. label="Only notify me if the mail…",
  131. default="needs a reply today, is from my manager or family, "
  132. "or mentions a deadline",
  133. ),
  134. _DELIVER,
  135. ],
  136. skills=("email-inbox-triage",),
  137. tags=("email", "monitor"),
  138. ),
  139. AutomationBlueprint(
  140. key="weekly-review",
  141. title="Weekly review",
  142. description="A weekly recap: what got done, what's still open, and "
  143. "what's coming up.",
  144. category="weekly",
  145. schedule_template="{minute} {hour} * * {dow}",
  146. prompt_template=(
  147. "Run the weekly-review-planning skill's procedure for the user: "
  148. "review the completed week and coming 1-2 weeks across connected "
  149. "calendar, tasks, notes, and email; surface commitments, stalled "
  150. "projects, and waiting items; build a capacity-aware plan for next "
  151. "week. Recommendations and drafts only — no mutations without "
  152. "approval. Keep the output in the skill's seven-section shape."
  153. ),
  154. slots=[
  155. _TIME("18:00"),
  156. BlueprintSlot(
  157. name="day", type="enum", label="Which day?",
  158. default="sunday",
  159. options=("sunday", "monday", "friday", "saturday"),
  160. ),
  161. _DELIVER,
  162. ],
  163. skills=("weekly-review-planning",),
  164. tags=("weekly", "review"),
  165. ),
  166. AutomationBlueprint(
  167. key="workday-start",
  168. title="Workday start reminder",
  169. description="A weekday nudge with your agenda and top priorities.",
  170. category="daily",
  171. schedule_template="{minute} {hour} * * 1-5",
  172. prompt_template=(
  173. "Give the user a brief weekday start-of-day nudge: today's calendar "
  174. "and the 1-3 highest-priority things to focus on, inferred from "
  175. "recent context and any task tools. Encouraging, short, one message."
  176. ),
  177. slots=[_TIME("09:00"), _DELIVER],
  178. tags=("daily", "focus"),
  179. ),
  180. AutomationBlueprint(
  181. key="custom-reminder",
  182. title="Custom reminder",
  183. description="A recurring reminder in your own words, on your schedule.",
  184. category="general",
  185. schedule_template="{minute} {hour} * * {dow}",
  186. prompt_template="Remind the user: {what}",
  187. slots=[
  188. BlueprintSlot(name="what", type="text", label="Remind me to…",
  189. default="take a break and stretch"),
  190. _TIME("14:00"),
  191. BlueprintSlot(
  192. name="recurrence", type="weekdays", label="Repeat on",
  193. default="everyday",
  194. options=tuple(WEEKDAY_PRESETS.keys()),
  195. ),
  196. _DELIVER,
  197. ],
  198. tags=("reminder",),
  199. ),
  200. AutomationBlueprint(
  201. key="evening-winddown",
  202. title="Evening wind-down",
  203. description="An end-of-day check-in: tomorrow's calendar at a glance "
  204. "and anything you should prep tonight.",
  205. category="daily",
  206. schedule_template="{minute} {hour} * * *",
  207. prompt_template=(
  208. "Give the user a short evening wind-down: tomorrow's calendar, any "
  209. "early commitments to prep for, and one gentle nudge to wrap up "
  210. "loose ends from today. Keep it calm and brief — one message. If no "
  211. "calendar is connected, just offer a friendly sign-off and the "
  212. "weather for tomorrow."
  213. ),
  214. slots=[_TIME("21:00"), _DELIVER],
  215. tags=("daily", "evening"),
  216. ),
  217. AutomationBlueprint(
  218. key="news-digest",
  219. title="Topic news digest",
  220. description="A recurring digest on a topic you care about — deduped "
  221. "against what was already sent, so only genuinely new items land.",
  222. category="general",
  223. schedule_template="{minute} {hour} * * {dow}",
  224. prompt_template=(
  225. "Search the web for new and noteworthy items about: {topic}. "
  226. "Dedupe against what you sent in previous runs — only include "
  227. "genuinely new developments. Deliver a tight digest of at most "
  228. "{count} bullets, each one line with a link. If nothing new since "
  229. "last run, respond with [SILENT]."
  230. ),
  231. slots=[
  232. BlueprintSlot(
  233. name="topic", type="text", label="What topic?",
  234. default="AI and technology",
  235. help="a subject, product, person, or search phrase",
  236. ),
  237. _TIME("18:00"),
  238. BlueprintSlot(
  239. name="recurrence", type="weekdays", label="Repeat on",
  240. default="weekdays",
  241. options=tuple(WEEKDAY_PRESETS.keys()),
  242. ),
  243. BlueprintSlot(
  244. name="count", type="enum", label="How many bullets?",
  245. default="5", options=("3", "5", "8"),
  246. ),
  247. _DELIVER,
  248. ],
  249. tags=("digest", "research"),
  250. ),
  251. AutomationBlueprint(
  252. key="bill-renewal-watch",
  253. title="Bills & renewals reminder",
  254. description="A heads-up before a recurring payment, subscription "
  255. "renewal, or due date — so nothing auto-charges by surprise.",
  256. category="general",
  257. schedule_template="{minute} {hour} * * {dow}",
  258. prompt_template=(
  259. "Remind the user about an upcoming payment or renewal: {what}. "
  260. "Phrase it as an actionable heads-up (e.g. 'review or cancel before "
  261. "it renews'), not just a notification. One short message."
  262. ),
  263. slots=[
  264. BlueprintSlot(
  265. name="what", type="text", label="What's due?",
  266. default="my streaming subscription renews soon",
  267. ),
  268. _TIME("10:00"),
  269. BlueprintSlot(
  270. name="recurrence", type="weekdays", label="Repeat on",
  271. default="everyday",
  272. options=tuple(WEEKDAY_PRESETS.keys()),
  273. ),
  274. _DELIVER,
  275. ],
  276. tags=("reminder", "finance"),
  277. ),
  278. AutomationBlueprint(
  279. key="price-watch",
  280. title="Price & availability watch",
  281. description="Watch an exact product, flight, hotel, or listing and "
  282. "alert when your price or availability condition is met.",
  283. category="general",
  284. schedule_template="0 */{interval_h} * * *",
  285. prompt_template=(
  286. "Load the product-price-monitor skill and run the tick for this "
  287. "watch: {item}. Alert condition: {condition}. Compare the "
  288. "normalized all-in price/availability against stored state, "
  289. "suppress duplicate alerts, and never overwrite last-known-good "
  290. "state with a failed fetch. If no condition is met, respond with "
  291. "[SILENT]. On the first run, execute the skill's setup phase "
  292. "first: pin the exact item, verify one live fetch, and write the "
  293. "watch contract state file."
  294. ),
  295. slots=[
  296. BlueprintSlot(
  297. name="item", type="text", label="What exactly to watch?",
  298. default="a product URL or exact flight/hotel/listing description",
  299. help="URL or precise description — variant, dates, seller",
  300. ),
  301. BlueprintSlot(
  302. name="condition", type="text", label="Alert me when…",
  303. default="the all-in price drops below my target",
  304. help="threshold price (state the currency), availability, or terms change",
  305. ),
  306. BlueprintSlot(
  307. name="interval_h", type="enum", label="How often?",
  308. default="6", options=("1", "3", "6", "12", "24"),
  309. help="hours between checks — be gentle with rate limits",
  310. ),
  311. _DELIVER,
  312. ],
  313. skills=("product-price-monitor",),
  314. tags=("prices", "shopping", "travel", "monitor"),
  315. ),
  316. AutomationBlueprint(
  317. key="competitor-watch",
  318. title="Competitor news watch",
  319. description="Track named companies for material news — launches, "
  320. "pricing, funding, filings — with a cited digest.",
  321. category="general",
  322. schedule_template="{minute} {hour} * * {dow}",
  323. prompt_template=(
  324. "Load the competitor-news-monitor skill and run the tick for this "
  325. "watch: companies {companies}; event categories {categories}. "
  326. "Collect incrementally from the last cutoff, deduplicate by "
  327. "underlying event, score materiality against the watch contract, "
  328. "and deliver a cited digest of material events only. If there are "
  329. "no material events, respond with [SILENT]. On the first run, "
  330. "execute the skill's setup phase first: freeze the watchlist, "
  331. "build source coverage, and write the watch contract state file."
  332. ),
  333. slots=[
  334. BlueprintSlot(
  335. name="companies", type="text", label="Which companies?",
  336. default="two or three competitors, by canonical name",
  337. help="canonical names and domains; aliases help dedup",
  338. ),
  339. BlueprintSlot(
  340. name="categories", type="text", label="Which events matter?",
  341. default="product launches, pricing changes, funding, "
  342. "partnerships, executive moves, incidents",
  343. ),
  344. _TIME("09:00"),
  345. BlueprintSlot(
  346. name="recurrence", type="weekdays", label="Repeat on",
  347. default="monday",
  348. options=tuple(WEEKDAY_PRESETS.keys()),
  349. ),
  350. _DELIVER,
  351. ],
  352. skills=("competitor-news-monitor",),
  353. tags=("competitors", "news", "monitor", "research"),
  354. ),
  355. AutomationBlueprint(
  356. key="habit-checkin",
  357. title="Habit check-in",
  358. description="A recurring nudge to keep a habit on track and reflect "
  359. "on whether you did it.",
  360. category="general",
  361. schedule_template="{minute} {hour} * * {dow}",
  362. prompt_template=(
  363. "Nudge the user about their habit: {habit}. Ask whether they did it "
  364. "today, keep it warm and non-judgmental, and offer a one-line word "
  365. "of encouragement. One short message."
  366. ),
  367. slots=[
  368. BlueprintSlot(
  369. name="habit", type="text", label="Which habit?",
  370. default="20 minutes of reading",
  371. ),
  372. _TIME("20:00"),
  373. BlueprintSlot(
  374. name="recurrence", type="weekdays", label="Repeat on",
  375. default="everyday",
  376. options=tuple(WEEKDAY_PRESETS.keys()),
  377. ),
  378. _DELIVER,
  379. ],
  380. tags=("habit", "wellbeing"),
  381. ),
  382. AutomationBlueprint(
  383. key="hydration-move",
  384. title="Hydration & movement nudge",
  385. description="A periodic nudge during the day to drink water, stand up, "
  386. "and stretch.",
  387. category="general",
  388. # NOTE: cron minute-field steps (*/90) wrap per hour — */90 and */120 both degrade to
  389. # hourly. Use an hour-field step instead so the chosen cadence is what actually fires.
  390. schedule_template="0 {start_hour}-{end_hour}/{interval_hours} * * 1-5",
  391. prompt_template=(
  392. "Send the user a brief, friendly nudge to drink some water, stand "
  393. "up, and stretch for a moment. Vary the wording each time so it "
  394. "doesn't feel robotic. One short line."
  395. ),
  396. slots=[
  397. BlueprintSlot(
  398. name="interval_hours", type="enum", label="How often?",
  399. default="1", options=("1", "2", "3"),
  400. help="hours between nudges",
  401. ),
  402. BlueprintSlot(
  403. name="start_hour", type="enum", label="Start hour",
  404. default="9", options=("7", "8", "9", "10"),
  405. help="first hour of the active window (24h)",
  406. ),
  407. BlueprintSlot(
  408. name="end_hour", type="enum", label="End hour",
  409. default="17", options=("16", "17", "18", "19"),
  410. help="last hour of the active window (24h)",
  411. ),
  412. _DELIVER,
  413. ],
  414. tags=("wellbeing", "focus"),
  415. ),
  416. AutomationBlueprint(
  417. key="meal-plan",
  418. title="Weekly meal plan",
  419. description="A weekly meal plan plus a consolidated grocery list, "
  420. "tuned to your diet and how much time you have to cook.",
  421. category="weekly",
  422. schedule_template="{minute} {hour} * * {dow}",
  423. prompt_template=(
  424. "Build the user a meal plan for the coming week: {meals} per day, "
  425. "suited to a {diet} diet and roughly {effort} cooking effort. "
  426. "Include a consolidated grocery list grouped by aisle. Keep blueprints "
  427. "simple and skimmable."
  428. ),
  429. slots=[
  430. BlueprintSlot(
  431. name="diet", type="enum", label="Diet?",
  432. default="no restrictions",
  433. options=("no restrictions", "vegetarian", "vegan",
  434. "high-protein", "low-carb"),
  435. ),
  436. BlueprintSlot(
  437. name="meals", type="enum", label="Meals per day?",
  438. default="dinner only",
  439. options=("dinner only", "lunch and dinner", "all three"),
  440. ),
  441. BlueprintSlot(
  442. name="effort", type="enum", label="Cooking effort?",
  443. default="quick", options=("quick", "medium", "ambitious"),
  444. ),
  445. _TIME("17:00"),
  446. BlueprintSlot(
  447. name="day", type="enum", label="Which day?",
  448. default="sunday",
  449. options=("sunday", "monday", "friday", "saturday"),
  450. ),
  451. _DELIVER,
  452. ],
  453. tags=("weekly", "food"),
  454. ),
  455. AutomationBlueprint(
  456. key="learn-daily",
  457. title="Daily learning drip",
  458. description="One bite-sized lesson a day on a topic you want to learn, "
  459. "building progressively over time.",
  460. category="daily",
  461. schedule_template="{minute} {hour} * * {dow}",
  462. prompt_template=(
  463. "Teach the user one bite-sized lesson about: {topic}. Build on "
  464. "earlier lessons so it progresses rather than repeating. Keep it to "
  465. "a couple of short paragraphs with one concrete example, and end "
  466. "with a single question to check understanding."
  467. ),
  468. slots=[
  469. BlueprintSlot(
  470. name="topic", type="text", label="Learn about…",
  471. default="Spanish vocabulary",
  472. ),
  473. _TIME("08:30"),
  474. BlueprintSlot(
  475. name="recurrence", type="weekdays", label="Repeat on",
  476. default="weekdays",
  477. options=tuple(WEEKDAY_PRESETS.keys()),
  478. ),
  479. _DELIVER,
  480. ],
  481. tags=("learning", "daily"),
  482. ),
  483. AutomationBlueprint(
  484. key="gratitude-journal",
  485. title="Gratitude & reflection prompt",
  486. description="A gentle evening prompt to reflect on the day and note "
  487. "what went well.",
  488. category="general",
  489. schedule_template="{minute} {hour} * * {dow}",
  490. prompt_template=(
  491. "Send the user a short, warm reflection prompt for the end of the "
  492. "day — invite them to note one thing that went well, one thing they "
  493. "are grateful for, and one small win. If they reply, acknowledge it "
  494. "kindly. One message."
  495. ),
  496. slots=[
  497. _TIME("21:30"),
  498. BlueprintSlot(
  499. name="recurrence", type="weekdays", label="Repeat on",
  500. default="everyday",
  501. options=tuple(WEEKDAY_PRESETS.keys()),
  502. ),
  503. _DELIVER,
  504. ],
  505. tags=("wellbeing", "reflection"),
  506. ),
  507. AutomationBlueprint(
  508. key="on-this-day",
  509. title="On-this-day discovery",
  510. description="A daily dose of curiosity: a notable historical event, "
  511. "fact, or word for the day.",
  512. category="daily",
  513. schedule_template="{minute} {hour} * * *",
  514. prompt_template=(
  515. "Give the user one interesting '{flavor}' item for today — keep it "
  516. "short, surprising, and genuinely interesting. One or two sentences, "
  517. "no filler."
  518. ),
  519. slots=[
  520. BlueprintSlot(
  521. name="flavor", type="enum", label="What kind?",
  522. default="on this day in history",
  523. options=("on this day in history", "word of the day",
  524. "science fact", "quote of the day"),
  525. ),
  526. _TIME("07:30"),
  527. _DELIVER,
  528. ],
  529. tags=("daily", "curiosity"),
  530. ),
  531. ]
  532. _CATALOG_BY_KEY = {r.key: r for r in CATALOG}
  533. def list_blueprints() -> list[AutomationBlueprint]:
  534. """The catalog every surface lists: built-ins, then the active profile's plugin blueprints.
  535. Resolved per call — plugins load per profile, so one process serving several profiles must not
  536. cache this."""
  537. from cron.blueprint_plugins import plugin_blueprints
  538. return [*CATALOG, *plugin_blueprints()]
  539. def get_blueprint(key: str) -> Optional[AutomationBlueprint]:
  540. """Look up a built-in or (``<plugin>:<key>``) one of the active profile's plugin blueprints."""
  541. blueprint = _CATALOG_BY_KEY.get(key)
  542. if blueprint is None and ":" in (key or ""):
  543. from cron.blueprint_plugins import plugin_blueprints
  544. blueprint = next((b for b in plugin_blueprints() if b.key == key), None)
  545. return blueprint
  546. def _slot(
  547. blueprint: AutomationBlueprint, *names: str, type: Optional[str] = None
  548. ) -> Optional[BlueprintSlot]:
  549. """First slot matching any of *names* (or *type*), else None."""
  550. return next((s for s in blueprint.slots if s.name in names or (type and s.type == type)), None)
  551. def _slot_default(blueprint: AutomationBlueprint, *names: str) -> Any:
  552. slot = _slot(blueprint, *names)
  553. return slot.default if slot else None
  554. # --- Renderers --------------------------------------------------------------------------------
  555. def blueprint_form_schema(blueprint: AutomationBlueprint) -> dict[str, Any]:
  556. """Emit the JSON a form renderer (dashboard / GUI) needs for this blueprint."""
  557. return {
  558. "key": blueprint.key,
  559. "title": blueprint.title,
  560. "description": blueprint.description,
  561. "category": blueprint.category,
  562. "tags": list(blueprint.tags),
  563. "fields": [
  564. {
  565. "name": s.name,
  566. "type": s.type,
  567. "label": s.label,
  568. "default": s.default,
  569. "options": list(s.options),
  570. "optional": s.optional,
  571. "strict": s.strict,
  572. "help": s.help,
  573. }
  574. for s in blueprint.slots
  575. ],
  576. }
  577. def blueprint_slash_command(blueprint: AutomationBlueprint, values: Optional[dict[str, Any]] = None) -> str:
  578. """Build the flattened ``/blueprint <key> slot=val …`` command string. Uses each slot's default
  579. when ``values`` is omitted (ready-to-paste for docs/dashboard). Free-text slots are quoted."""
  580. values = values or {}
  581. parts = [f"/blueprint {blueprint.key}"]
  582. for s in blueprint.slots:
  583. val = values.get(s.name, s.default)
  584. if val is None or val == "":
  585. if s.optional:
  586. continue
  587. val = ""
  588. sval = str(val)
  589. if s.type == "text" or " " in sval:
  590. sval = '"' + sval.replace('"', '\\"') + '"'
  591. parts.append(f"{s.name}={sval}")
  592. return " ".join(parts)
  593. def blueprint_deeplink(blueprint: AutomationBlueprint, values: Optional[dict[str, Any]] = None) -> str:
  594. """Build the ``hermes://blueprint/<key>?slot=val`` deep-link URL."""
  595. from urllib.parse import quote, urlencode
  596. values = values or {}
  597. query = {
  598. s.name: str(values.get(s.name, s.default))
  599. for s in blueprint.slots
  600. if values.get(s.name, s.default) not in (None, "")
  601. }
  602. qs = ("?" + urlencode(query)) if query else ""
  603. return f"hermes://blueprint/{quote(blueprint.key)}{qs}"
  604. def _humanize_schedule(blueprint: AutomationBlueprint) -> str:
  605. """A short human-readable description of when a blueprint runs (defaults)."""
  606. sched = blueprint.schedule_template
  607. if sched.startswith("*/"):
  608. every = _slot_default(blueprint, "interval_min") or sched.split("/")[1].split()[0]
  609. return f"every {every} minutes"
  610. if "{interval_hours}" in sched:
  611. every = str(_slot_default(blueprint, "interval_hours") or "1")
  612. scope = "weekdays, " if "* * 1-5" in sched else ""
  613. return f"{scope}every hour" if every == "1" else f"{scope}every {every} hours"
  614. time_slot = _slot(blueprint, type="time")
  615. when = time_slot.default if time_slot else None
  616. if "* * 1-5" in sched:
  617. return f"weekdays at {when}" if when else "every weekday"
  618. if "{dow}" in sched:
  619. scope = _slot_default(blueprint, "day", "recurrence") or ""
  620. if scope and when:
  621. return f"{scope} at {when}"
  622. return f"at {when}" if when else "on a schedule"
  623. return f"daily at {when}" if when else "on a schedule"
  624. def blueprint_catalog_entry(blueprint: AutomationBlueprint) -> dict[str, Any]:
  625. """Unified serializable shape (docs generator + dashboard API): form schema + ready-to-paste
  626. slash command + deep-link URL + human-readable schedule."""
  627. return {
  628. **blueprint_form_schema(blueprint),
  629. "source": "plugin" if blueprint.plugin else "builtin",
  630. "plugin": blueprint.plugin or None,
  631. "schedule": blueprint.schedule_template,
  632. "scheduleHuman": _humanize_schedule(blueprint),
  633. "command": blueprint_slash_command(blueprint),
  634. "appUrl": blueprint_deeplink(blueprint),
  635. }
  636. # --- Fill + validate + translate to a create_job spec -----------------------------------------
  637. _TIME_RE = re.compile(r"^([01]?\d|2[0-3]):([0-5]\d)$")
  638. _DAY_TO_DOW = {
  639. "sunday": "0", "monday": "1", "tuesday": "2", "wednesday": "3",
  640. "thursday": "4", "friday": "5", "saturday": "6",
  641. }
  642. def _resolve_schedule(blueprint: AutomationBlueprint, values: dict[str, Any]) -> str:
  643. """Fill the schedule_template placeholders from resolved slot values."""
  644. sched = blueprint.schedule_template
  645. # A free-text `schedule` slot passes through verbatim (full flexibility).
  646. if values.get("schedule"):
  647. return str(values["schedule"])
  648. repl: dict[str, str] = {}
  649. if "{minute}" in sched or "{hour}" in sched:
  650. time_val = values.get("time")
  651. if not time_val:
  652. raise BlueprintFillError("a time is required")
  653. m = _TIME_RE.match(str(time_val).strip())
  654. if not m:
  655. raise BlueprintFillError(f"invalid time {time_val!r} — use HH:MM (24h)")
  656. repl["hour"] = str(int(m.group(1)))
  657. repl["minute"] = str(int(m.group(2)))
  658. if "{dow}" in sched:
  659. if "recurrence" in values:
  660. preset = str(values.get("recurrence", "everyday")).lower()
  661. if preset not in WEEKDAY_PRESETS:
  662. raise BlueprintFillError(
  663. f"unknown recurrence {preset!r} — one of {', '.join(WEEKDAY_PRESETS)}"
  664. )
  665. repl["dow"] = WEEKDAY_PRESETS[preset]
  666. elif "day" in values:
  667. day = str(values.get("day", "")).lower()
  668. if day not in _DAY_TO_DOW:
  669. raise BlueprintFillError(f"unknown day {day!r}")
  670. repl["dow"] = _DAY_TO_DOW[day]
  671. else:
  672. repl["dow"] = "*"
  673. if "{interval_min}" in sched:
  674. iv = str(values.get("interval_min", "")).strip()
  675. if not iv.isdigit() or int(iv) <= 0:
  676. raise BlueprintFillError(f"invalid interval {iv!r} — minutes as a positive integer")
  677. repl["interval_min"] = iv
  678. # Remaining {slot} placeholders are filled verbatim from validated enum/text slot values (enum
  679. # options were already checked in fill_blueprint, so they are safe to interpolate).
  680. for name in re.findall(r"\{(\w+)\}", sched):
  681. if name not in repl and name in values:
  682. repl[name] = str(values[name])
  683. try:
  684. return sched.format(**repl)
  685. except KeyError as e: # pragma: no cover - template/slot mismatch is a dev error
  686. raise BlueprintFillError(f"schedule template missing value for {e}") from e
  687. def fill_blueprint(
  688. blueprint: AutomationBlueprint, values: dict[str, Any], *,
  689. origin: Optional[dict[str, Any]] = None,
  690. ) -> dict[str, Any]:
  691. """Validate ``values`` and return ``cron.jobs.create_job`` kwargs.
  692. Missing required slots raise BlueprintFillError naming the slot (forms show field errors, the
  693. agent knows what to ask). Unknown slot names are rejected (a typo'd ``tiem=07:15`` must not
  694. silently create a job with the default time). Strict enums are checked against their options.
  695. """
  696. known = {s.name for s in blueprint.slots}
  697. unknown = sorted(set(values) - known)
  698. if unknown:
  699. raise BlueprintFillError(
  700. f"unknown slot{'s' if len(unknown) > 1 else ''}: "
  701. f"{', '.join(unknown)} — valid: {', '.join(s.name for s in blueprint.slots)}"
  702. )
  703. resolved: dict[str, Any] = {}
  704. for s in blueprint.slots:
  705. raw = values.get(s.name, s.default)
  706. if raw in (None, ""):
  707. if s.optional:
  708. continue
  709. raise BlueprintFillError(f"missing required value: {s.name} ({s.label})")
  710. if s.type == "enum" and s.strict and s.options and str(raw) not in {str(o) for o in s.options}:
  711. raise BlueprintFillError(
  712. f"{s.name}={raw!r} not allowed — one of {', '.join(map(str, s.options))}"
  713. )
  714. resolved[s.name] = raw
  715. schedule = _resolve_schedule(blueprint, resolved)
  716. try:
  717. prompt = blueprint.prompt_template.format(**resolved)
  718. except KeyError as e:
  719. raise BlueprintFillError(f"blueprint prompt missing value for {e}") from e
  720. spec: dict[str, Any] = {
  721. "prompt": prompt,
  722. "schedule": schedule,
  723. "name": blueprint.title,
  724. "deliver": resolved.get("deliver", blueprint.deliver_default),
  725. }
  726. if blueprint.skills:
  727. spec["skills"] = list(blueprint.skills)
  728. if origin is not None:
  729. spec["origin"] = origin
  730. return spec