gateway_tools.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. """The background-process registry main's classic CLI reads, served by the gateway session.
  2. On main the CLI process ran every ``terminal(background=true)`` itself, so the live-work dock,
  3. the status bar's ``⚙ N`` segment, ``/stop`` and the dock's tail view read
  4. ``tools.process_registry`` in-process. Rewired, the processes run in the gateway: this view
  5. answers the same calls (``list_sessions`` / ``get`` / ``count_running`` / ``kill_process`` /
  6. ``kill_all``) from the session's ``process.list`` / ``process.kill`` / ``process.stop`` verbs, so
  7. main's dock and command code render unchanged.
  8. Polling: the dock ticks once a second. The view only asks the gateway while it has a reason to
  9. (a tool finished since the last poll, or a listed process is still running or recently
  10. exited); the status bar reads the cached count and never blocks a repaint on an RPC.
  11. """
  12. from __future__ import annotations
  13. import logging
  14. import threading
  15. import time
  16. from hermes_cli.gateway_client import GatewayClientError
  17. logger = logging.getLogger(__name__)
  18. _POLL_SECONDS = 1.0
  19. # A finished process stays interesting this long (main's dock RETAIN_SECONDS).
  20. _RETAIN_SECONDS = 60
  21. _view = None
  22. class _Proc:
  23. """The ``ProcessSession`` attributes main's dock reads."""
  24. def __init__(self, row):
  25. self.id = row.get("session_id") or ""
  26. self.command = row.get("command") or ""
  27. self.exit_code = row.get("exit_code")
  28. self.started_at = float(row.get("started_epoch") or 0.0)
  29. self.exited_at = float(row.get("exited_at") or 0.0)
  30. self.output_buffer = row.get("output_tail") or ""
  31. self.completion_reason = row.get("completion_reason") or "exited"
  32. self.exited = row.get("status") == "exited"
  33. class GatewayProcessView:
  34. def __init__(self, agent):
  35. self.agent = agent
  36. self.connection = agent.connection
  37. self.rows: list = []
  38. self.dirty = True
  39. self.delegations = 0
  40. self._polled = 0.0
  41. self._lock = threading.Lock()
  42. self.subagents: list = []
  43. self._subagents_polled = 0.0
  44. self._subagents_seen = 0.0
  45. self._subagents_lock = threading.Lock()
  46. self._tail = None
  47. self._subagents_watch_until = 0.0
  48. @property
  49. def session_id(self):
  50. return self.agent.session_id # follows /new, /resume and compression rotations
  51. # -- polling ---------------------------------------------------------------------------
  52. def mark_dirty(self):
  53. self.dirty = True
  54. def _interesting(self, now):
  55. return any(not p.exited or (p.exited_at and now - p.exited_at <= _RETAIN_SECONDS) for p in self.rows)
  56. def refresh(self, *, force=False):
  57. now = time.time()
  58. if not force and (now - self._polled < _POLL_SECONDS or not (self.dirty or self._interesting(now))):
  59. return
  60. if not self._lock.acquire(blocking=False):
  61. return
  62. try:
  63. self._polled = now
  64. self.dirty = False
  65. result = self.connection.call("process.list", session_id=self.session_id, timeout=5)
  66. self.rows = [_Proc(row) for row in (result or {}).get("processes") or []]
  67. except (GatewayClientError, RuntimeError) as exc:
  68. logger.debug("process.list failed: %s", exc)
  69. finally:
  70. self._lock.release()
  71. # -- the tools.process_registry surface main's CLI calls ---------------------------------
  72. def list_sessions(self):
  73. self.refresh()
  74. now = time.time()
  75. return [{"session_id": p.id, "command": p.command[:200],
  76. "status": "exited" if p.exited else "running", "exit_code": p.exit_code,
  77. "completion_reason": p.completion_reason if p.exited else None,
  78. "uptime_seconds": int(now - p.started_at) if p.started_at else 0} for p in self.rows]
  79. def get(self, process_id):
  80. return next((p for p in self.rows if p.id == process_id), None)
  81. def count_running(self):
  82. """Cached (the status bar repaints off the render thread)."""
  83. return sum(1 for p in self.rows if not p.exited)
  84. def kill_process(self, process_id, **_kw):
  85. try:
  86. result = self.connection.call("process.kill", session_id=self.session_id, process_id=process_id)
  87. except GatewayClientError as exc:
  88. return {"status": "error", "error": str(exc)}
  89. self.refresh(force=True)
  90. return result
  91. def kill_all(self, **_kw):
  92. """``/stop``: the session's own processes plus its background delegations (``process.stop``)."""
  93. result = self.connection.call("process.stop", session_id=self.session_id) or {}
  94. self.delegations = int(result.get("delegations") or 0)
  95. self.refresh(force=True)
  96. return int(result.get("killed") or 0)
  97. def interrupt_delegations(self):
  98. """The delegation half of ``/stop`` (``kill_all`` already ran it when processes were live)."""
  99. if self.delegations:
  100. count, self.delegations = self.delegations, 0
  101. return count
  102. self.kill_all()
  103. count, self.delegations = self.delegations, 0
  104. return count
  105. def active_delegations(self):
  106. """Running background subagents (the gateway's ``session.usage.active_subagents``)."""
  107. try:
  108. usage = self.connection.state(self.session_id).usage or {}
  109. except Exception: # health: allow BLE001 -- a missing usage cache reads as none running
  110. return 0
  111. value = usage.get("active_subagents")
  112. return value if isinstance(value, int) else 0
  113. # -- the subagent registry main's Ctrl+T monitor and dock read ---------------------------
  114. def watch_subagents(self, seconds=_RETAIN_SECONDS):
  115. """Poll ``subagent.list`` for a while even with no turn running: an off-turn spawn
  116. (``/review``) moves neither ``busy`` nor the usage count the gate below reads."""
  117. self._subagents_watch_until = time.time() + seconds
  118. self._subagents_polled = 0.0
  119. def subagent_rows(self, *, busy):
  120. """The session's live children (``subagent.list``). Asks at most once a second, and only
  121. while a turn runs (``busy``), children were listed last time, the gateway counts some, or
  122. an off-turn spawn asked to be watched."""
  123. now = time.time()
  124. wanted = (busy or self.subagents or now < self._subagents_watch_until
  125. or self.active_delegations())
  126. if wanted and now - self._subagents_polled >= _POLL_SECONDS and self._subagents_lock.acquire(blocking=False):
  127. try:
  128. self._subagents_polled = now
  129. result = self.connection.call("subagent.list", session_id=self.session_id, timeout=5)
  130. self.subagents = list((result or {}).get("subagents") or [])
  131. self._subagents_seen = now
  132. except (GatewayClientError, RuntimeError) as exc:
  133. logger.debug("subagent.list failed: %s", exc)
  134. if now - self._subagents_seen > _RETAIN_SECONDS:
  135. self.subagents = [] # no answer for a minute: drop the rows and stop polling
  136. finally:
  137. self._subagents_lock.release()
  138. return [dict(row) for row in self.subagents]
  139. def subagent_tail(self, subagent_id, *, fetch=False):
  140. """The child's live transcript tail (``subagent.tail``); None when the gateway has none.
  141. The detail view repaints every frame and reads only the cache; ``fetch`` (the monitor's
  142. tick, on the spinner thread) asks the gateway at most once a second, failures included."""
  143. now = time.time()
  144. cached = self._tail if self._tail and self._tail[0] == subagent_id else None
  145. if not fetch or (cached and now - cached[1] < _POLL_SECONDS):
  146. return cached[2] if cached else None
  147. try:
  148. result = self.connection.call("subagent.tail", session_id=self.session_id,
  149. subagent_id=subagent_id, timeout=5) or {}
  150. text = result.get("text") if result.get("available") else None
  151. if text is not None: # filter once here, not on every repaint of the detail view
  152. text = "".join(c for c in text if c.isprintable() or c in "\n\t")
  153. except (GatewayClientError, RuntimeError) as exc:
  154. logger.debug("subagent.tail failed: %s", exc)
  155. text = None
  156. self._tail = (subagent_id, now, text)
  157. return text
  158. def subagent_control(self, action, subagent_id, message=None):
  159. """Steer (``subagent.steer``) or stop (``subagent.interrupt``) one child of this session, in
  160. the shape ``delegate_tool_registry._handle_control_action`` answers: ``note`` or ``error``."""
  161. from tools.delegate_tool_registry import _CONTROL_OUTCOMES
  162. status, note, failure = _CONTROL_OUTCOMES[action]
  163. try:
  164. if action == "steer":
  165. result = self.connection.call("subagent.steer", session_id=self.session_id,
  166. subagent_id=subagent_id, text=message, timeout=5) or {}
  167. ok = result.get("status") == "queued"
  168. else:
  169. result = self.connection.call("subagent.interrupt", session_id=self.session_id,
  170. subagent_id=subagent_id, timeout=5) or {}
  171. ok = bool(result.get("found"))
  172. except GatewayClientError as exc:
  173. return {"error": str(exc)}
  174. self._subagents_polled = 0.0 # the next tick re-reads the roster
  175. if ok:
  176. return {"action": action, "subagent_id": subagent_id, "status": status, "note": note}
  177. return {"error": failure.format(sid=subagent_id)}
  178. class LocalSubagents:
  179. """This process's own subagent registry behind the view's ``subagent_*`` surface, for a CLI that
  180. runs its agent in-process: the dock and monitor talk to one backend shape either way."""
  181. def __init__(self, cli):
  182. self.cli = cli
  183. self._paths: dict = {}
  184. def subagent_rows(self, *, busy):
  185. from tools.delegate_tool_registry import _list_payload, list_active_subagents
  186. parent = getattr(self.cli, "agent", None)
  187. entries = _list_payload(parent)["subagents"] if parent is not None else []
  188. # The scoped control-plane snapshot supplies authority and transcript paths; the public
  189. # lifecycle record supplies start time and the latest observed tool (as subagent.list does).
  190. live = {r["subagent_id"]: r for r in list_active_subagents()} if entries else {}
  191. for row in entries:
  192. record = live.get(row["subagent_id"], {})
  193. row["started_at"], row["last_tool"] = record.get("started_at"), record.get("last_tool") or ""
  194. self._paths = {row["subagent_id"]: row.get("live_transcript") for row in entries}
  195. return entries
  196. def subagent_tail(self, subagent_id, *, fetch=False):
  197. from hermes_cli.cli_subagent_monitor import read_tail
  198. return read_tail(self._paths.get(subagent_id))
  199. def subagent_control(self, action, subagent_id, message=None):
  200. import json
  201. from tools.delegate_tool_registry import _handle_control_action
  202. return json.loads(_handle_control_action(action, subagent_id, message, getattr(self.cli, "agent", None)))
  203. class _OpenedSession:
  204. """The CLI's open gateway session before any chat agent exists (``_init_agent`` builds that on the
  205. first turn): the view's ``connection`` and ``session_id``, following the CLI's id."""
  206. def __init__(self, cli, connection):
  207. self.cli, self.connection = cli, connection
  208. @property
  209. def session_id(self):
  210. return self.cli.session_id
  211. def bind(agent):
  212. """Called when the CLI's gateway-backed agent is built."""
  213. global _view
  214. _view = GatewayProcessView(agent) if getattr(agent, "connection", None) is not None else None
  215. return _view
  216. def bind_session(cli, connection):
  217. """Called when the CLI opens its gateway session, so ``/agents``, ``/stop``, the dock and the status
  218. bar read the session's processes before the first turn (a resumed session's work keeps running)."""
  219. return bind(_OpenedSession(cli, connection))
  220. def mark_dirty():
  221. if _view is not None:
  222. _view.mark_dirty()
  223. def process_view():
  224. """The gateway-backed registry, or None when this process runs its own tools (not rewired) or
  225. its gateway connection is final (a hang-up keeps the view; its next call redials)."""
  226. view = _view
  227. return view if view is not None and not view.connection.final else None
  228. def process_registry():
  229. """``tools.process_registry.process_registry`` for main's dock, status bar and ``/stop``."""
  230. view = process_view()
  231. if view is not None:
  232. return view
  233. from tools.process_registry import process_registry as local
  234. return local
  235. def background_counts():
  236. """The status bar's ``⚙ N`` processes and running background subagents (cached, no RPC)."""
  237. view = process_view()
  238. if view is not None:
  239. return {"active_background_processes": view.count_running(),
  240. "active_background_subagents": view.active_delegations()}
  241. from tools.async_delegation import active_count
  242. from tools.process_registry import process_registry as local
  243. return {"active_background_processes": local.count_running(), "active_background_subagents": active_count()}
  244. def session_tools():
  245. """``/tools``: the gateway session's tool catalog (``tools.show``) as
  246. ``(tools, toolset_of)``: ``get_tool_definitions``-shaped rows (first description sentence) and
  247. a name -> toolset lookup. None when the CLI is not gateway-backed."""
  248. view = process_view()
  249. if view is None:
  250. return None
  251. result = view.connection.call("tools.show", session_id=view.session_id) or {}
  252. tools, toolset_of = [], {}
  253. for section in result.get("sections") or []:
  254. for row in section.get("tools") or []:
  255. toolset_of[row["name"]] = section.get("name")
  256. tools.append({"type": "function", "function": {"name": row["name"],
  257. "description": row.get("description") or ""}})
  258. return tools, toolset_of.get
  259. def reload_gateway_skills():
  260. """Rescan skills in the gateway session too (its skill-command map serves this session's
  261. ``/<skill>`` and bundle invocations); the CLI's own rescan still drives main's output."""
  262. view = process_view()
  263. if view is None:
  264. return None
  265. try:
  266. return (view.connection.call("skills.reload", session_id=view.session_id) or {}).get("result")
  267. except GatewayClientError as exc:
  268. logger.debug("skills.reload failed: %s", exc)
  269. return None
  270. def handle_skills_slash(cmd, console, cli=None):
  271. """Main's ``/skills`` (hub search / install / uninstall write the local skills tree), then the
  272. gateway's rescan so an install reaches the skill map the session's turns use, and ``cli``'s copy of
  273. the gateway's skill list is read again."""
  274. from hermes_cli.skills_hub import handle_skills_slash as local
  275. local(cmd, console)
  276. reload_gateway_skills()
  277. if cli is not None:
  278. from hermes_cli.gateway_plugin_commands import invalidate
  279. invalidate(cli)