suggestions_cmd.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. """Shared ``/suggestions`` command logic for CLI and gateway.
  2. Both surfaces call ``handle_suggestions_command(args, origin=...)`` and present the returned text,
  3. so the two surfaces can never drift. Subcommands are listed in ``_USAGE``.
  4. """
  5. from __future__ import annotations
  6. import logging
  7. from typing import Any, Dict, Optional
  8. logger = logging.getLogger(__name__)
  9. def _fmt_pending(pending: list) -> str:
  10. if not pending:
  11. return ("No suggested automations right now.\n"
  12. "Try `/suggestions catalog` to see the curated starter set, or "
  13. "install a blueprint skill to get one.")
  14. lines = ["Suggested automations — `/suggestions accept N` or `dismiss N`:\n"]
  15. for i, s in enumerate(pending, 1):
  16. sched = (s.get("job_spec", {}) or {}).get("schedule", "?")
  17. lines.append(f" {i}. {s.get('title', '(untitled)')} [{sched}] ({s.get('source', '?')})")
  18. desc = s.get("description", "").strip()
  19. if desc:
  20. lines.append(f" {desc}")
  21. return "\n".join(lines)
  22. def _resolve_origin() -> Optional[dict[str, Any]]:
  23. """Best-effort current-chat origin from session env (cron's ``_origin_from_env``, which also
  24. withholds non-push surfaces such as api_server) so an accepted job delivers back to the
  25. accepting chat; None lets create_job use the home channel."""
  26. try:
  27. from tools.cronjob_job_args import _origin_from_env
  28. return _origin_from_env()
  29. except Exception:
  30. pass
  31. return None
  32. def _accept(store, rest: str, origin, surface: str) -> str:
  33. if not rest:
  34. return "Usage: /suggestions accept <number|id>"
  35. from cron.scheduler import CronSchedulerRegistrationError
  36. try:
  37. job = store.accept_suggestion(rest, origin=origin)
  38. except CronSchedulerRegistrationError as e:
  39. return e.user_message()
  40. if job is None:
  41. return f"No pending suggestion matches '{rest}'. Run /suggestions to list them."
  42. sched = job.get("schedule_display") or (job.get("job_spec", {}) or {}).get("schedule", "")
  43. name = job.get("name", "automation")
  44. manage = ("Manage it with /cron." if surface == "cli"
  45. else "Ask me to list, pause, or remove it any time.")
  46. return f"Scheduled '{name}'" + (f" ({sched})" if sched else "") + f". {manage}"
  47. def _dismiss(store, rest: str, origin, surface: str) -> str:
  48. if not rest:
  49. return "Usage: /suggestions dismiss <number|id>"
  50. if store.dismiss_suggestion(rest):
  51. return "Dismissed. Won't suggest that again."
  52. return f"No pending suggestion matches '{rest}'."
  53. def _catalog(store, rest: str, origin, surface: str) -> str:
  54. try:
  55. from cron.suggestion_catalog import seed_catalog_suggestions
  56. created = seed_catalog_suggestions()
  57. except Exception as e:
  58. logger.debug("catalog seed failed: %s", e)
  59. return "Couldn't load the catalog."
  60. if not created:
  61. return ("No new catalog automations to add (already offered, dismissed, "
  62. "or your suggestion list is full). Run /suggestions to see pending.")
  63. added = ", ".join(c.get("title", "?") for c in created)
  64. return f"Added {len(created)} suggestion(s): {added}.\nRun /suggestions to review."
  65. def _clear(store, rest: str, origin, surface: str) -> str:
  66. return f"Cleared {store.clear_resolved()} resolved suggestion record(s)."
  67. _SUBCOMMANDS = {
  68. "": lambda store, rest, origin, surface: _fmt_pending(store.list_pending()),
  69. "accept": _accept, "add": _accept, "schedule": _accept,
  70. "dismiss": _dismiss, "no": _dismiss, "reject": _dismiss,
  71. "catalog": _catalog, "clear": _clear}
  72. _USAGE = (
  73. "Usage:\n"
  74. " /suggestions list pending\n"
  75. " /suggestions accept N schedule suggestion N\n"
  76. " /suggestions dismiss N dismiss suggestion N\n"
  77. " /suggestions catalog add curated starter automations\n"
  78. " /suggestions clear housekeeping")
  79. def handle_suggestions_command(
  80. args: str, *, origin: Optional[dict[str, Any]] = None, surface: str = "cli") -> str:
  81. """Dispatch a ``/suggestions`` invocation (``args`` = text after the command word); returns
  82. text to show the user. ``origin`` defaults to the session environment's chat."""
  83. if origin is None:
  84. origin = _resolve_origin()
  85. try:
  86. from cron import suggestions as store
  87. except Exception as e: # pragma: no cover - import guard
  88. logger.debug("suggestions store import failed: %s", e)
  89. return "Suggestions are unavailable in this build."
  90. parts = (args or "").strip().split()
  91. handler = _SUBCOMMANDS.get(parts[0].lower() if parts else "")
  92. if handler is None:
  93. return _USAGE
  94. return handler(store, " ".join(parts[1:]).strip(), origin, surface)