The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): Ctrl+T monitor and dock read the gateway session's subagents (CLI-12)
Turgut Kuralb2bd66b65fba
diff --git a/hermes_cli/cli_subagent_monitor.py b/hermes_cli/cli_subagent_monitor.pyindex 18126e89fef..c3d28b46d0f 100644--- a/hermes_cli/cli_subagent_monitor.py+++ b/hermes_cli/cli_subagent_monitor.py@@ -65,17 +65,27 @@ class SubagentMonitor:row = self.selectedreturn row if row and row.get('kind') == 'process' else None- def refresh(self, now=None):+ def _subagent_rows(self):+ """``(rows, activity)``: the session's live children and their lifecycle records. Rewired, the+ children run in the gateway, so both come from its ``subagent.list`` (CLI-12)."""+ from hermes_cli.gateway_tools import process_view+ view = process_view()+ if view is not None:+ rows = view.subagent_rows(busy=bool(getattr(self.cli, '_agent_running', False)))+ return rows, {r['subagent_id']: r for r in rows}from tools.delegate_tool_registry import _list_payload, list_active_subagents- now = time.time() if now is None else nowparent = getattr(self.cli, 'agent', None)entries = _list_payload(parent)['subagents'] if parent is not None else []# The scoped control-plane snapshot supplies authority and transcript paths;# its matching public lifecycle record supplies the latest observed tool.- activity = {r['subagent_id']: r for r in list_active_subagents()} if entries else {}+ return entries, ({r['subagent_id']: r for r in list_active_subagents()} if entries else {})++ def refresh(self, now=None):+ now = time.time() if now is None else now+ entries, activity = self._subagent_rows()for row in entries:live = activity.get(row['subagent_id'], {})- row['elapsed'] = max(0, int(now - live.get('started_at', now)))+ row['elapsed'] = max(0, int(now - (live.get('started_at') or now)))row['last_tool'] = live.get('last_tool') or ''row['key'] = row['subagent_id']row.pop('running_seconds', None)@@ -130,6 +140,10 @@ class SubagentMonitor:if action != 'stop':return {'error': t('cli.subagents.cannot_steer_process')}return procs.kill(target)+ from hermes_cli.gateway_tools import process_view+ view = process_view()+ if view is not None:+ return view.subagent_control(action, target, message)from tools.delegate_tool_registry import _handle_control_actionreturn json.loads(_handle_control_action(action, target, message, getattr(self.cli, 'agent', None)))@@ -259,6 +273,19 @@ def read_tail(path):return t('cli.subagents.transcript_unavailable')+def subagent_tail(row):+ """The child's transcript tail: the gateway's ``subagent.tail`` when it runs the child, else the+ transcript file this process wrote."""+ from hermes_cli.gateway_tools import process_view+ view = process_view()+ if view is None:+ return read_tail(row.get('live_transcript'))+ text = view.subagent_tail(row['subagent_id'])+ if text is None:+ return t('cli.subagents.transcript_unavailable')+ return ''.join(c for c in text if c.isprintable() or c in '\n\t')++def modal_prompt_active(cli):return any(getattr(cli, name, None) for name in ('_clarify_state', '_approval_state', '_slash_confirm_state', '_sudo_state',@@ -311,7 +338,7 @@ def build_monitor_application(monitor, **kwargs):elif row.get('kind') == 'process':text = procs.process_tail(row['id'])else:- text = read_tail(row.get('live_transcript'))+ text = subagent_tail(row)if text != tail.text:following = tail.buffer.cursor_position == len(tail.text)position = tail.buffer.cursor_positiondiff --git a/hermes_cli/gateway_tools.py b/hermes_cli/gateway_tools.pyindex 8efbe3b2eab..f6e23b4ca41 100644--- a/hermes_cli/gateway_tools.py+++ b/hermes_cli/gateway_tools.py@@ -51,6 +51,10 @@ class GatewayProcessView:self.delegations = 0self._polled = 0.0self._lock = threading.Lock()+ self.subagents: list = []+ self._subagents_polled = 0.0+ self._subagents_lock = threading.Lock()+ self._tail = None@propertydef session_id(self):@@ -128,6 +132,62 @@ class GatewayProcessView:value = usage.get("active_subagents")return value if isinstance(value, int) else 0+ # -- the subagent registry main's Ctrl+T monitor and dock read ---------------------------+ def subagent_rows(self, *, busy):+ """The session's live children (``subagent.list``). Asks at most once a second, and only+ while a turn runs (``busy``), children were listed last time, or the gateway counts some."""+ now = time.time()+ wanted = busy or self.subagents or self.active_delegations()+ if wanted and now - self._subagents_polled >= _POLL_SECONDS and self._subagents_lock.acquire(blocking=False):+ try:+ self._subagents_polled = now+ result = self.connection.call("subagent.list", session_id=self.session_id, timeout=5)+ self.subagents = list((result or {}).get("subagents") or [])+ except (GatewayClientError, RuntimeError) as exc:+ logger.debug("subagent.list failed: %s", exc)+ finally:+ self._subagents_lock.release()+ return [dict(row) for row in self.subagents]++ def subagent_tail(self, subagent_id):+ """The child's live transcript tail (``subagent.tail``); None when the gateway has none.+ The monitor repaints the detail view every frame, so the answer is reused for a second."""+ now = time.time()+ cached = self._tail+ if cached and cached[0] == subagent_id and now - cached[1] < _POLL_SECONDS:+ return cached[2]+ try:+ result = self.connection.call("subagent.tail", session_id=self.session_id,+ subagent_id=subagent_id, timeout=5) or {}+ except (GatewayClientError, RuntimeError) as exc:+ logger.debug("subagent.tail failed: %s", exc)+ return None+ text = result.get("text") if result.get("available") else None+ self._tail = (subagent_id, now, text)+ return text++ def subagent_control(self, action, subagent_id, message=None):+ """Steer (``subagent.steer``) or stop (``subagent.interrupt``) one child of this session, in+ the shape ``delegate_tool_registry._handle_control_action`` answers: ``note`` or ``error``."""+ from tools.delegate_tool_registry import _CONTROL_OUTCOMES++ status, note, failure = _CONTROL_OUTCOMES[action]+ try:+ if action == "steer":+ result = self.connection.call("subagent.steer", session_id=self.session_id,+ subagent_id=subagent_id, text=message) or {}+ ok = result.get("status") == "queued"+ else:+ result = self.connection.call("subagent.interrupt", session_id=self.session_id,+ subagent_id=subagent_id) or {}+ ok = bool(result.get("found"))+ except GatewayClientError as exc:+ return {"error": str(exc)}+ self._subagents_polled = 0.0 # the next tick re-reads the roster+ if ok:+ return {"action": action, "subagent_id": subagent_id, "status": status, "note": note}+ return {"error": failure.format(sid=subagent_id)}+class _OpenedSession:"""The CLI's open gateway session before any chat agent exists (``_init_agent`` builds that on thediff --git a/tests/hermes_cli/test_subagent_monitor_gateway.py b/tests/hermes_cli/test_subagent_monitor_gateway.pynew file mode 100644index 00000000000..9d905e07e77--- /dev/null+++ b/tests/hermes_cli/test_subagent_monitor_gateway.py@@ -0,0 +1,91 @@+"""CLI-12: the Ctrl+T monitor and dock read the gateway session's subagents.++Rewired, delegate_task children run in the gateway, so the CLI process's own+``tools.delegate_tool_registry`` is empty. The monitor lists, tails, steers and stops them through+the session's ``subagent.list`` / ``subagent.tail`` / ``subagent.steer`` / ``subagent.interrupt``+verbs (scripted fake gateway, no live gateway).+"""+import asyncio+import time+from contextlib import asynccontextmanager+from types import SimpleNamespace++import pytest++from hermes_cli import gateway_tools+from hermes_cli.gateway_agent import GatewayAgent+from hermes_cli.gateway_connection import GatewayConnection++SID = "local-abc"+++class FakeClient:+ def __init__(self):+ self.events = asyncio.Queue()+ self.calls = []+ self.children = [{"subagent_id": "sa-0-1", "goal": "Audit the parser", "status": "running",+ "started_at": time.time() - 7, "last_tool": "read_file", "accepting_steer": True}]+ self.steered = []++ async def rpc(self, method, *, _timeout=None, **params):+ self.calls.append((method, params))+ if method == "subagent.list":+ return {"subagents": self.children, "delegations": []}+ if method == "subagent.tail":+ return {"subagent_id": params["subagent_id"], "available": True, "text": "step 1\nstep 2\n",+ "truncated": False}+ if method == "subagent.steer":+ self.steered.append(params["text"])+ return {"status": "queued", "subagent_id": params["subagent_id"], "text": params["text"]}+ if method == "subagent.interrupt":+ found = any(c["subagent_id"] == params["subagent_id"] for c in self.children)+ self.children = [c for c in self.children if c["subagent_id"] != params["subagent_id"]]+ return {"found": found, "subagent_id": params["subagent_id"]}+ return {}+++def gateway(monkeypatch):+ from tools import delegate_tool_registry as registry+ monkeypatch.setattr(registry, "_active_subagents", {}) # the CLI process runs no children+ client = FakeClient()++ @asynccontextmanager+ async def connect():+ yield client+ conn = GatewayConnection(connect=connect)+ conn.start(5)+ conn.state(SID)+ agent = GatewayAgent(connection=conn, session_id=SID)+ gateway_tools.bind(agent)+ yield agent, client+ conn.close()+ gateway_tools._view = None+++def test_monitor_lists_tails_and_controls_the_gateway_sessions_children(gateway):+ from hermes_cli import cli_subagent_monitor+ agent, client = gateway+ monitor = cli_subagent_monitor.SubagentMonitor(SimpleNamespace(agent=agent, _agent_running=True))++ monitor.refresh()+ assert [r["subagent_id"] for r in monitor.entries] == ["sa-0-1"]+ assert monitor.entries[0]["last_tool"] == "read_file" and monitor.entries[0]["elapsed"] >= 6+ assert ("subagent.list", {"session_id": SID}) in client.calls+ assert cli_subagent_monitor.subagent_tail(monitor.selected) == "step 1\nstep 2\n"++ assert "note" in monitor.control("steer", "Focus on the tokenizer")+ assert client.steered == ["Focus on the tokenizer"]+ assert "note" in monitor.control("stop")+ assert "error" in monitor.control("stop") # already gone: the gateway found nothing+ assert monitor.refresh()+ assert monitor.entries == []+++def test_idle_session_without_children_does_not_poll_the_roster(gateway):+ from hermes_cli.cli_subagent_monitor import SubagentMonitor+ agent, client = gateway+ client.children = []+ monitor = SubagentMonitor(SimpleNamespace(agent=agent, _agent_running=False))+ monitor.refresh()+ assert not any(method == "subagent.list" for method, _ in client.calls)