slash_commands_goals.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. """Autonomy-loop gateway commands: /goal, /subgoal, /heartbeat, /loop, /refine, /review.
  2. Bound onto ``GatewayRunner`` through ``GatewaySlashCommandsMixin``."""
  3. from __future__ import annotations
  4. import logging
  5. from agent.i18n import t
  6. from gateway.platforms.event import MessageEvent, MessageType
  7. # Log-record parity with gateway/run.py and the origin module.
  8. logger = logging.getLogger("gateway.run")
  9. def _quiet_bool(fn) -> bool:
  10. try:
  11. return bool(fn())
  12. except Exception:
  13. return False
  14. def _mgr_call(prefix: str, fn, *args, errors=(RuntimeError, ValueError)):
  15. """``(result, None)`` from ``fn(*args)``, or ``(None, "<prefix>: <exc>")`` on a manager error."""
  16. try:
  17. return fn(*args), None
  18. except errors as exc:
  19. return None, f"{prefix}: {exc}"
  20. class GatewayGoalCommandsMixin:
  21. """Autonomy-loop gateway commands: /goal, /subgoal, /heartbeat, /loop, /refine, /review."""
  22. async def _handle_goal_command(self, event: MessageEvent) -> str:
  23. from hermes_cli.goal_command import dispatch_goal_command
  24. from hermes_cli.goals import last_user_message_from_db
  25. mgr, _session_entry = await self._get_goal_manager_for_event(event)
  26. if mgr is None:
  27. return t("gateway.goal.unavailable")
  28. def authorize_gate():
  29. # A local session's owner is its admin: slash.exec admitted this command only after
  30. # authorize_local_source and the session:control capability (T7). Messaging stays
  31. # explicit-admin-only.
  32. from gateway.session_local import authorize_local_source
  33. if event.source is not None and authorize_local_source(self, event.source) is True:
  34. return None
  35. if not self._resume_caller_is_admin(event.source):
  36. return t("gateway.goal.gate_add_admin_only")
  37. return None
  38. def dispatch():
  39. return dispatch_goal_command(
  40. mgr, event.get_command_args() or "", authorize_gate=authorize_gate,
  41. render=lambda key, default, **values: t(key, **values),
  42. last_user_message=last_user_message_from_db(getattr(mgr, "session_id", None)),
  43. )
  44. # Drafting resolves profile-scoped credentials. Keep ContextVars across the
  45. # executor hop; manager I/O must also stay off the messaging event loop.
  46. result = await self._run_in_executor_with_context(dispatch)
  47. if result.clear_pending:
  48. self._clear_goal_continuations(event, result.clear_pending)
  49. if result.prompt:
  50. self._enqueue_goal_turn(event, result.prompt, label="command enqueue", kickoff=result.kickoff)
  51. return result.output
  52. def _clear_goal_continuations(self, event: MessageEvent, verb: str) -> None:
  53. try:
  54. adapter, quick_key = self._adapter_and_key_for(event)
  55. if adapter and quick_key:
  56. self._clear_goal_pending_continuations(quick_key, adapter)
  57. except Exception as exc:
  58. logger.debug("goal %s: pending continuation cleanup failed: %s", verb, exc)
  59. def _enqueue_goal_turn(
  60. self, event: MessageEvent, text: str, *, label: str, kickoff: bool
  61. ) -> None:
  62. """Enqueue *text* as the next turn through the adapter FIFO (the post-turn judge's path).
  63. A kickoff keeps the triggering message id / channel prompt / bound skills; a resume
  64. continuation carries none. Best-effort: failures only logged. A local ``slash.exec`` returns
  65. the turn to the client as its ``send`` directive instead (the client submits it with its own
  66. input id).
  67. """
  68. from gateway.session_command_sink import active_sink
  69. if (sink := active_sink()) is not None:
  70. sink.prompt = text
  71. if not kickoff:
  72. sink.display = "/goal resume"
  73. return
  74. try:
  75. adapter, quick_key = self._adapter_and_key_for(event)
  76. if text and adapter and quick_key:
  77. turn = MessageEvent(
  78. text=text,
  79. message_type=MessageType.TEXT,
  80. source=event.source,
  81. message_id=event.message_id if kickoff else None,
  82. channel_prompt=event.channel_prompt if kickoff else None,
  83. auto_skill=event.auto_skill if kickoff else None,
  84. inherit_channel_pin=not kickoff,
  85. )
  86. self._enqueue_fifo(quick_key, turn, adapter)
  87. except Exception as exc:
  88. logger.debug("goal %s failed: %s", label, exc)
  89. async def _handle_heartbeat_command(self, event: MessageEvent) -> str:
  90. """Handle /heartbeat (mirror of the CLI handler): the session's one recurring re-entry
  91. prompt. The gateway-wide poller injects due heartbeats through the adapter FIFO as
  92. ordinary user turns, so alternation and caching hold."""
  93. from hermes_cli.heartbeat import parse_interval, format_interval, MIN_INTERVAL_SECONDS
  94. args = (event.get_command_args() or "").strip()
  95. lower = args.lower()
  96. mgr, _session_entry = await self._get_heartbeat_manager_for_event(event)
  97. if mgr is None:
  98. return t("gateway.heartbeat.unavailable")
  99. quick_key = self._session_key_for_source(event.source) if event.source else None
  100. def _watch():
  101. if quick_key and event.source is not None:
  102. self._register_heartbeat_watch(quick_key, event.source, mgr.session_id)
  103. if not args or lower == "status":
  104. return mgr.status_line()
  105. if lower == "pause":
  106. state = mgr.pause()
  107. return t("gateway.heartbeat.paused", prompt=state.prompt) if state else t("gateway.heartbeat.none_set")
  108. if lower == "resume":
  109. state = mgr.resume()
  110. if state is None:
  111. return t("gateway.heartbeat.no_resume")
  112. _watch()
  113. return t("gateway.heartbeat.resumed", interval=format_interval(state.interval_seconds), prompt=state.prompt)
  114. if lower in {"clear", "stop", "off"}:
  115. had = mgr.clear()
  116. if quick_key:
  117. self._unregister_heartbeat_watch(quick_key)
  118. return t("gateway.heartbeat.cleared") if had else t("gateway.heartbeat.none_set")
  119. # Set: `/heartbeat every 10m <prompt>` (also accepts `10m <prompt>`).
  120. tokens = args.split(None, 2)
  121. interval, prompt = None, ""
  122. if tokens[0].lower() == "every" and len(tokens) >= 2:
  123. interval = parse_interval(f"every {tokens[1]}")
  124. prompt = tokens[2] if len(tokens) > 2 else ""
  125. else:
  126. interval = parse_interval(tokens[0])
  127. prompt = args[len(tokens[0]):].strip() if interval and interval > 0 else ""
  128. if interval is None:
  129. return t("gateway.heartbeat.usage")
  130. if interval < 0:
  131. return t("gateway.heartbeat.interval_too_small", min_seconds=MIN_INTERVAL_SECONDS)
  132. if not prompt.strip():
  133. return t("gateway.heartbeat.prompt_required")
  134. state, err = _mgr_call(t("gateway.heartbeat.invalid_prefix"), mgr.set, prompt, interval, errors=(ValueError,))
  135. if err:
  136. return err
  137. _watch()
  138. return t("gateway.heartbeat.set", interval=format_interval(state.interval_seconds), prompt=state.prompt)
  139. def _idle_cached_agent_or_error(self, event: MessageEvent, verb: str):
  140. """``(session_key, cached_agent, None)`` for /refine and /review, or ``(_, _, error_text)``:
  141. both need a cached agent from a completed turn and refuse while a run is in flight.
  142. ``verb`` is the command name (``refine`` / ``review``) and selects ``gateway.<verb>.*`` copy."""
  143. quick_key = self._session_key_for_source(event.source) if event.source else None
  144. if not quick_key:
  145. return None, None, t(f"gateway.{verb}.unavailable")
  146. if quick_key in self._running_agents:
  147. return quick_key, None, t("gateway.shared.agent_running_retry_later", command=verb)
  148. agent = self._cached_agent_for(quick_key)
  149. if agent is None:
  150. return quick_key, None, t(f"gateway.{verb}.nothing_yet")
  151. return quick_key, agent, None
  152. async def _handle_refine_command(self, event: MessageEvent) -> str:
  153. """Handle /refine — run the memory/skill review fork on demand, in a daemon thread against a
  154. snapshot of the cached AIAgent's conversation (live session and prompt cache untouched)."""
  155. args = (event.get_command_args() or "").strip()
  156. quick_key, agent, error = self._idle_cached_agent_or_error(event, "refine")
  157. snapshot = list(getattr(agent, "_session_messages", None) or [])
  158. session_id = None
  159. if not snapshot and quick_key and quick_key not in self._running_agents:
  160. # A local session's conversation is its stored transcript, not the cached agent: /moa
  161. # (and its settle) drop that agent, so /refine reads the session itself (T7).
  162. from gateway.session_refine import refine_local_session
  163. local = await refine_local_session(self, event.source, args)
  164. if local is not None:
  165. return local
  166. # A released cached agent (idle TTL, pressure, /moa), or one holding no messages, is not
  167. # an empty conversation: refine the stored transcript.
  168. from gateway.session_cold_review import stored_transcript
  169. from gateway.session_transcript import TranscriptReadError
  170. from gateway.slash_commands_status import history_unreadable
  171. try:
  172. session_id, snapshot = await stored_transcript(self, quick_key)
  173. except TranscriptReadError:
  174. return history_unreadable()
  175. error = None if snapshot else error
  176. if error:
  177. return error
  178. if not snapshot:
  179. return t("gateway.refine.empty")
  180. try:
  181. if agent is None:
  182. from gateway.session_cold_review import start_cold_refine
  183. await start_cold_refine(self, event.source, quick_key, session_id, snapshot, args)
  184. else:
  185. agent._spawn_background_review(
  186. messages_snapshot=snapshot, review_memory=True,
  187. review_skills="skill_manage" in getattr(agent, "valid_tool_names", set()), focus=args or None,
  188. explicit=True,
  189. )
  190. except Exception as exc:
  191. return t("gateway.refine.start_failed", error=exc)
  192. tail = t("gateway.refine.focus_suffix", focus=args) if args else ""
  193. return t("gateway.refine.started", focus_suffix=tail)
  194. async def _handle_review_command(self, event: MessageEvent) -> str:
  195. """Handle /review — spawn an independent reviewer subagent. The approval session-key
  196. contextvar is only bound during agent turns, so bind it explicitly here or the completion
  197. event carries no gateway route and never re-enters this chat."""
  198. args = (event.get_command_args() or "").strip()
  199. quick_key, agent, error = self._idle_cached_agent_or_error(event, "review")
  200. snapshot = list(getattr(agent, "_session_messages", None) or [])
  201. cold_session_id = None
  202. if agent is None and quick_key and quick_key not in self._running_agents:
  203. # The cached agent was evicted (idle TTL, pressure, /moa): review the stored transcript.
  204. from gateway.session_cold_review import cold_review_history
  205. from gateway.session_transcript import TranscriptReadError
  206. from gateway.slash_commands_status import history_unreadable
  207. try:
  208. cold_session_id, snapshot = await cold_review_history(self, event.source)
  209. except TranscriptReadError:
  210. return history_unreadable()
  211. error = None
  212. if error:
  213. return error
  214. from tools.approval_context import reset_current_session_key, set_current_session_key
  215. def _dispatch():
  216. from agent.review_engine import start_review
  217. from gateway.session_cold_review import cold_review_parent
  218. token = set_current_session_key(quick_key)
  219. try:
  220. if cold_session_id is None:
  221. return start_review(agent, snapshot, args)
  222. with cold_review_parent(self, event.source, quick_key, cold_session_id) as parent:
  223. return start_review(parent, snapshot, args)
  224. finally:
  225. reset_current_session_key(token)
  226. try:
  227. # _run_in_executor_with_context, not a bare hop: the reviewer subagent is spawned from
  228. # the worker and inherits its context; a bare hop would run it under the launch home.
  229. result = await self._run_in_executor_with_context(_dispatch)
  230. except ValueError as exc:
  231. return str(exc)
  232. except Exception as exc:
  233. return t("gateway.review.start_failed", error=exc)
  234. from agent.review_engine import format_dispatch_note
  235. return format_dispatch_note(result, args)
  236. async def _handle_subgoal_command(self, event: MessageEvent) -> str:
  237. """Handle /subgoal (mirror of the CLI handler): extra criteria appended to the active goal
  238. mid-loop. They modify state read at the next turn boundary, so this is safe while the
  239. agent is running."""
  240. args = (event.get_command_args() or "").strip()
  241. mgr, _session_entry = await self._get_goal_manager_for_event(event)
  242. if mgr is None:
  243. return t("gateway.goal.unavailable")
  244. if not mgr.has_goal():
  245. return t("gateway.subgoal.no_goal")
  246. if not args:
  247. return f"{mgr.status_line()}\n{mgr.render_subgoals()}"
  248. tokens = args.split(None, 1)
  249. verb = tokens[0].lower()
  250. rest = tokens[1].strip() if len(tokens) > 1 else ""
  251. if verb == "remove":
  252. if not rest:
  253. return t("gateway.subgoal.usage_remove")
  254. try:
  255. idx = int(rest.split()[0])
  256. except ValueError:
  257. return t("gateway.subgoal.remove_not_int")
  258. removed, err = _mgr_call(
  259. "/subgoal remove", mgr.remove_subgoal, idx, errors=(IndexError, RuntimeError)
  260. )
  261. return err or t("gateway.subgoal.removed", index=idx, text=removed)
  262. if verb == "clear":
  263. prev, err = _mgr_call("/subgoal clear", mgr.clear_subgoals, errors=(RuntimeError,))
  264. if err:
  265. return err
  266. if not prev:
  267. return t("gateway.subgoal.none_to_clear")
  268. return t("gateway.subgoal.cleared_one" if prev == 1 else "gateway.subgoal.cleared_other", count=prev)
  269. text, err = _mgr_call("/subgoal", mgr.add_subgoal, args)
  270. if err:
  271. return err
  272. idx = len(mgr.state.subgoals) if mgr.state else 0
  273. return t("gateway.subgoal.added", index=idx, text=text)
  274. async def _handle_loop_command(self, event: MessageEvent) -> str:
  275. """Handle /loop — recurring in-session wakeups, via ``dispatch_loop_command`` (CLI mirror)."""
  276. try:
  277. from hermes_cli.loops import LoopManager, dispatch_loop_command, goal_blocks_loop_tick
  278. except Exception as exc:
  279. logger.debug("loops module unavailable: %s", exc)
  280. return t("gateway.loop.unavailable")
  281. # Warm the SessionDB cache off-loop: a cold cache drops the first /loop write while the
  282. # reply claims the loop was set (same class as the /goal false-ack fix).
  283. await self._warm_goals_session_db("loop manager")
  284. try:
  285. session_entry = await self.async_session_store.get_or_create_session(event.source)
  286. except Exception:
  287. session_entry = None
  288. sid = getattr(session_entry, "session_id", None) or ""
  289. if not sid:
  290. return t("gateway.loop.no_session")
  291. mgr = LoopManager(session_id=sid)
  292. # New loops capture the event's routing so the idle loop-wakeup watcher can inject ticks
  293. # here after a restart; best-effort, empty fields dropped. ``profile`` pins the wakeup to this
  294. # session's own bot under multiplex (the watcher must never fire it through the default bot).
  295. route: dict = {}
  296. try:
  297. src = event.source
  298. if src is not None:
  299. platform = getattr(src, "platform", "")
  300. route = {"platform": platform.value if hasattr(platform, "value") else str(platform or "")}
  301. for key in ("chat_id", "chat_type", "thread_id", "user_id", "user_name", "profile"):
  302. route[key] = str(getattr(src, key, "") or "")
  303. route = {k: v for k, v in route.items() if v}
  304. except Exception:
  305. route = {}
  306. result = dispatch_loop_command(mgr, (event.get_command_args() or "").strip(), route=route)
  307. output = result.get("output") or ""
  308. if result.get("created") and _quiet_bool(lambda: goal_blocks_loop_tick(mgr.session_id)):
  309. output += t("gateway.loop.goal_defers_note")
  310. return output