loops.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. """Recurring in-session wakeups — the /loop command (Claude Code parity).
  2. A loop stops when the agent ends a wakeup reply with ``LOOP_COMPLETE`` on its own line, when
  3. ``--times N`` ticks have fired, when the ``--until`` judge rules the condition met, or when the
  4. ``loops.max_ticks`` backstop pauses it. State lives in SessionDB ``state_meta`` (same contract as
  5. ``hermes_cli/goals.py``); CLI, gateway, and TUI all drive it through :class:`LoopManager`.
  6. """
  7. from __future__ import annotations
  8. import hashlib
  9. import json
  10. import logging
  11. import re
  12. import time
  13. from dataclasses import dataclass, field, fields, asdict
  14. from typing import Any, Dict, List, Optional, Tuple
  15. logger = logging.getLogger(__name__)
  16. # Floor for fixed intervals. Claude Code allows 30s; anything tighter is almost always an
  17. # accident that burns tokens polling unchanged state. Config loops.min_interval_seconds (clamped ≥ 5).
  18. DEFAULT_MIN_INTERVAL_SECONDS = 30
  19. # Backstop tick budget so an unattended loop can't run forever. 0 = unlimited; config loops.max_ticks.
  20. DEFAULT_MAX_TICKS = 100
  21. # Self-paced mode: start at the floor, double while replies are unchanged, cap at the
  22. # ceiling, snap back to the floor on any change.
  23. DEFAULT_SELF_PACED_FLOOR_SECONDS = 60
  24. DEFAULT_SELF_PACED_CEILING_SECONDS = 15 * 60
  25. # Completion sentinel the wakeup prompt teaches the agent to emit.
  26. LOOP_COMPLETE_MARKER = "LOOP_COMPLETE"
  27. # Marker on its own line, tolerating surrounding whitespace / trailing punctuation.
  28. _LOOP_COMPLETE_RE = re.compile(
  29. r"(?im)^\s*" + re.escape(LOOP_COMPLETE_MARKER) + r"\s*[.!]?\s*$"
  30. )
  31. # Interval token: 30s / 5m / 2h / 1h30m (compound units allowed, at least one).
  32. _INTERVAL_TOKEN_RE = re.compile(
  33. r"^(?=\d)(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$", re.IGNORECASE
  34. )
  35. WAKEUP_PROMPT_TEMPLATE = (
  36. "[/loop wakeup #{tick}{cadence}]\n"
  37. "Recurring task: {prompt}\n\n"
  38. "This is an automatic wakeup from the /loop the user set. Perform the "
  39. "task now against the CURRENT state (re-check files, processes, or "
  40. "services fresh — do not assume anything from earlier iterations still "
  41. "holds). Report concisely what you found or did this iteration.\n"
  42. "If the task is now complete, no longer applicable, or the thing you "
  43. "were watching has finished, say so and end your reply with "
  44. f"{LOOP_COMPLETE_MARKER} on its own line — that stops the loop."
  45. )
  46. WAKEUP_PROMPT_WITH_UNTIL_TEMPLATE = (
  47. "[/loop wakeup #{tick}{cadence}]\n"
  48. "Recurring task: {prompt}\n\n"
  49. "Stop condition: {until}\n\n"
  50. "This is an automatic wakeup from the /loop the user set. Perform the "
  51. "task now against the CURRENT state (re-check files, processes, or "
  52. "services fresh — do not assume anything from earlier iterations still "
  53. "holds). Report concisely what you found or did this iteration, and "
  54. "show concrete evidence of the stop condition's status.\n"
  55. "If the stop condition is met, or the task is no longer applicable, say "
  56. f"so and end your reply with {LOOP_COMPLETE_MARKER} on its own line — "
  57. "that stops the loop."
  58. )
  59. def parse_interval_token(token: str) -> Optional[int]:
  60. """Total seconds for ``30s``/``5m``/``2h``/``1h30m``, else None.
  61. A bare number is NOT an interval (it collides with prompt text like ``/loop 3 things``).
  62. """
  63. m = _INTERVAL_TOKEN_RE.match(token.strip()) if token else None
  64. if not m:
  65. return None
  66. h, mnt, s = (int(g) if g else 0 for g in m.groups())
  67. total = h * 3600 + mnt * 60 + s
  68. return total if total > 0 else None
  69. def parse_loop_args(text: str) -> dict[str, Any]:
  70. """Parse ``/loop [interval] <prompt> [--times N] [--until ...]``.
  71. Returns ``{"interval_seconds": int|None, "prompt", "times", "until", "error"}``;
  72. ``interval_seconds`` None means self-paced, ``error`` is set for unusable input.
  73. """
  74. raw = (text or "").strip()
  75. result: dict[str, Any] = {"interval_seconds": None, "prompt": "", "times": 0, "until": "", "error": None}
  76. if not raw:
  77. return {**result, "error": "empty"}
  78. # Pull trailing flags first so an interval-looking token inside the --until clause can't
  79. # confuse the front parse. --until consumes to end-of-line (or to a following --times).
  80. times, until = 0, ""
  81. m_times = re.search(r"\s--times\s+(\S+)", raw)
  82. if m_times:
  83. try:
  84. times = int(m_times.group(1))
  85. if times < 1:
  86. raise ValueError
  87. except ValueError:
  88. return {**result, "error": f"--times expects a positive integer, got {m_times.group(1)!r}"}
  89. raw = (raw[: m_times.start()] + raw[m_times.end():]).strip()
  90. m_until = re.search(r"\s--until\s+(.+)$", raw, re.DOTALL)
  91. if m_until:
  92. until = m_until.group(1).strip()
  93. raw = raw[: m_until.start()].strip()
  94. # Leading "every" sugar: /loop every 5m <prompt>
  95. tokens = raw.split(None, 1)
  96. if tokens and tokens[0].lower() == "every" and len(tokens) > 1:
  97. raw = tokens[1]
  98. tokens = raw.split(None, 1)
  99. interval = parse_interval_token(tokens[0]) if tokens else None
  100. if interval is not None:
  101. raw = tokens[1].strip() if len(tokens) > 1 else ""
  102. if not raw:
  103. return {**result, "error": "missing prompt (usage: /loop [interval] <prompt>)"}
  104. return {**result, "interval_seconds": interval, "prompt": raw, "times": times, "until": until}
  105. def format_interval(seconds: float) -> str:
  106. """Render seconds as a compact human interval (``90`` → ``1m30s``)."""
  107. h, rem = divmod(int(max(0, round(seconds))), 3600)
  108. m, s = divmod(rem, 60)
  109. parts = [f"{h}h"] if h else []
  110. if m:
  111. parts.append(f"{m}m")
  112. if s or not parts:
  113. parts.append(f"{s}s")
  114. return "".join(parts)
  115. def _loops_config() -> dict[str, Any]:
  116. try:
  117. from hermes_cli.config import load_config
  118. section = (load_config() or {}).get("loops") or {}
  119. return section if isinstance(section, dict) else {}
  120. except Exception:
  121. return {}
  122. def _config_int(key: str, default: int, floor: int) -> int:
  123. """``loops.<key>`` as an int clamped to ``floor``; ``default`` on any bad value."""
  124. try:
  125. return max(floor, int(_loops_config().get(key, default)))
  126. except Exception:
  127. return default
  128. def min_interval_seconds() -> int:
  129. return _config_int("min_interval_seconds", DEFAULT_MIN_INTERVAL_SECONDS, 5)
  130. def max_ticks_default() -> int:
  131. return _config_int("max_ticks", DEFAULT_MAX_TICKS, 0)
  132. def self_paced_floor_seconds() -> int:
  133. return _config_int("self_paced_floor_seconds", DEFAULT_SELF_PACED_FLOOR_SECONDS, 10)
  134. def self_paced_ceiling_seconds() -> int:
  135. floor = self_paced_floor_seconds()
  136. return _config_int("self_paced_ceiling_seconds", max(floor, DEFAULT_SELF_PACED_CEILING_SECONDS), floor)
  137. @dataclass
  138. class LoopState:
  139. """Serializable /loop state stored per session."""
  140. prompt: str
  141. status: str = "active" # active | paused | done | cleared
  142. mode: str = "interval" # interval | self_paced
  143. interval_seconds: float = 0.0 # fixed cadence (mode == "interval")
  144. current_delay: float = 0.0 # live cadence (self-paced backoff)
  145. times: int = 0 # user cap (--times N); 0 = none
  146. until: str = "" # judged stop condition; "" = none
  147. max_ticks: int = DEFAULT_MAX_TICKS # config backstop; 0 = unlimited
  148. ticks_fired: int = 0
  149. created_at: float = 0.0
  150. last_fired_at: float = 0.0
  151. next_due_at: float = 0.0
  152. # True between "wakeup injected" and "that turn's response evaluated": stops a tick from
  153. # double-firing mid-turn and tells the post-turn hook the turn that just ended was ours.
  154. awaiting_response: bool = False
  155. last_response_digest: str = "" # self-paced change detection
  156. paused_reason: Optional[str] = None
  157. last_stop_reason: Optional[str] = None
  158. # Gateway routing (platform / chat_id / chat_type / thread_id) captured at creation so the
  159. # idle watcher can inject ticks into the right chat. Empty for CLI/TUI (own schedulers).
  160. route: dict[str, str] = field(default_factory=dict)
  161. def to_json(self) -> str:
  162. return json.dumps(asdict(self), ensure_ascii=False)
  163. @classmethod
  164. def from_json(cls, raw: str) -> LoopState:
  165. data = json.loads(raw)
  166. route = data.get("route")
  167. kwargs: dict[str, Any] = {
  168. "prompt": data.get("prompt", ""),
  169. "status": data.get("status", "active"),
  170. "mode": data.get("mode", "interval"),
  171. "paused_reason": data.get("paused_reason"),
  172. "last_stop_reason": data.get("last_stop_reason"),
  173. "route": route if isinstance(route, dict) else {},
  174. }
  175. # Remaining scalar fields: missing key -> dataclass default; present-but-falsy -> type zero.
  176. casts = {"str": str, "int": int, "float": float, "bool": bool}
  177. for f in fields(cls):
  178. if f.name not in kwargs:
  179. kwargs[f.name] = casts[f.type](data.get(f.name, f.default) or casts[f.type]())
  180. return cls(**kwargs)
  181. def cadence_label(self) -> str:
  182. if self.mode == "self_paced":
  183. live = f", currently {format_interval(self.current_delay)}" if self.current_delay else ""
  184. return f"self-paced{live}"
  185. return f"every {format_interval(self.interval_seconds)}"
  186. def remaining_label(self) -> str:
  187. if self.status != "active":
  188. return ""
  189. remaining = self.next_due_at - time.time()
  190. return "due now" if remaining <= 0 else f"next in {format_interval(remaining)}"
  191. _META_PREFIX = "loop:"
  192. def _meta_key(session_id: str) -> str:
  193. return f"{_META_PREFIX}{session_id}"
  194. def _get_session_db() -> Optional[Any]:
  195. """The goals module's cached SessionDB, so goals/loops/heartbeats share one connection and
  196. its off-loop bootstrap (a cold cache on the loop thread never runs ``SessionDB()`` inline).
  197. The previous copy here did, which froze the loop for the init duration and dropped the first ``loop:*``
  198. write (the /goal bug class, #88965).
  199. """
  200. try:
  201. from hermes_cli.goals import _get_session_db as _goals_db
  202. except Exception as exc: # pragma: no cover
  203. logger.debug("LoopManager: SessionDB bootstrap failed (%s)", exc)
  204. return None
  205. return _goals_db()
  206. def _db_op(label: str, fn, default=None):
  207. """Run one SessionDB call; any error is logged at debug and yields ``default``."""
  208. try:
  209. return fn()
  210. except Exception as exc:
  211. logger.debug("LoopManager: %s failed: %s", label, exc)
  212. return default
  213. def _parse_state(raw: str, session_id: str = "") -> Optional[LoopState]:
  214. """``LoopState`` from stored JSON; None (warning when *session_id* given) on corrupt data."""
  215. try:
  216. return LoopState.from_json(raw)
  217. except Exception as exc:
  218. if session_id:
  219. logger.warning("LoopManager: could not parse stored loop for %s: %s", session_id, exc)
  220. return None
  221. def load_loop(session_id: str) -> Optional[LoopState]:
  222. """Load the loop for a session, or None if none exists."""
  223. db = _get_session_db() if session_id else None
  224. if db is None:
  225. return None
  226. raw = _db_op("get_meta", lambda: db.get_meta(_meta_key(session_id)))
  227. return _parse_state(raw, session_id) if raw else None
  228. def save_loop(session_id: str, state: LoopState) -> None:
  229. """Persist a loop to SessionDB. No-op if DB unavailable."""
  230. if not session_id:
  231. return
  232. db = _get_session_db()
  233. if db is None:
  234. from hermes_cli.goals import _warn_dropped_write
  235. _warn_dropped_write("LoopManager", "loop", session_id)
  236. return
  237. _db_op("set_meta", lambda: db.set_meta(_meta_key(session_id), state.to_json()))
  238. def clear_loop(session_id: str) -> None:
  239. """Mark a loop cleared in the DB (preserved for audit, status=cleared)."""
  240. state = load_loop(session_id)
  241. if state is not None:
  242. state.status = "cleared"
  243. save_loop(session_id, state)
  244. def list_active_loops() -> list[tuple[str, LoopState]]:
  245. """``[(session_id, LoopState), ...]`` for every ACTIVE loop; ``[]`` on any DB error.
  246. Used by the gateway's idle wakeup watcher, which scans for due loops on a coarse tick.
  247. """
  248. db = _get_session_db()
  249. if db is None:
  250. return []
  251. out: list[tuple[str, LoopState]] = []
  252. for key, raw in _db_op("list_meta_prefix", lambda: db.list_meta_prefix(_META_PREFIX), []):
  253. session_id = key[len(_META_PREFIX):]
  254. state = _parse_state(raw) if session_id and raw else None
  255. if state is not None and state.status == "active":
  256. out.append((session_id, state))
  257. return out
  258. def store_has_active_loop(db: Any) -> bool:
  259. """True when *db* holds an ACTIVE ``loop:*`` row — or a row that cannot be parsed (unknown, so the
  260. caller keeps its full scan). Unlike :func:`list_active_loops` this takes the store explicitly and
  261. propagates read errors, so an idle gate can tell "empty" from "unavailable"."""
  262. for key, raw in db.list_meta_prefix(_META_PREFIX):
  263. state = _parse_state(raw, key[len(_META_PREFIX):]) if raw else None
  264. if state is None or state.status == "active":
  265. return True
  266. return False
  267. def migrate_loop_to_session(old_session_id: str, new_session_id: str, *, reason: str = "") -> bool:
  268. """Carry a /loop from a parent session to its continuation. Best-effort, never raises.
  269. Context compression rotates ``session_id`` to a fresh child; without this the loop silently
  270. dies at the compaction boundary.
  271. Copies the loop onto the new session and archives the old row as ``cleared`` so exactly one active loop
  272. row exists per logical conversation. See #33618.
  273. """
  274. if not old_session_id or not new_session_id or old_session_id == new_session_id:
  275. return False
  276. try:
  277. state = load_loop(old_session_id)
  278. if state is None or state.status == "cleared" or load_loop(new_session_id) is not None:
  279. return False
  280. save_loop(new_session_id, state)
  281. clear_loop(old_session_id)
  282. logger.debug(
  283. "LoopManager: migrated loop %s -> %s (%s)",
  284. old_session_id, new_session_id, reason or "rotation",
  285. )
  286. return True
  287. except Exception as exc: # pragma: no cover - defensive
  288. logger.debug("LoopManager: loop migration failed: %s", exc)
  289. return False
  290. def _ticks_label(n: int) -> str:
  291. return f"{n} tick{'s' if n != 1 else ''}"
  292. def _dash(reason: Optional[str]) -> str:
  293. return f" — {reason}" if reason else ""
  294. def response_signals_complete(response: str) -> bool:
  295. """True when the agent ended its reply with the LOOP_COMPLETE marker."""
  296. return bool(response) and _LOOP_COMPLETE_RE.search(response) is not None
  297. def _digest_response(response: str) -> str:
  298. """Digest for self-paced change detection; whitespace-normalized with clock/timestamp/duration
  299. tokens stripped so 'checked at 14:02:33' doesn't defeat the backoff."""
  300. text = (response or "").strip().lower()
  301. text = re.sub(r"\d{1,2}:\d{2}(:\d{2})?", "", text)
  302. text = re.sub(r"\d{4}-\d{2}-\d{2}", "", text)
  303. text = re.sub(r"\b\d+(\.\d+)?\s*(s|sec|secs|seconds|m|min|mins|minutes|h|hr|hrs|hours)\b", "", text)
  304. text = re.sub(r"\s+", " ", text)
  305. return hashlib.sha256(text.encode("utf-8", "replace")).hexdigest()
  306. class LoopManager:
  307. """Per-session /loop state + tick decisions.
  308. Drivers call ``set``/``pause``/``resume``/``clear`` for user controls, ``is_due()`` (cheap,
  309. in-memory), ``fire_tick()`` to claim a tick and get the wakeup message, ``complete_tick()`` to
  310. evaluate the finished turn, and ``status_line()``.
  311. """
  312. def __init__(self, session_id: str):
  313. self.session_id = session_id
  314. self._state: Optional[LoopState] = load_loop(session_id)
  315. @property
  316. def state(self) -> Optional[LoopState]:
  317. return self._state
  318. def refresh(self) -> None:
  319. """Re-read state from the DB (cross-process safety for the gateway)."""
  320. self._state = load_loop(self.session_id)
  321. def is_active(self) -> bool:
  322. return self._state is not None and self._state.status == "active"
  323. def has_loop(self) -> bool:
  324. return self._state is not None and self._state.status in {"active", "paused"}
  325. def _save(self) -> LoopState:
  326. save_loop(self.session_id, self._state)
  327. return self._state
  328. def status_line(self) -> str:
  329. s = self._state
  330. if s is None or s.status == "cleared":
  331. return "No loop set. Start one with /loop [interval] <prompt>."
  332. fired = _ticks_label(s.ticks_fired)
  333. if s.times:
  334. caps = [f"{s.ticks_fired}/{s.times} runs"]
  335. elif s.max_ticks:
  336. caps = [f"{s.ticks_fired}/{s.max_ticks} budget"]
  337. else:
  338. caps = [fired]
  339. if s.until:
  340. caps.append(f"until: {s.until}")
  341. meta = f"{s.cadence_label()}, {', '.join(caps)}"
  342. if s.status == "active":
  343. remaining = s.remaining_label()
  344. tail = ", wakeup running" if s.awaiting_response else (f", {remaining}" if remaining else "")
  345. return f"↻ Loop (active, {meta}{tail}): {s.prompt}"
  346. if s.status == "paused":
  347. return f"⏸ Loop (paused, {meta}{_dash(s.paused_reason)}): {s.prompt}"
  348. if s.status == "done":
  349. return f"✓ Loop finished ({fired}{_dash(s.last_stop_reason)}): {s.prompt}"
  350. return f"Loop ({s.status}, {meta}): {s.prompt}"
  351. def set(
  352. self,
  353. prompt: str,
  354. *,
  355. interval_seconds: Optional[int] = None,
  356. times: int = 0,
  357. until: str = "",
  358. route: Optional[dict[str, str]] = None,
  359. ) -> LoopState:
  360. """Start a new loop (replaces any existing one for the session)."""
  361. prompt = (prompt or "").strip()
  362. if not prompt:
  363. raise ValueError("loop prompt is empty")
  364. now = time.time()
  365. self_paced = interval_seconds is None
  366. interval = 0.0 if self_paced else float(max(int(interval_seconds), min_interval_seconds()))
  367. state = LoopState(
  368. prompt=prompt,
  369. mode="self_paced" if self_paced else "interval",
  370. interval_seconds=interval,
  371. current_delay=float(self_paced_floor_seconds()) if self_paced else interval,
  372. times=max(0, int(times or 0)),
  373. until=(until or "").strip(),
  374. max_ticks=max_ticks_default(),
  375. created_at=now,
  376. next_due_at=now,
  377. route=dict(route or {}),
  378. )
  379. self._state = state
  380. return self._save()
  381. def pause(self, reason: str = "user-paused") -> Optional[LoopState]:
  382. s = self._state
  383. if not s or s.status not in {"active", "paused"}:
  384. return None
  385. s.status, s.paused_reason, s.awaiting_response = "paused", reason, False
  386. return self._save()
  387. def resume(self) -> Optional[LoopState]:
  388. s = self._state
  389. if not s or s.status == "cleared":
  390. return None
  391. s.status, s.paused_reason, s.awaiting_response = "active", None, False
  392. # Re-arm relative to now so a long pause doesn't fire instantly N times.
  393. delay = s.current_delay or s.interval_seconds or self_paced_floor_seconds()
  394. s.next_due_at = time.time() + min(delay, 5.0)
  395. return self._save()
  396. def clear(self) -> bool:
  397. if self._state is None or self._state.status == "cleared":
  398. return False
  399. self._state.status = "cleared"
  400. self._save()
  401. self._state = None
  402. return True
  403. def is_due(self, now: Optional[float] = None) -> bool:
  404. """Cheap check: active, not mid-wakeup, and the clock has passed."""
  405. s = self._state
  406. return (
  407. s is not None and s.status == "active" and not s.awaiting_response
  408. and (now if now is not None else time.time()) >= s.next_due_at
  409. )
  410. def fire_tick(self) -> Optional[str]:
  411. """Claim a due tick; returns the message to inject, or None.
  412. The message is the wakeup-framed prompt, or the raw command when the loop's prompt is
  413. itself a slash command (``/loop 10m /recap``). Marks ``awaiting_response`` so the tick
  414. can't double-fire; drivers MUST follow up with ``complete_tick`` (or ``abandon_tick``).
  415. """
  416. s = self._state
  417. if s is None or not self.is_due():
  418. return None
  419. s.ticks_fired += 1
  420. s.last_fired_at = time.time()
  421. s.awaiting_response = True
  422. # Provisional schedule from NOW: complete_tick reschedules from turn end, but if the
  423. # process dies mid-turn this keeps the persisted loop from being 'due' in a tight loop.
  424. s.next_due_at = s.last_fired_at + (s.current_delay or s.interval_seconds or self_paced_floor_seconds())
  425. self._save()
  426. if s.prompt.lstrip().startswith("/"):
  427. return s.prompt.strip()
  428. cadence = f", {s.cadence_label()}" if s.mode == "interval" else ", self-paced"
  429. template = WAKEUP_PROMPT_WITH_UNTIL_TEMPLATE if s.until else WAKEUP_PROMPT_TEMPLATE
  430. return template.format(tick=s.ticks_fired, cadence=cadence, prompt=s.prompt, until=s.until)
  431. def abandon_tick(self) -> None:
  432. """Roll back a fired tick whose injection failed (nothing ran)."""
  433. s = self._state
  434. if s is None or not s.awaiting_response:
  435. return
  436. s.awaiting_response = False
  437. s.ticks_fired = max(0, s.ticks_fired - 1)
  438. self._save()
  439. def _stop(self, status: str, reason: str, message: str) -> dict[str, Any]:
  440. """Persist a terminal (``done``) or recoverable (``paused``) stop and build the result."""
  441. s = self._state
  442. s.status = status
  443. if status == "done":
  444. s.last_stop_reason = reason
  445. else:
  446. s.paused_reason = reason
  447. self._save()
  448. return {"status": status, "stopped": True, "reason": reason, "message": message}
  449. def complete_tick(self, last_response: str) -> dict[str, Any]:
  450. """Evaluate the finished wakeup turn and schedule what's next.
  451. Returns ``{"status": "active|done|paused", "stopped": bool, "reason": str, "message": str}``;
  452. ``message`` is a user-visible one-liner, "" in the common still-looping case.
  453. """
  454. s = self._state
  455. if s is None or not s.awaiting_response:
  456. return {"status": s.status if s else None, "stopped": False, "reason": "no tick in flight", "message": ""}
  457. s.awaiting_response = False
  458. now = time.time()
  459. ticks = _ticks_label(s.ticks_fired)
  460. # 1. Agent self-stop marker.
  461. if response_signals_complete(last_response):
  462. return self._stop("done", "agent signaled the task is complete",
  463. f"✓ Loop finished after {ticks} — task complete.")
  464. # 2. Evidence-based --until judge (reuses the /goal judge; fail-open).
  465. if s.until and (last_response or "").strip():
  466. try:
  467. from hermes_cli.goals import judge_goal
  468. verdict, reason, _pf, _wait, _tf = judge_goal(s.until, last_response)
  469. except Exception as exc:
  470. verdict, reason = "continue", f"judge unavailable: {type(exc).__name__}"
  471. if verdict == "done":
  472. return self._stop("done", f"stop condition met: {reason}",
  473. f"✓ Loop finished after {ticks} — {reason}")
  474. if verdict == "blocked":
  475. # Unachievable stop condition: pause so the user can re-scope, don't spin.
  476. why = f"stop condition judged unachievable: {reason}"
  477. return self._stop("paused", why,
  478. f"⏸ Loop paused — {why}. /loop resume to keep going, /loop stop to end it.")
  479. # 3. --times user cap.
  480. if s.times and s.ticks_fired >= s.times:
  481. return self._stop("done", f"completed the requested {s.times} runs",
  482. f"✓ Loop finished — ran {s.times}/{s.times} times.")
  483. # 4. Config backstop budget → pause (recoverable), not done.
  484. if s.max_ticks and s.ticks_fired >= s.max_ticks:
  485. return self._stop(
  486. "paused", f"tick budget exhausted ({s.ticks_fired}/{s.max_ticks})",
  487. f"⏸ Loop paused — {s.ticks_fired}/{s.max_ticks} ticks used "
  488. "(loops.max_ticks). /loop resume to keep going, /loop stop to end it.",
  489. )
  490. # 5. Still looping — schedule the next tick from turn end.
  491. if s.mode == "self_paced":
  492. digest = _digest_response(last_response)
  493. floor = self_paced_floor_seconds()
  494. if digest and digest == s.last_response_digest:
  495. s.current_delay = min(max(s.current_delay, floor) * 2, self_paced_ceiling_seconds())
  496. else:
  497. s.current_delay = float(floor)
  498. s.last_response_digest = digest
  499. else:
  500. s.current_delay = s.interval_seconds
  501. s.next_due_at = now + s.current_delay
  502. self._save()
  503. return {"status": "active", "stopped": False, "reason": "loop continues", "message": ""}
  504. def goal_blocks_loop_tick(session_id: str) -> bool:
  505. """True when an ACTIVE, non-parked /goal should defer this session's /loop tick.
  506. Both features inject synthetic turns at idle boundaries; interleaving them would burn the
  507. goal's turn budget. Parked (waiting), paused, or done goals do NOT block the loop.
  508. """
  509. try:
  510. from hermes_cli.goals import GoalManager
  511. mgr = GoalManager(session_id=session_id)
  512. return mgr.is_active() and not mgr.is_waiting()
  513. except Exception:
  514. return False
  515. LOOP_HELP = (
  516. "Usage: /loop [interval] <prompt> [--times N] [--until <condition>]\n"
  517. " /loop 5m check the deploy status — first run now, then every 5m\n"
  518. " /loop every 10m /recap — loop a slash command\n"
  519. " /loop keep fixing tests until green — self-paced (backs off while output is unchanged)\n"
  520. " /loop 2m poll CI --times 30 — stop after 30 runs\n"
  521. " /loop 5m watch the queue --until queue is empty\n"
  522. "Controls: /loop status · /loop pause · /loop resume · /loop stop\n"
  523. "The loop also stops itself when the agent replies with "
  524. f"{LOOP_COMPLETE_MARKER}."
  525. )
  526. def _pause_output(mgr: LoopManager) -> str:
  527. state = mgr.pause(reason="user-paused")
  528. return "No loop set." if state is None else f"⏸ Loop paused: {state.prompt}\nUse /loop resume to continue."
  529. def _resume_output(mgr: LoopManager) -> str:
  530. state = mgr.resume()
  531. return "No loop to resume." if state is None else f"▶ Loop resumed ({state.cadence_label()}): {state.prompt}"
  532. # Control words -> handler returning the output text. Anything else is a new loop spec.
  533. _CONTROL_COMMANDS = {
  534. **dict.fromkeys(("", "status"), lambda mgr: mgr.status_line()),
  535. "pause": _pause_output,
  536. "resume": _resume_output,
  537. **dict.fromkeys(("stop", "clear", "cancel"), lambda mgr: "✓ Loop stopped." if mgr.clear() else "No active loop."),
  538. **dict.fromkeys(("help", "--help", "-h"), lambda mgr: LOOP_HELP),
  539. }
  540. def dispatch_loop_command(
  541. mgr: LoopManager,
  542. args: str,
  543. *,
  544. route: Optional[dict[str, str]] = None,
  545. ) -> dict[str, Any]:
  546. """Surface-agnostic handler for ``/loop <args>`` → ``{"output": str, "created": bool}``.
  547. ``output`` is printed/sent verbatim by each surface. ``route`` is stored on new loops so the
  548. gateway's idle watcher can inject wakeups into the right chat; CLI/TUI pass None.
  549. """
  550. arg = (args or "").strip()
  551. control = _CONTROL_COMMANDS.get(arg.lower())
  552. if control is not None:
  553. return {"output": control(mgr), "created": False}
  554. parsed = parse_loop_args(arg)
  555. if parsed["error"]:
  556. if parsed["error"] == "empty":
  557. return {"output": "Usage: /loop [interval] <prompt> — see /loop help.", "created": False}
  558. return {"output": f"/loop: {parsed['error']}", "created": False}
  559. replacing = mgr.has_loop()
  560. try:
  561. state = mgr.set(
  562. parsed["prompt"],
  563. interval_seconds=parsed["interval_seconds"],
  564. times=parsed["times"],
  565. until=parsed["until"],
  566. route=route,
  567. )
  568. except ValueError as exc:
  569. return {"output": f"/loop: {exc}", "created": False}
  570. lines = [f"↻ Loop set ({state.cadence_label()}): {state.prompt}"]
  571. if replacing:
  572. lines.append("(replaced the previous loop for this session)")
  573. if parsed["interval_seconds"] is not None and parsed["interval_seconds"] < state.interval_seconds:
  574. lines.append(
  575. f"(interval raised to the {format_interval(state.interval_seconds)} minimum — "
  576. "loops.min_interval_seconds)"
  577. )
  578. if state.mode == "self_paced":
  579. lines.append(
  580. f"Self-paced: first check in {format_interval(state.current_delay)}; "
  581. f"backs off up to {format_interval(self_paced_ceiling_seconds())} while nothing changes."
  582. )
  583. if state.times:
  584. lines.append(f"Runs {state.times} time{'s' if state.times != 1 else ''}, then stops.")
  585. if state.until:
  586. lines.append(f"Stops when: {state.until}")
  587. if not state.times and state.max_ticks:
  588. lines.append(f"Backstop budget: {state.max_ticks} ticks (loops.max_ticks; 0 = unlimited).")
  589. first = "fires now, then on the cadence above" if state.status == "active" else state.remaining_label()
  590. lines.append(f"First wakeup {first}. Controls: /loop status · pause · resume · stop.")
  591. return {"output": "\n".join(lines), "created": True}
  592. __all__ = [
  593. "DEFAULT_MAX_TICKS",
  594. "DEFAULT_MIN_INTERVAL_SECONDS",
  595. "LOOP_COMPLETE_MARKER",
  596. "WAKEUP_PROMPT_TEMPLATE",
  597. "WAKEUP_PROMPT_WITH_UNTIL_TEMPLATE",
  598. "LoopManager",
  599. "LoopState",
  600. "clear_loop",
  601. "dispatch_loop_command",
  602. "format_interval",
  603. "goal_blocks_loop_tick",
  604. "list_active_loops",
  605. "load_loop",
  606. "migrate_loop_to_session",
  607. "parse_interval_token",
  608. "parse_loop_args",
  609. "response_signals_complete",
  610. "save_loop",
  611. ]