cron.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. """``hermes cron`` subcommand parser."""
  2. from __future__ import annotations
  3. import argparse
  4. from typing import Callable
  5. from hermes_cli.subcommands._shared import add_accept_hooks_flag
  6. def _flag(parser, *names, help, **kw):
  7. parser.add_argument(*names, action="store_true", help=help, **kw)
  8. def _catch_up_flag(value: str) -> bool:
  9. if value not in ("on", "off"):
  10. raise argparse.ArgumentTypeError("use 'on' (run missed runs once) or 'off' (skip them)")
  11. return value == "on"
  12. def _add_catch_up(parser) -> None:
  13. parser.add_argument(
  14. "--catch-up", dest="catch_up", type=_catch_up_flag, metavar="{on,off}",
  15. help="Runs missed while the machine was off: 'on' runs once on return, 'off' skips "
  16. "them (each is booked as a 'missed' row in `hermes cron runs`). Default: "
  17. "cron.catch_up_missed for recurring jobs; one-shots skip.")
  18. def build_cron_parser(subparsers, *, cmd_cron: Callable) -> None:
  19. """Attach the ``cron`` subcommand (and its sub-actions) to ``subparsers``."""
  20. cron_parser = subparsers.add_parser(
  21. "cron", help="Cron job management", description="Manage scheduled tasks")
  22. cron_subparsers = cron_parser.add_subparsers(dest="cron_command")
  23. cron_list = cron_subparsers.add_parser("list", help="List scheduled jobs")
  24. _flag(cron_list, "--all", help="Include disabled and completed jobs")
  25. cron_create = cron_subparsers.add_parser(
  26. "create", aliases=["add"], help="Create a scheduled job")
  27. cron_create.add_argument("schedule", help="Schedule like '30m', 'every 2h', or '0 9 * * *'")
  28. cron_create.add_argument(
  29. "prompt", nargs="?", help="Optional self-contained prompt or task instruction")
  30. cron_create.add_argument("--name", help="Optional human-friendly job name")
  31. cron_create.add_argument("--deliver",
  32. help="Delivery target: origin, local, telegram, discord, signal, "
  33. "platform:chat_id, or bot-chat[:profile] (inject output into a "
  34. "local profile's canonical Bot Chat as a message the bot responds to), "
  35. "or room:<room_id>[@profile] (post into a Group Chat; wakes only the Bots it @mentions)")
  36. cron_create.add_argument("--failure-deliver", dest="failure_deliver",
  37. help="Override target for FAILURE notices only (same grammar as "
  38. "--deliver). 'local' suppresses failure notices entirely; run "
  39. "state stays visible in `hermes cron list`. Omit = failures "
  40. "follow --deliver.")
  41. cron_create.add_argument("--repeat", type=int, help="Optional repeat count")
  42. _add_catch_up(cron_create)
  43. cron_create.add_argument("--skill", dest="skills", action="append",
  44. help="Attach a skill. Repeat to add multiple skills.")
  45. cron_create.add_argument("--script",
  46. help="Path to a script under ~/.hermes/scripts/. Default mode: "
  47. "script stdout is injected into the agent's prompt each run. "
  48. "With --no-agent: the script IS the job and its stdout is "
  49. "delivered verbatim. .sh/.bash files run via bash, everything "
  50. "else via Python.")
  51. _flag(cron_create, "--no-agent", dest="no_agent", default=False,
  52. help="Skip the LLM entirely — run --script on schedule and deliver "
  53. "its stdout directly. Empty stdout = silent. Classic watchdog "
  54. "pattern (memory alerts, disk alerts, CI pings).")
  55. cron_create.add_argument("--monitor-script", dest="monitor_script",
  56. help="Monitor mode: path to a cheap source script under "
  57. "~/.hermes/scripts/ that runs each tick BEFORE the agent. "
  58. "Unchanged output (exact-bytes hash) suppresses the agent run "
  59. "entirely; changed output injects a MONITOR CHANGE DETECTED "
  60. "diff into the prompt. Script output must be stable (no "
  61. "timestamps). Mutually exclusive with --monitor-url; "
  62. "incompatible with --no-agent.")
  63. cron_create.add_argument("--monitor-url", dest="monitor_url",
  64. help="Monitor mode: http(s) URL fetched with a bounded GET each tick "
  65. "instead of a script. Same hash-suppression semantics as "
  66. "--monitor-script.")
  67. cron_create.add_argument("--workdir",
  68. help="Absolute path for the job to run from. Injects AGENTS.md / CLAUDE.md / .cursorrules from that directory and uses it as the cwd for terminal/file/code_exec tools. Omit to preserve old behaviour (no project context files).",
  69. )
  70. cron_create.add_argument("--model",
  71. help="Pin this job to a specific inference model (user-owned; the "
  72. "agent's cronjob tool cannot set this). Omit to follow "
  73. "cron.model, then the main agent model (`hermes model`), at fire time.")
  74. cron_create.add_argument("--pin", dest="pinned", action="store_true", default=None,
  75. help="Lock the CURRENT main agent model (and its provider) onto this job so later "
  76. "`hermes model` changes never touch it. Ignored when --model is given.")
  77. cron_create.add_argument("--provider", dest="model_provider",
  78. help="Inference provider paired with --model (e.g. 'openrouter', 'nous').")
  79. cron_create.add_argument("--reasoning-effort", dest="reasoning_effort",
  80. help="Pin this job's reasoning (thinking) effort: none, minimal, low, "
  81. "medium, high, xhigh, max, or ultra. Overrides agent.reasoning_effort "
  82. "and agent.reasoning_overrides for this job; unsupported levels are "
  83. "clamped by the provider at request time. Omit to follow config.")
  84. cron_create.add_argument("--interpreter",
  85. help="Absolute or ~ path to a Python in your own venv (e.g. ~/venvs/report/bin/python) "
  86. "for a .py --script / --monitor-script, so it can import packages Hermes does not "
  87. "ship. .sh/.bash still run under bash. Omit to use Hermes' Python.")
  88. cron_create.add_argument("--timezone",
  89. help="IANA zone for this job's schedule (e.g. Asia/Hong_Kong), so the cron "
  90. "expression is read as THAT zone's wall clock whatever the profile's timezone "
  91. "is. Omit to inherit the profile timezone.")
  92. cron_create.add_argument("--grace-minutes", dest="grace_minutes",
  93. help="Catch-up window override in minutes (0-1440) for a cron schedule. "
  94. "Default: half the period, clamped to 2-120 minutes. 0 = never catch up "
  95. "(a missed occurrence is skipped, not run late).")
  96. cron_create.add_argument(
  97. "--continuity", dest="continuity", action="store_const", const=True, default=None,
  98. help="Each run wakes up with the job's own previous output injected "
  99. "into its prompt, so it can dedupe against what was already "
  100. "reported and continue where the last run left off (scouts, "
  101. "monitors, incremental digests). First run is unchanged.")
  102. _flag(cron_create, "--paused", default=False,
  103. help="Create disabled in one write; resume to schedule, or explicitly run now.")
  104. cron_create.add_argument("--paused-reason", help="Auditable reason; requires --paused.")
  105. cron_edit = cron_subparsers.add_parser("edit", help="Edit an existing scheduled job")
  106. cron_edit.add_argument("job_id", help="Job ID to edit")
  107. cron_edit.add_argument("--schedule", help="New schedule")
  108. cron_edit.add_argument("--prompt", help="New prompt/task instruction")
  109. cron_edit.add_argument("--name", help="New job name")
  110. cron_edit.add_argument("--deliver", help="New delivery target")
  111. cron_edit.add_argument("--failure-deliver", dest="failure_deliver",
  112. help="Override target for failure notices (same grammar as --deliver; "
  113. "'local' suppresses; '' clears the override)")
  114. cron_edit.add_argument("--repeat", type=int, help="New repeat count")
  115. _add_catch_up(cron_edit)
  116. cron_edit.add_argument("--skill", dest="skills", action="append",
  117. help="Replace the job's skills with this set. Repeat to attach multiple skills.")
  118. cron_edit.add_argument("--add-skill", dest="add_skills", action="append",
  119. help="Append a skill without replacing the existing list. Repeatable.")
  120. cron_edit.add_argument("--remove-skill", dest="remove_skills", action="append",
  121. help="Remove a specific attached skill. Repeatable.")
  122. _flag(cron_edit, "--clear-skills", help="Remove all attached skills from the job")
  123. cron_edit.add_argument("--script",
  124. help="Path to a script under ~/.hermes/scripts/. Pass empty string to clear. "
  125. "With --no-agent the script IS the job; otherwise its stdout is "
  126. "injected into the agent's prompt each run.")
  127. cron_edit.add_argument(
  128. "--no-agent", dest="no_agent", action="store_const", const=True, default=None,
  129. help="Enable no-agent mode on this job (requires --script or an "
  130. "existing script on the job).")
  131. cron_edit.add_argument("--agent", dest="no_agent", action="store_const", const=False,
  132. help="Disable no-agent mode on this job (reverts to LLM-driven execution).")
  133. cron_edit.add_argument(
  134. "--continuity", dest="continuity", action="store_const", const=True, default=None,
  135. help="Turn on run-to-run continuity: each run sees the job's own "
  136. "previous output (dedupe, continue where it left off).")
  137. cron_edit.add_argument("--no-continuity", dest="continuity", action="store_const", const=False,
  138. help=("Turn off run-to-run continuity (other context_from job refs are preserved)."))
  139. cron_edit.add_argument("--monitor-script", dest="monitor_script",
  140. help="Set/replace the monitor source script (see `hermes cron create "
  141. "--monitor-script`). Pass empty string to clear.")
  142. cron_edit.add_argument("--monitor-url", dest="monitor_url",
  143. help=("Set/replace the monitor source URL. Pass empty string to clear."))
  144. cron_edit.add_argument("--workdir",
  145. help="Absolute path for the job to run from (injects AGENTS.md etc. and sets terminal cwd). Pass empty string to clear.",
  146. )
  147. cron_edit.add_argument("--model",
  148. help="Pin this job to a specific inference model (user-owned; the "
  149. "agent's cronjob tool cannot set this). Pass empty string to "
  150. "clear the pin and follow cron.model, then the main agent model.")
  151. _pin = cron_edit.add_mutually_exclusive_group()
  152. _pin.add_argument("--pin", dest="pinned", action="store_true", default=None,
  153. help="Lock the CURRENT main agent model (and its provider) onto this job.")
  154. _pin.add_argument("--unpin", dest="pinned", action="store_false",
  155. help="Release the job's model pin so it follows the main agent model again.")
  156. cron_edit.add_argument("--provider", dest="model_provider",
  157. help="Inference provider paired with --model. Pass empty string to clear.")
  158. cron_edit.add_argument("--reasoning-effort", dest="reasoning_effort",
  159. help="Pin this job's reasoning (thinking) effort: none, minimal, low, "
  160. "medium, high, xhigh, max, or ultra. Pass empty string to clear "
  161. "the pin and follow config resolution.")
  162. cron_edit.add_argument("--interpreter",
  163. help="Absolute or ~ path to a Python for a .py script / monitor script. "
  164. "Pass empty string to clear (back to Hermes' Python).")
  165. cron_edit.add_argument("--timezone",
  166. help="IANA zone for this job's schedule. Pass empty string to clear the pin "
  167. "(back to the profile timezone); next_run_at is recomputed in the new zone.")
  168. cron_edit.add_argument("--grace-minutes", dest="grace_minutes",
  169. help="Catch-up window override in minutes (0-1440). 0 = never catch up. "
  170. "Pass empty string to restore the computed window.")
  171. # lifecycle actions
  172. cron_pause = cron_subparsers.add_parser("pause", help="Pause a scheduled job")
  173. cron_pause.add_argument("job_id", help="Job ID to pause")
  174. cron_resume = cron_subparsers.add_parser("resume", help="Resume a paused job")
  175. cron_resume.add_argument("job_id", help="Job ID to resume")
  176. cron_resume.add_argument("--at", dest="run_at", help="Re-arm at an ISO-8601 time")
  177. _flag(cron_resume, "--run-now", help="Re-arm to run now")
  178. cron_run = cron_subparsers.add_parser("run", help="Run a job on the next scheduler tick")
  179. cron_run.add_argument("job_id", help="Job ID to trigger")
  180. add_accept_hooks_flag(cron_run)
  181. cron_cancel = cron_subparsers.add_parser(
  182. "cancel", help="Stop a job's live run (its schedule is untouched)")
  183. cron_cancel.add_argument("job_id", help="Job ID whose in-flight run to stop")
  184. cron_cancel.add_argument(
  185. "--reason", help="Optional note recorded with the cancelled run")
  186. cron_remove = cron_subparsers.add_parser(
  187. "remove", aliases=["rm", "delete"], help="Remove a scheduled job")
  188. cron_remove.add_argument("job_id", help="Job ID to remove")
  189. # cron status
  190. cron_subparsers.add_parser("status", help="Check if cron scheduler is running")
  191. cron_runs = cron_subparsers.add_parser(
  192. "runs", aliases=["history"], help="Show durable execution attempts")
  193. cron_runs.add_argument("job_id", nargs="?", help="Optional job ID filter")
  194. cron_runs.add_argument("--limit", type=int, default=20, help="Rows to show (1-500)")
  195. # cron incidents — durable failure incidents (list/ack)
  196. cron_incidents = cron_subparsers.add_parser(
  197. "incidents", help="List or acknowledge durable cron failure incidents")
  198. cron_incidents.add_argument("--state", choices=["detected", "alerted", "resolved", "closed"],
  199. help="Filter incidents by lifecycle state")
  200. cron_incidents.add_argument(
  201. "incident_action", nargs="?", default="list", choices=["list", "ack"],
  202. help="Action (default: list)")
  203. cron_incidents.add_argument("incident_id", nargs="?", help="Incident ID to acknowledge (ack)")
  204. # notepad: per-job durable KV, injected into the job prompt each run.
  205. cron_notepad = cron_subparsers.add_parser(
  206. "notepad", help="Read/write a job's durable notepad (persistent KV across runs)")
  207. cron_notepad.add_argument("job_id", help="Job ID the notepad belongs to")
  208. cron_notepad.add_argument(
  209. "notepad_action", nargs="?", default="list", choices=["get", "set", "delete", "list"],
  210. help="Action (default: list)")
  211. cron_notepad.add_argument("key", nargs="?", help="Notepad key (get/set/delete)")
  212. cron_notepad.add_argument("value", nargs="?", help="Value to store (set)")
  213. cron_subparsers.add_parser("doctor", help="Check scheduled jobs for common health issues")
  214. cron_tick = cron_subparsers.add_parser("tick", help="Run due jobs once and exit")
  215. add_accept_hooks_flag(cron_tick)
  216. add_accept_hooks_flag(cron_parser)
  217. cron_parser.set_defaults(func=cmd_cron)