gateway_automation.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. """The classic CLI's /goal, /subgoal, /loop and /heartbeat managers, backed by the gateway session.
  2. Main's ``HermesCLI`` built ``GoalManager`` / ``LoopManager`` / ``HeartbeatManager`` in-process: each
  3. mutation wrote ``state_meta`` through a read-write SessionDB and ``evaluate_after_turn`` called the goal
  4. judge model from the CLI pid. Rewired, the gateway is the single writer and runs every model call, so
  5. these are thin proxies (the GatewayAgent / GatewaySessionStore seam): every mutation and judgement is
  6. one ``session.automation`` call, and the persisted state the gateway returns is cached here so the
  7. status bar, the dock and main's read-only helpers (``status_line``, ``is_due``, ``render_gates``…) keep
  8. running main's own code, unchanged, against the same state object.
  9. """
  10. from __future__ import annotations
  11. import logging
  12. from hermes_cli.gateway_client import GatewayClientError
  13. logger = logging.getLogger(__name__)
  14. _ERRORS = {"RuntimeError": RuntimeError, "ValueError": ValueError, "IndexError": IndexError}
  15. def _decode(value):
  16. if isinstance(value, dict):
  17. if set(value) == {"__state__"}:
  18. return value["__state__"]
  19. if set(value) == {"__gate__"}:
  20. from hermes_cli.goals import GoalGate
  21. return GoalGate.from_dict(value["__gate__"])
  22. return {k: _decode(v) for k, v in value.items()}
  23. if isinstance(value, list):
  24. return [_decode(v) for v in value]
  25. return value
  26. class _Remote:
  27. """Shared plumbing: ``self._state`` mirrors the gateway's row; ``_rpc`` runs one call there."""
  28. kind = ""
  29. _state_cls: type = type(None)
  30. def __init__(self, session_id, connection, *, load=True):
  31. self.session_id = session_id
  32. self._connection = connection
  33. self._state = None
  34. if load:
  35. self.refresh()
  36. @property
  37. def state(self):
  38. return self._state
  39. def _adopt(self, raw):
  40. state = self._state_cls.from_json(raw) if raw else None
  41. self._state = None if state is None or state.status == "cleared" else state
  42. return self._state
  43. def _rpc(self, call, *args, **kwargs):
  44. try:
  45. reply = self._connection.call("session.automation", session_id=self.session_id, kind=self.kind,
  46. call=call, args=list(args), kwargs=kwargs)
  47. except GatewayClientError as exc:
  48. # Main's managers swallowed a dropped write (debug log, no crash); the REPL stays up.
  49. logger.debug("session.automation %s.%s failed: %s", self.kind, call, exc)
  50. return None
  51. self._adopt(reply.get("state"))
  52. error = reply.get("error")
  53. if error:
  54. raise _ERRORS.get(error.get("type"), RuntimeError)(error.get("message") or "")
  55. value = _decode(reply.get("value"))
  56. return self._state if isinstance(value, str) and value == reply.get("state") and value else value
  57. def refresh(self):
  58. self._rpc("state")
  59. class GatewayGoalManager(_Remote):
  60. """``hermes_cli.goals.GoalManager`` over the gateway (same method names and returns)."""
  61. kind = "goal"
  62. def __init__(self, session_id, connection, *, default_max_turns=None, load=True):
  63. from hermes_cli.goals import GoalState
  64. self._state_cls = GoalState
  65. self.default_max_turns = default_max_turns
  66. super().__init__(session_id, connection, load=load)
  67. # Main's pure reads, on the mirrored state (``GoalManager`` methods bound to this object).
  68. from hermes_cli.goals import GoalManager as _Local
  69. is_active = _Local.is_active
  70. has_goal = _Local.has_goal
  71. has_contract = _Local.has_contract
  72. status_line = _Local.status_line
  73. render_subgoals = _Local.render_subgoals
  74. render_gates = _Local.render_gates
  75. render_contract = _Local.render_contract
  76. next_continuation_prompt = _Local.next_continuation_prompt
  77. del _Local
  78. def set(self, goal, *, max_turns=None, contract=None):
  79. kwargs = {"max_turns": max_turns} if max_turns is not None else {}
  80. if contract is not None:
  81. kwargs["contract"] = contract.to_dict()
  82. return self._rpc("set", goal, **kwargs)
  83. def pause(self, reason="user-paused"):
  84. return self._rpc("pause", reason=reason)
  85. def resume(self, *, reset_budget=True):
  86. return self._rpc("resume", reset_budget=reset_budget)
  87. def clear(self):
  88. self._rpc("clear")
  89. def mark_done(self, reason):
  90. self._rpc("mark_done", reason)
  91. def add_subgoal(self, text):
  92. return self._rpc("add_subgoal", text)
  93. def remove_subgoal(self, index_1based):
  94. return self._rpc("remove_subgoal", int(index_1based))
  95. def clear_subgoals(self):
  96. return self._rpc("clear_subgoals")
  97. def add_gate(self, command, *, timeout_seconds=None, max_retries=None):
  98. kwargs = {k: v for k, v in (("timeout_seconds", timeout_seconds), ("max_retries", max_retries)) if v}
  99. return self._rpc("add_gate", command, **kwargs)
  100. def remove_gate(self, index_1based):
  101. return self._rpc("remove_gate", int(index_1based))
  102. def clear_gates(self):
  103. return self._rpc("clear_gates")
  104. def wait_on(self, pid, reason=""):
  105. return self._rpc("wait_on", int(pid), reason=reason)
  106. def wait_on_session(self, session_id, reason=""):
  107. return self._rpc("wait_on_session", session_id, reason=reason)
  108. def wait_for_seconds(self, seconds, reason="", *, on_delegations=0):
  109. return self._rpc("wait_for_seconds", int(seconds), reason=reason, on_delegations=on_delegations)
  110. def stop_waiting(self):
  111. return bool(self._rpc("stop_waiting"))
  112. def is_waiting(self):
  113. """Barrier check (and lazy clear) where the barrier lives: the pid / process session is the
  114. gateway's. A state with no barrier answers locally, so the idle poll costs no round trip."""
  115. s = self._state
  116. if s is None or (s.waiting_on_pid is None and s.waiting_on_session is None and not s.waiting_until):
  117. return False
  118. return bool(self._rpc("is_waiting"))
  119. def command(self, arg, last_user_message=None):
  120. """The whole ``/goal <arg>`` run by the gateway (``/goal draft``: its contract drafter is a model call)."""
  121. from hermes_cli.goal_command import GoalCommandResult
  122. result = self._rpc("command", arg, last_user_message)
  123. if not isinstance(result, dict):
  124. return GoalCommandResult("Goal unavailable: the gateway did not answer.", error=True)
  125. return GoalCommandResult(**{k: v for k, v in result.items() if k in GoalCommandResult.__dataclass_fields__})
  126. def evaluate_after_turn(self, last_response, *, user_initiated=True, background_processes=None,
  127. active_delegations=0):
  128. """The judge runs in the gateway (``auxiliary.goal_judge``), with the gateway's background
  129. processes and delegations; the decision dict is main's."""
  130. decision = self._rpc("evaluate_after_turn", last_response or "")
  131. if not isinstance(decision, dict):
  132. return {"status": None, "should_continue": False, "continuation_prompt": None,
  133. "verdict": "inactive", "reason": "gateway unavailable", "message": ""}
  134. return decision
  135. class GatewayLoopManager(_Remote):
  136. """``hermes_cli.loops.LoopManager`` over the gateway."""
  137. kind = "loop"
  138. def __init__(self, session_id, connection, *, load=True):
  139. from hermes_cli.loops import LoopState
  140. self._state_cls = LoopState
  141. super().__init__(session_id, connection, load=load)
  142. from hermes_cli.loops import LoopManager as _Local
  143. is_active = _Local.is_active
  144. has_loop = _Local.has_loop
  145. status_line = _Local.status_line
  146. is_due = _Local.is_due
  147. del _Local
  148. def set(self, prompt, *, interval_seconds=None, times=0, until="", route=None):
  149. return self._rpc("set", prompt, interval_seconds=interval_seconds, times=times, until=until)
  150. def pause(self, reason="user-paused"):
  151. return self._rpc("pause", reason=reason)
  152. def resume(self):
  153. return self._rpc("resume")
  154. def clear(self):
  155. return bool(self._rpc("clear"))
  156. def fire_tick(self):
  157. return self._rpc("fire_tick")
  158. def abandon_tick(self):
  159. self._rpc("abandon_tick")
  160. def complete_tick(self, last_response):
  161. decision = self._rpc("complete_tick", last_response or "")
  162. return decision if isinstance(decision, dict) else {"status": None, "stopped": False,
  163. "reason": "gateway unavailable", "message": ""}
  164. def goal_blocks_tick(self):
  165. return bool(self._rpc("goal_blocks_tick"))
  166. class GatewayHeartbeatManager(_Remote):
  167. """``hermes_cli.heartbeat.HeartbeatManager`` over the gateway."""
  168. kind = "heartbeat"
  169. def __init__(self, session_id, connection, *, load=True):
  170. from hermes_cli.heartbeat import HeartbeatState
  171. self._state_cls = HeartbeatState
  172. super().__init__(session_id, connection, load=load)
  173. from hermes_cli.heartbeat import HeartbeatManager as _Local
  174. has_heartbeat = _Local.has_heartbeat
  175. is_active = _Local.is_active
  176. status_line = _Local.status_line
  177. del _Local
  178. def set(self, prompt, interval_seconds):
  179. return self._rpc("set", prompt, int(interval_seconds))
  180. def pause(self):
  181. return self._rpc("pause")
  182. def resume(self):
  183. return self._rpc("resume")
  184. def clear(self):
  185. return bool(self._rpc("clear"))
  186. def due_prompt(self, now=None):
  187. s = self._state
  188. if s is None or not s.is_due(now):
  189. return None # main's cheap local check first (the watchdog refreshes the state each poll)
  190. return self._rpc("due_prompt")
  191. def abandon_fire(self):
  192. return bool(self._rpc("abandon_fire"))
  193. def dispatch_goal_command(mgr, arg, *, authorize_gate, last_user_message=None, progress=None):
  194. """``goal_command.dispatch_goal_command`` for the classic CLI: on a gateway manager ``/goal draft``
  195. (its contract drafter is an auxiliary-model call) runs whole on the gateway; every other form is
  196. main's dispatcher over the proxy, so its output strings stay main's."""
  197. from hermes_cli import goal_command
  198. if isinstance(mgr, GatewayGoalManager) and (arg or "").split(None, 1)[:1] == ["draft"]:
  199. if progress is not None:
  200. progress("Drafting completion contract…")
  201. return mgr.command(arg, last_user_message)
  202. return goal_command.dispatch_goal_command(mgr, arg, authorize_gate=authorize_gate,
  203. last_user_message=last_user_message, progress=progress)
  204. def gateway_connection(cli):
  205. """The CLI's gateway connection when its session store is the gateway's, else None (main's local
  206. managers: tests and the TUI slash worker's shadow CLI)."""
  207. from hermes_cli.gateway_session_store import GatewaySessionStore
  208. store = getattr(cli, "_session_db", None)
  209. if isinstance(store, GatewaySessionStore) and getattr(cli, "_gateway_session_open", False):
  210. return store.connection
  211. return None