cronjob_job_args.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. """Cron job argument normalization, validation and result shaping (re-exported by
  2. tools/cronjob_tools.py)."""
  3. import contextlib
  4. import logging
  5. from datetime import datetime, timedelta
  6. from typing import Any, Dict, List, Optional, Union
  7. from cron.jobs import effective_job_state
  8. import hermes_time
  9. # Logger parity with the origin module.
  10. logger = logging.getLogger("tools.cronjob_tools")
  11. # A one-shot firing within this many minutes is still part of the conversation that created it:
  12. # with platforms.slack.extra.reply_in_thread at its default true, the whole exchange under a
  13. # top-level message lives in the thread keyed on that message's own id.
  14. _THREAD_HORIZON_MINUTES = 60
  15. def _first_fire_within_thread_horizon(
  16. schedule: str | dict[str, Any] | None,
  17. ) -> bool:
  18. """True when the job's first fire is close enough that the creating conversation is still
  19. alive when it happens. Only near one-shots qualify; recurring jobs and one-shots beyond the
  20. horizon outlive the conversation, which is what the synthetic-drop rule protects."""
  21. if not schedule:
  22. return False
  23. parsed: Optional[dict[str, Any]]
  24. if isinstance(schedule, dict):
  25. parsed = schedule
  26. else:
  27. parsed = None
  28. with contextlib.suppress(Exception):
  29. from cron.jobs import parse_schedule
  30. parsed = parse_schedule(schedule)
  31. if not isinstance(parsed, dict) or parsed.get("kind") != "once":
  32. return False
  33. run_at = parsed.get("run_at")
  34. if not run_at:
  35. return False
  36. try:
  37. fire_at = datetime.fromisoformat(str(run_at))
  38. except ValueError:
  39. return False
  40. now = hermes_time.now()
  41. if fire_at.tzinfo is None:
  42. fire_at = fire_at.replace(tzinfo=now.tzinfo)
  43. # Bounded interval: an already-expired run_at gives a negative delta that would
  44. # otherwise sail through a bare upper bound — a conversation that is already over
  45. # must fail closed to the channel-level drop, while a fire at this instant still
  46. # happens inside the live conversation and keeps the thread.
  47. delta = fire_at - now
  48. return timedelta(0) <= delta <= timedelta(minutes=_THREAD_HORIZON_MINUTES)
  49. def _origin_from_env(
  50. schedule: str | dict[str, Any] | None = None,
  51. ) -> Optional[dict[str, str]]:
  52. from gateway.session_context import async_delivery_supported, get_session_env
  53. origin_platform = get_session_env("HERMES_SESSION_PLATFORM")
  54. origin_chat_id = get_session_env("HERMES_SESSION_CHAT_ID")
  55. if not (origin_platform and origin_chat_id):
  56. return None
  57. # A non-push surface (api_server: request/response, ``send()`` is a stub) cannot receive a
  58. # fire-time report, so an origin stamp would make ``deliver=origin`` fail silently on every
  59. # fire (#69304). No origin => the home-channel fallback + creation-time notice apply.
  60. if not async_delivery_supported():
  61. return None
  62. thread_id = get_session_env("HERMES_SESSION_THREAD_ID") or None
  63. # Slack stamps every TOP-LEVEL message's own id as the session thread (a per-message
  64. # KEY, not a location); persisting it would pin all future deliveries inside an
  65. # ephemeral thread, so thread == creating message id is synthetic and dropped — unless
  66. # the job's first fire is within the conversation's remaining lifetime: under the
  67. # default reply_in_thread the exchange under a top-level message lives in exactly that
  68. # thread, so a near one-shot must deliver back into it.
  69. if thread_id and origin_platform == "slack":
  70. message_id = get_session_env("HERMES_SESSION_MESSAGE_ID") or None
  71. if message_id and str(thread_id) == str(message_id):
  72. if _first_fire_within_thread_horizon(schedule):
  73. logger.debug(
  74. "Cron origin: keeping synthetic Slack thread_id=%s — first fire is "
  75. "within the conversation horizon",
  76. thread_id,
  77. )
  78. else:
  79. logger.debug(
  80. "Cron origin: dropping synthetic per-message Slack "
  81. "thread_id=%s (== creation message id)",
  82. thread_id,
  83. )
  84. thread_id = None
  85. if thread_id:
  86. logger.debug(
  87. "Cron origin captured thread_id=%s for %s:%s",
  88. thread_id, origin_platform, origin_chat_id)
  89. return {
  90. "platform": origin_platform, "chat_id": origin_chat_id,
  91. "chat_name": get_session_env("HERMES_SESSION_CHAT_NAME") or None, "thread_id": thread_id,
  92. # Lets a delivery mirror resolve the participant's session in per-user-isolated groups.
  93. "user_id": get_session_env("HERMES_SESSION_USER_ID") or None,
  94. # Workspace/server scope (Slack team, Discord guild...): Slack session keys embed it,
  95. # so a continuable cron seed built without it would never resolve a scoped reply.
  96. "scope_id": get_session_env("HERMES_SESSION_SCOPE_ID") or None,
  97. }
  98. def _local_delivery_notice(job: dict[str, Any], user_deliver: Optional[str]) -> Optional[str]:
  99. """Notice when a created job won't deliver anywhere: CLI/TUI sessions have no capturable
  100. origin, so deliver='origin' (or omitted) saves output but never delivers it. None when the
  101. user explicitly asked for ``local`` or the job resolves to a real target.
  102. TUI/CLI sessions cannot be captured as a cron ``origin`` (no ``HERMES_SESSION_PLATFORM``/``CHAT_ID`` is
  103. set for them), so a ``deliver="origin"`` request — or an omitted ``deliver`` that defaults to
  104. origin-or-local — produces a job that runs and saves output to ``last_output`` but is never delivered
  105. back into the session. This is by design (there is no live-delivery channel for local sessions), but
  106. silently dropping the user's "tell me when it runs" intent is the trap reported in 51568. Surface it at
  107. create time so the agent can relay it instead of promising a delivery that never happens. See #51568.
  108. """
  109. if (user_deliver or "").strip().lower() == "local":
  110. return None
  111. try:
  112. from cron.scheduler import _resolve_delivery_targets
  113. targets = _resolve_delivery_targets(job)
  114. if targets:
  115. # _origin_from_env() dropped a non-push origin (api_server) and the job rerouted to a
  116. # home channel: tell the creating client where the report goes (#69304).
  117. from gateway.session_context import async_delivery_supported, get_session_env
  118. fallback = [t for t in targets if t.get("_resolved_from") == "origin_fallback"]
  119. if fallback and get_session_env("HERMES_SESSION_PLATFORM") and not async_delivery_supported():
  120. return ("Note: this stateless HTTP API session cannot receive cron delivery, so this "
  121. f"job will report to the home channel {fallback[0]['platform']}:"
  122. f"{fallback[0]['chat_id']} instead of back here.")
  123. return None
  124. except Exception: # resolution unavailable — fall back to the origin signal
  125. if job.get("origin"):
  126. return None
  127. return (
  128. "This is a local-only cron job: its output is saved (view it with "
  129. "cronjob(action='list')) but will NOT be delivered back into this "
  130. "session — CLI/TUI and stateless HTTP API sessions have no live-delivery channel. To be "
  131. "notified when it runs, recreate or update the job with deliver set to "
  132. "a gateway-connected platform, e.g. deliver='telegram' or deliver='all'.")
  133. def _mode_guidance_notes(job: dict[str, Any], user_deliver: Optional[str]) -> list[str]:
  134. """Mode guidance echoed once in the create/update response (not in the schema, which is
  135. paid for on every API call)."""
  136. notes: list[str] = []
  137. if job.get("monitor_script") or job.get("monitor_url"):
  138. notes.append(
  139. "Monitor mode: the source runs first each tick and its output is "
  140. "hashed as exact bytes — unchanged output suppresses the agent run "
  141. "(silent no_change tick), changed output injects a MONITOR CHANGE "
  142. "DETECTED diff into the prompt. The first tick always runs as "
  143. "baseline. The source must emit STABLE output (no timestamps, no "
  144. "random ordering) or every tick will look changed.")
  145. if job.get("no_agent"):
  146. notes.append(
  147. "no_agent mode: stdout is delivered verbatim; EMPTY stdout sends "
  148. "nothing at all (watchdog pattern — script should stay quiet when "
  149. "there is nothing to report). Non-zero exit or timeout sends an "
  150. "error alert. prompt/skills are ignored.")
  151. _deliver = (user_deliver or "").strip().lower()
  152. if _deliver:
  153. if "all" in _deliver.split(","):
  154. notes.append(
  155. "deliver='all' resolves at fire time and never includes "
  156. "bot-chat targets — channels connected later are picked up "
  157. "automatically.")
  158. if _deliver.startswith("bot-chat:"):
  159. notes.append("Targeting another profile's Bot Chat costs that bot an agent turn per run.")
  160. # platform:chat_id with no thread segment loses topic targeting.
  161. for target in _deliver.split(","):
  162. parts = target.strip().split(":")
  163. if (
  164. len(parts) == 2
  165. and parts[0] not in ("bot-chat", "room", "sms")
  166. and parts[1]
  167. and not parts[1].startswith("#")):
  168. notes.append(
  169. f"deliver target '{target.strip()}' has no :thread_id "
  170. "segment — on thread/topic platforms the delivery lands in "
  171. "the main chat, not a topic.")
  172. break
  173. return notes
  174. def _split_monitor_arg(
  175. monitor: Optional[str],
  176. monitor_script: Optional[str],
  177. monitor_url: Optional[str]) -> tuple:
  178. """Resolve the model-facing ``monitor`` field into the stored ``(monitor_script,
  179. monitor_url)`` pair. http(s):// is a URL, anything else a script path (a legal script path
  180. never starts with a URL scheme). None = unchanged, '' = clear; setting one source clears
  181. the other so switching transports never trips mutual exclusion; an explicit ``monitor``
  182. wins over the legacy alias fields."""
  183. if monitor is None:
  184. return monitor_script, monitor_url
  185. value = monitor.strip()
  186. if not value:
  187. return "", ""
  188. if value.lower().startswith(("http://", "https://")):
  189. return "", value
  190. return value, ""
  191. def _repeat_display(job: dict[str, Any]) -> str:
  192. rep = job.get("repeat") or {}
  193. times, completed = rep.get("times"), rep.get("completed", 0)
  194. if times is None:
  195. return "forever"
  196. if times == 1:
  197. return "once" if completed == 0 else "1/1"
  198. return f"{completed}/{times}" if completed else f"{times} times"
  199. def _clean_str_list(items: Any) -> list[str]:
  200. """Stripped, non-empty ``str(item)`` values from a str-or-iterable (order kept)."""
  201. if items is None:
  202. return []
  203. if isinstance(items, str):
  204. items = [items]
  205. return [s for s in (str(i).strip() for i in items) if s]
  206. def _canonical_skills(skill: Optional[str] = None, skills: Optional[Any] = None) -> list[str]:
  207. if skills is None:
  208. skills = [skill] if skill else []
  209. elif isinstance(skills, str):
  210. skills = [skills]
  211. # `item or ""`: a None entry must drop out, not stringify to "None".
  212. return list(dict.fromkeys(_clean_str_list(item or "" for item in skills)))
  213. def _normalize_optional_job_value(value: Optional[Any], *, strip_trailing_slash: bool = False) -> Optional[str]:
  214. if value is None:
  215. return None
  216. text = str(value).strip()
  217. if strip_trailing_slash:
  218. text = text.rstrip("/")
  219. return text or None
  220. def _normalize_deliver_param(value: Any) -> Optional[str]:
  221. """Canonical string form of ``deliver``; None for None/empty. MCP clients may pass a list
  222. (``["telegram"]``) which the scheduler's ``str(deliver).split(",")`` would mangle."""
  223. if value is None:
  224. return None
  225. if isinstance(value, (list, tuple)):
  226. return ",".join(_clean_str_list(value)) or None
  227. return str(value).strip() or None
  228. def _validate_bot_chat_deliver(deliver: Optional[str]) -> Optional[str]:
  229. """Validate ``bot-chat[:<profile>]`` deliver elements at create time: Bot Chat delivery is
  230. machine-local, so the profile must exist where the scheduler fires (Desktop rosters may
  231. show same-named profiles from other machines). Returns an error string or None."""
  232. if not deliver:
  233. return None
  234. try:
  235. from cron.scheduler_delivery import parse_bot_chat_deliver_token
  236. from hermes_cli.profiles import normalize_profile_name, profile_exists
  237. except Exception:
  238. return None # best-effort; resolution re-checks at fire time
  239. for part in str(deliver).split(","):
  240. profile_arg = parse_bot_chat_deliver_token(part.strip())
  241. if not profile_arg:
  242. continue # not a bot-chat token, or bare token (own profile)
  243. try:
  244. canon = normalize_profile_name(profile_arg)
  245. except Exception:
  246. return f"invalid bot-chat profile name '{profile_arg}'"
  247. if not profile_exists(canon):
  248. return (
  249. f"bot-chat delivery profile '{profile_arg}' not found on this "
  250. "gateway's machine. Bot Chat delivery is machine-local — use a "
  251. "profile that exists here (hermes profile list), or omit the "
  252. "name (deliver='bot-chat') for the job's own profile.")
  253. return None
  254. def _resolve_cron_context_deliver(deliver: Optional[str]) -> Optional[str]:
  255. """Resolve ``origin`` to a concrete target for creates made FROM a cron run (the creating
  256. session is ephemeral, so by fire time there is no origin). Non-cron sessions: unchanged.
  257. Cron sessions: ``origin`` (or omitted) becomes the creating run's ``platform:chat_id[:thread]``
  258. from HERMES_CRON_AUTO_DELIVER_*, or ``local`` when it has no concrete target; other
  259. elements pass through. Otherwise the scheduler would guess a home channel."""
  260. from gateway.session_context import get_session_env
  261. from utils import is_truthy_value
  262. if not is_truthy_value(get_session_env("HERMES_CRON_SESSION", "")):
  263. return deliver
  264. def _creator_target() -> str:
  265. platform = get_session_env("HERMES_CRON_AUTO_DELIVER_PLATFORM", "").strip()
  266. chat_id = get_session_env("HERMES_CRON_AUTO_DELIVER_CHAT_ID", "").strip()
  267. if not platform or not chat_id:
  268. return "local"
  269. thread_id = get_session_env("HERMES_CRON_AUTO_DELIVER_THREAD_ID", "").strip()
  270. return f"{platform}:{chat_id}:{thread_id}" if thread_id else f"{platform}:{chat_id}"
  271. if deliver is None:
  272. return _creator_target()
  273. resolved = [_creator_target() if p.lower() == "origin" else p for p in _clean_str_list(str(deliver).split(","))]
  274. # Order-preserving de-dup: 'origin,local' with a local creator -> 'local'.
  275. return ",".join(dict.fromkeys(resolved)) or None
  276. def _same_origin(base_url: str, configured: str) -> bool:
  277. """Origin (scheme, host, effective port) equality, as for any bearer secret moved to a
  278. new URL: a host-only or subdomain match would let a job send the stored key over plain
  279. HTTP, to another port, or to a host the operator never configured."""
  280. from utils import base_url_origin
  281. try:
  282. want, got = base_url_origin(configured), base_url_origin(base_url)
  283. except ValueError: # malformed URL (e.g. unclosed IPv6 bracket) cannot match
  284. return False
  285. return bool(want[1]) and got == want
  286. def _base_url_refused(bu: str, prov: str, why: str) -> str:
  287. """The one refusal wording for a base_url override; ``why`` names the endpoint rule."""
  288. return f"base_url {bu!r} is not allowed for provider {prov!r}. {why}"
  289. def _custom_stored_key_error(bu: str) -> Optional[str]:
  290. """Bare 'custom' is BYOK only while the runtime attaches no stored key. The resolver picks
  291. the host-gated env keys by HOSTNAME, so a base_url that would receive one must be an origin
  292. the operator or the provider registry names; pool and ``model.key_env`` keys already match
  293. their configured URL exactly."""
  294. from agent.secret_scope import get_secret_str
  295. from hermes_cli import runtime_provider as rp
  296. from hermes_cli.auth import PROVIDER_REGISTRY
  297. from hermes_constants import OPENROUTER_BASE_URL
  298. from utils import base_url_origin
  299. custom_why = (
  300. "A stored API key matches its hostname, and a stored credential may only be sent to a "
  301. "configured endpoint (same scheme, host and port); configure the endpoint as a custom "
  302. "provider to use it.")
  303. try: # a URL urlparse rejects (unclosed IPv6 bracket) would raise in the key lookup below
  304. base_url_origin(bu)
  305. except ValueError:
  306. return _base_url_refused(bu, "custom", "It is not a valid URL.")
  307. if not any(rp.has_usable_secret(key) for key in rp._host_gated_env_key_candidates(bu, ollama=True)):
  308. return None
  309. # The RAW configured model.base_url: _get_model_config() may network-probe a local model.
  310. cfg = rp.load_config()
  311. model_cfg = cfg.get("model")
  312. configured = [
  313. model_cfg.get("base_url") if isinstance(model_cfg, dict) else None,
  314. get_secret_str("OPENAI_BASE_URL", ""), OPENROUTER_BASE_URL,
  315. # PROVIDER_REGISTRY already carries the direct OpenAI origin (openai-api).
  316. *(getattr(p, "inference_base_url", "") for p in PROVIDER_REGISTRY.values()),
  317. *(entry.get("base_url") for entry in rp.get_compatible_custom_providers(cfg)),
  318. ]
  319. if any(_same_origin(bu, str(url)) for url in configured if url):
  320. return None
  321. return _base_url_refused(bu, "custom", custom_why)
  322. def _validate_cron_base_url(
  323. provider: Optional[Any], base_url: Optional[Any]) -> Optional[str]:
  324. """Reject pairing a stored credential with an off-origin base_url (a prompt-injected job
  325. could exfil the key). Allowed: no override; bare 'custom' while no stored key would go with
  326. it, or at a configured origin; an override with the same origin as the named provider's
  327. own endpoint. Everything else fails closed. Returns an error string if blocked, else None."""
  328. bu = _normalize_optional_job_value(base_url, strip_trailing_slash=True)
  329. if not bu:
  330. return None
  331. prov = _normalize_optional_job_value(provider)
  332. if not prov: # no provider inherits the default provider's stored key — same primitive
  333. return (
  334. "base_url override requires an explicit provider. Set provider to a "
  335. "configured custom provider to use a custom endpoint.")
  336. try:
  337. from hermes_cli.runtime_provider import (
  338. has_named_custom_provider,
  339. resolve_requested_provider,
  340. _get_named_custom_provider)
  341. from hermes_cli.auth import PROVIDER_REGISTRY
  342. except Exception:
  343. return f"Unable to validate base_url override for provider {prov!r}; refused."
  344. if prov.lower() == "custom":
  345. return _custom_stored_key_error(bu)
  346. if has_named_custom_provider(prov):
  347. # A NAMED custom provider's STORED key is still sent to an override base_url.
  348. try:
  349. cp = _get_named_custom_provider(prov)
  350. except Exception:
  351. cp = None
  352. cfg_url = str((cp or {}).get("base_url") or "")
  353. if cfg_url and _same_origin(bu, cfg_url):
  354. return None
  355. return _base_url_refused(
  356. bu, prov, "A named custom provider's stored credential may only be sent to its own "
  357. f"configured endpoint ({cfg_url or 'unknown'}): same scheme, host and port.")
  358. try:
  359. resolved = resolve_requested_provider(prov)
  360. except Exception:
  361. resolved = prov
  362. pconfig = PROVIDER_REGISTRY.get(resolved) if isinstance(resolved, str) else None
  363. known_url = str(getattr(pconfig, "inference_base_url", "") or "") if pconfig else ""
  364. if known_url and _same_origin(bu, known_url):
  365. return None
  366. # Fail closed: named providers with stored credentials AND unknown names we cannot origin-match.
  367. return _base_url_refused(
  368. bu, prov, "A named provider's stored credential may only be sent to its own endpoint "
  369. '(same scheme, host and port); use a configured custom provider (provider="custom") '
  370. "for a custom base_url.")
  371. def _validate_cron_script_path(script: Optional[str]) -> Optional[str]:
  372. """Scripts must be relative paths within HERMES_HOME/scripts/ (absolute / ~ / drive-letter
  373. rejected — prompt-injection guard). Error string if blocked, else None; empty = clear."""
  374. if not script or not script.strip():
  375. return None
  376. from hermes_constants import get_hermes_home
  377. raw = script.strip()
  378. scripts_dir = get_hermes_home() / "scripts"
  379. if raw.startswith(("/", "~")) or (len(raw) >= 2 and raw[1] == ":"):
  380. return (
  381. f"Script path must be relative to {scripts_dir}/. "
  382. f"Got absolute or home-relative path: {raw!r}. "
  383. f"Place scripts in {scripts_dir}/ and use just the filename.")
  384. from tools.path_security import validate_within_dir
  385. scripts_dir.mkdir(parents=True, exist_ok=True)
  386. resolved_script = scripts_dir / raw
  387. if validate_within_dir(resolved_script, scripts_dir):
  388. return f"Script path escapes the scripts directory via traversal: {raw!r}"
  389. if not resolved_script.is_file():
  390. return (
  391. f"Script file not found: {resolved_script}. "
  392. f"Create it in {scripts_dir}/ first.")
  393. return None
  394. def _apply_continuity(
  395. context_from: Optional[str | list[str]],
  396. continuity: bool) -> Optional[list[str]]:
  397. """continuity=True ensures "self" is in context_from; False removes it; others untouched."""
  398. refs = _clean_str_list(context_from)
  399. has_self = any(r.lower() == "self" for r in refs)
  400. if continuity and not has_self:
  401. refs.append("self")
  402. elif not continuity and has_self:
  403. refs = [r for r in refs if r.lower() != "self"]
  404. return refs or None
  405. def _validate_context_from_refs(refs: list[Any]) -> Optional[str]:
  406. """Error string if any non-"self" ref names a missing job ("self" resolves to the job's
  407. own id at run time, so it can't be checked — the job doesn't exist yet at create)."""
  408. from cron.jobs import get_job as _get_job
  409. for ref_id in refs:
  410. if isinstance(ref_id, str) and ref_id.strip().lower() == "self":
  411. continue
  412. if not _get_job(ref_id):
  413. return (
  414. f"context_from job '{ref_id}' not found. "
  415. "Use cronjob(action='list') to see available jobs.")
  416. return None
  417. # Optional fields echoed by _format_job only when truthy (order = JSON key order).
  418. _FORMAT_JOB_OPTIONAL_KEYS = (
  419. "script", "reasoning_effort", "monitor_script", "monitor_url",
  420. "monitor_state", "no_agent", "enabled_toolsets", "workdir", "interpreter")
  421. def _format_job(job: dict[str, Any]) -> dict[str, Any]:
  422. from agent.redact import redact_sensitive_text
  423. prompt = str(job.get("prompt") or "")
  424. skills = _canonical_skills(job.get("skill"), job.get("skills"))
  425. job_id = str(job.get("id") or "unknown")
  426. name = str(job.get("name") or prompt[:50] or (skills[0] if skills else "") or job_id or "cron job")
  427. result = {
  428. "job_id": job_id,
  429. "name": name,
  430. "skill": skills[0] if skills else None,
  431. "skills": skills,
  432. "prompt_preview": prompt[:100] + "..." if len(prompt) > 100 else prompt,
  433. "model": job.get("model"),
  434. "provider": job.get("provider"),
  435. # Locked to its own model; unpinned jobs follow cron.model, then the main agent model.
  436. "pinned": bool(str(job.get("model") or "").strip()),
  437. "base_url": job.get("base_url"),
  438. "schedule": job.get("schedule_display") or "?",
  439. "repeat": _repeat_display(job),
  440. "deliver": job.get("deliver", "local"),
  441. "next_run_at": job.get("next_run_at"),
  442. "last_run_at": job.get("last_run_at"),
  443. "last_status": job.get("last_status"),
  444. "last_delivery_error": job.get("last_delivery_error"),
  445. "last_delivery_unverified": job.get("last_delivery_unverified"),
  446. "last_fire_error": job.get("last_fire_error"),
  447. "last_error": redact_sensitive_text(
  448. job["last_error"], force=True, redact_url_credentials=True,
  449. ) if job.get("last_error") else job.get("last_error"),
  450. "enabled": job.get("enabled", True),
  451. # Derive from enabled so half-paused records never render as paused.
  452. "state": effective_job_state(job),
  453. "paused_at": job.get("paused_at"),
  454. "paused_reason": job.get("paused_reason"),
  455. }
  456. for key in _FORMAT_JOB_OPTIONAL_KEYS:
  457. if job.get(key):
  458. result[key] = True if key == "no_agent" else job[key]
  459. stored_refs = job.get("context_from") or []
  460. if isinstance(stored_refs, str):
  461. stored_refs = [stored_refs]
  462. is_self = lambda r: str(r).strip().lower() == "self" or r == job.get("id")
  463. if any(is_self(r) for r in stored_refs):
  464. result["continuity"] = True
  465. external_refs = [r for r in stored_refs if not is_self(r)]
  466. if external_refs:
  467. result["context_from"] = external_refs
  468. if isinstance(job.get("attach_to_session"), bool):
  469. result["attach_to_session"] = job["attach_to_session"]
  470. return result
  471. def _gateway_liveness_notice(plural: bool = False) -> dict:
  472. """``gateway_running``/``warning`` payload via the shared CLI helper so CLI and tool agree
  473. on "scheduler active". False -> warning (no gateway process), None -> probe failed.
  474. Thin adapter over the shared CLI helper ``hermes_cli.cron._builtin_gateway_liveness`` (#87033) so the
  475. CLI and this tool can never disagree about what "scheduler active" means. ``plural`` rewords the warning
  476. for multi-job results (the ``list`` action).
  477. """
  478. try:
  479. from hermes_cli.cron import _builtin_gateway_liveness
  480. _gw = _builtin_gateway_liveness()
  481. except Exception:
  482. return {"gateway_running": None}
  483. if _gw is False:
  484. subject = "these jobs are saved" if plural else "this job is saved"
  485. return {
  486. "gateway_running": False,
  487. "warning": (
  488. f"The Hermes gateway is not running — {subject} "
  489. "but will NOT fire until the gateway is started "
  490. "(hermes gateway install / hermes gateway start). "
  491. "Tell the user the task is scheduled but not active yet."),
  492. }
  493. return {"gateway_running": None if _gw is None else True}