cli_cron_lines.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. """The classic CLI's `/cron` as plain lines: the overview, the list and every store write.
  2. Shared by the classic CLI off the gateway (`CLICommandsMixin._handle_cron_command`) and the shared gateway, which runs
  3. `/cron` for a local session's `slash.exec` (gateway/session_commands.py, gateway/session_cron_commands.py), so the
  4. profile's cron store has one writer: the gateway that owns it.
  5. """
  6. from __future__ import annotations
  7. import shlex
  8. from hermes_cli.cli_commands_session_tools import _lines, _t
  9. def _cron(**kwargs) -> dict:
  10. # Looked up on the mixin module at call time so tests that patch `cli_commands_mixin._cron_api` still apply.
  11. from hermes_cli import cli_commands_mixin
  12. return cli_commands_mixin._cron_api(**kwargs)
  13. def cron_overview_lines() -> list[str]:
  14. """Bare ``/cron``: the command card, then the current jobs. Plain text (the shared gateway serves
  15. the same lines to every local session, gateway/session_cron_commands.py)."""
  16. out = ["", "+" + "-" * 68 + "+", "|" + _t("cron.overview_title").center(68) + "|",
  17. "+" + "-" * 68 + "+", "", f" {_t('cron.overview_commands')}",
  18. *_lines(_t("cron.overview_usage"), pad=" "), ""]
  19. result = _cron(action="list")
  20. jobs = result.get("jobs", []) if result.get("success") else []
  21. if not jobs:
  22. return [*out, f" {_t('cron.no_jobs_hint')}", ""]
  23. from hermes_cli.cron import _next_run_row
  24. out += [f" {_t('cron.current_jobs')}", " " + "-" * 63]
  25. for job in jobs:
  26. out.append(f" {job['job_id'][:12]:<12} | {job['schedule']:<15} | {job.get('repeat', '?'):<8}")
  27. if job.get("skills"):
  28. out.append(f" {_t('cron.skills', skills=', '.join(job['skills']))}")
  29. out.append(f" {job.get('prompt_preview', '')}")
  30. if job.get("next_run_at"):
  31. # A stamp parked past the scheduler grace must not read as upcoming (#114309).
  32. label, value = _next_run_row(job)
  33. out.append(f" {_t('cron.next_short') if label == 'Next run' else label}: {value}")
  34. out.append("")
  35. return [*out, ""]
  36. def cron_list_lines(*, include_disabled: bool = False) -> list[str]:
  37. """``/cron list [--all]``."""
  38. result = _cron(action="list", include_disabled=include_disabled)
  39. jobs = result.get("jobs", []) if result.get("success") else []
  40. if not jobs:
  41. return [_t("cron.no_jobs")]
  42. from hermes_cli.cron import _next_run_row
  43. out = ["", _t("cron.list_header"), "-" * 80]
  44. for job in jobs:
  45. out += [f" {_t('cron.id', job_id=job['job_id'])}", f" {_t('cron.name', name=job['name'])}",
  46. f" {_t('cron.state', state=job.get('state', '?'))}",
  47. f" {_t('cron.schedule_repeat', schedule=job['schedule'], repeat=job.get('repeat', '?'))}",
  48. " {}: {}".format(*_next_run_row(job)) if job.get("next_run_at") else f" {_t('cron.next_run_na')}"]
  49. if job.get("skills"):
  50. out.append(f" {_t('cron.skills', skills=', '.join(job['skills']))}")
  51. out.append(f" {_t('cron.prompt', prompt=job.get('prompt_preview', ''))}")
  52. if job.get("last_run_at"):
  53. status = job.get("last_status") or "?"
  54. # delivery_failed: the run succeeded but delivery didn't — the reason lives
  55. # in last_delivery_error (last_error is None).
  56. if status == "delivery_failed" and job.get("last_delivery_error"):
  57. status = _t("cron.status_delivery_failed", error=job["last_delivery_error"])
  58. elif status == "error" and job.get("last_error"):
  59. status = _t("cron.status_error", error=job["last_error"])
  60. out.append(f" {_t('cron.last_run', when=job['last_run_at'], status=status)}")
  61. out.append("")
  62. return out
  63. # /cron flag tables: flag -> opts key. Order-sensitive in _parse_cron_flags: bool flags never
  64. # consume a value; --repeat is int-validated separately.
  65. _CRON_BOOL_FLAGS = {"--clear-skills": "clear_skills", "--all": "all"}
  66. _CRON_LIST_FLAGS = {"--skill": "skills", "--add-skill": "add_skills", "--remove-skill": "remove_skills"}
  67. _CRON_VALUE_FLAGS = {"--name": "name", "--deliver": "deliver", "--prompt": "prompt", "--schedule": "schedule"}
  68. def _normalize_skills(values) -> list:
  69. """Strip, drop empties, and dedupe (order-preserving)."""
  70. normalized = []
  71. for value in values:
  72. text = str(value or "").strip()
  73. if text and text not in normalized:
  74. normalized.append(text)
  75. return normalized
  76. def _parse_cron_flags(tokens):
  77. """Parse /cron flags into an opts dict (None for a bad --repeat)."""
  78. opts = {
  79. "name": None, "deliver": None, "repeat": None, "prompt": None, "schedule": None,
  80. "skills": [], "add_skills": [], "remove_skills": [],
  81. "clear_skills": False, "all": False, "positionals": []}
  82. i = 0
  83. while i < len(tokens):
  84. token = tokens[i]
  85. has_value = i + 1 < len(tokens)
  86. if token in _CRON_BOOL_FLAGS:
  87. opts[_CRON_BOOL_FLAGS[token]] = True
  88. i += 1
  89. elif token in _CRON_LIST_FLAGS and has_value:
  90. opts[_CRON_LIST_FLAGS[token]].append(tokens[i + 1])
  91. i += 2
  92. elif token == "--repeat" and has_value:
  93. try:
  94. opts["repeat"] = int(tokens[i + 1])
  95. except ValueError:
  96. return None
  97. i += 2
  98. elif token in _CRON_VALUE_FLAGS and has_value:
  99. opts[_CRON_VALUE_FLAGS[token]] = tokens[i + 1]
  100. i += 2
  101. else:
  102. opts["positionals"].append(token)
  103. i += 1
  104. return opts
  105. def _add_lines(subcommand: str, opts: dict) -> list[str]:
  106. positionals = opts["positionals"]
  107. if not positionals:
  108. return [_t("cron.usage_add")]
  109. schedule = opts["schedule"] or positionals[0]
  110. prompt = opts["prompt"] or " ".join(positionals[1:])
  111. skills = _normalize_skills(opts["skills"])
  112. if not prompt and not skills:
  113. return [_t("cron.need_prompt_or_skill")]
  114. result = _cron(
  115. action="create", schedule=schedule, prompt=prompt or None, name=opts["name"],
  116. deliver=opts["deliver"], repeat=opts["repeat"], skills=skills or None)
  117. if not result.get("success"):
  118. return [_t("cron.create_failed", error=result.get("error"))]
  119. out = [_t("cron.created", job_id=result["job_id"]), f" {_t('cron.schedule', schedule=result['schedule'])}"]
  120. if result.get("skills"):
  121. out.append(f" {_t('cron.skills', skills=', '.join(result['skills']))}")
  122. return [*out, f" {_t('cron.next_run', value=result['next_run_at'])}"]
  123. def _edit_lines(subcommand: str, opts: dict) -> list[str]:
  124. from cron import get_job
  125. positionals = opts["positionals"]
  126. if not positionals:
  127. return [_t("cron.usage_edit")]
  128. job_id = positionals[0]
  129. existing = get_job(job_id)
  130. if not existing:
  131. return [_t("cron.job_not_found", job_id=job_id)]
  132. # Skill edit precedence: --clear-skills > --skill (replace) > --add/--remove (merge) > untouched.
  133. final_skills = None
  134. replacement_skills = _normalize_skills(opts["skills"])
  135. add_skills = _normalize_skills(opts["add_skills"])
  136. remove_skills = set(_normalize_skills(opts["remove_skills"]))
  137. if opts["clear_skills"]:
  138. final_skills = []
  139. elif replacement_skills:
  140. final_skills = replacement_skills
  141. elif add_skills or remove_skills:
  142. existing_skills = list(existing.get("skills") or ([existing["skill"]] if existing.get("skill") else []))
  143. final_skills = [skill for skill in existing_skills if skill not in remove_skills]
  144. final_skills += [skill for skill in add_skills if skill not in final_skills]
  145. result = _cron(
  146. action="update", job_id=job_id, schedule=opts["schedule"], prompt=opts["prompt"],
  147. name=opts["name"], deliver=opts["deliver"], repeat=opts["repeat"], skills=final_skills)
  148. if not result.get("success"):
  149. return [_t("cron.update_failed", error=result.get("error"))]
  150. job = result["job"]
  151. return [_t("cron.updated", job_id=job["job_id"]), f" {_t('cron.schedule', schedule=job['schedule'])}",
  152. f" {_t('cron.skills', skills=', '.join(job['skills']))}" if job.get("skills")
  153. else f" {_t('cron.skills_none')}"]
  154. def _job_action_lines(subcommand: str, opts: dict) -> list[str]:
  155. """pause / resume / run / remove (aliases rm, delete) on one job id."""
  156. positionals = opts["positionals"]
  157. if not positionals:
  158. return [_t("cron.usage_action", subcommand=subcommand)]
  159. job_id = positionals[0]
  160. action = "remove" if subcommand in {"remove", "rm", "delete"} else subcommand
  161. result = _cron(action=action, job_id=job_id, reason="paused from /cron" if action == "pause" else None)
  162. if not result.get("success"):
  163. return [_t(f"cron.{action}_failed", error=result.get("error"))]
  164. if action == "remove":
  165. removed = result.get("removed_job", {})
  166. return [_t("cron.removed", name=removed.get("name", job_id), job_id=job_id)]
  167. job = result["job"]
  168. if action == "run" and job.get("execution_skipped"):
  169. # A refused run-now (claim lost, paused, gone) must not read as accepted.
  170. return [_t("cron.did_not_run", name=job["name"], job_id=job_id, reason=job["execution_skipped"])]
  171. # One full template per action verb (cron.paused / cron.resumed / cron.triggered).
  172. out = [_t({"pause": "cron.paused", "resume": "cron.resumed", "run": "cron.triggered"}[action],
  173. name=job["name"], job_id=job_id)]
  174. if action == "resume":
  175. out.append(f" {_t('cron.next_run', value=job.get('next_run_at'))}")
  176. elif action == "run":
  177. from hermes_cli.cron import _run_outcome
  178. out.append(f" {_run_outcome(job)}")
  179. return out
  180. # /cron subcommand -> line builder.
  181. _CRON_SUBCOMMANDS = {
  182. # ``-a``: the list-all alias main's TUI read path accepted (only here, so no other form loses a ``-a`` word).
  183. "list": lambda _sub, opts: cron_list_lines(include_disabled=opts["all"] or "-a" in opts["positionals"]),
  184. "add": _add_lines, "create": _add_lines, "edit": _edit_lines,
  185. **{k: _job_action_lines for k in ("pause", "resume", "run", "remove", "rm", "delete")}}
  186. def cron_command_lines(arg: str) -> list[str]:
  187. """``/cron [subcommand ...]`` (the text after ``/cron``); raises ValueError on an unclosed quote."""
  188. tokens = shlex.split(arg)
  189. if not tokens:
  190. return cron_overview_lines()
  191. subcommand, opts = tokens[0].lower(), _parse_cron_flags(tokens[1:])
  192. if opts is None:
  193. return [_t("cron.repeat_must_be_integer")]
  194. handler = _CRON_SUBCOMMANDS.get(subcommand)
  195. if handler is None:
  196. return [_t("cron.unknown_command", subcommand=subcommand), f" {_t('cron.available')}"]
  197. return handler(subcommand, opts)