The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): the process dock, status-bar ⚙ count and /stop read the gateway session's processes
Tekniumbf94644b99f1
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 8f31a77378b..8854b7e67cc 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -3661,6 +3661,7 @@ export interface ProcessStopParams {}export interface ProcessStopResult {killed: number+ delegations?: number}export interface AgentsListParams {profile?: string | null@@ -3699,6 +3700,7 @@ export interface ProcessEntry {notify_on_complete?: boolean | nullexit_code?: number | nullexited_at?: number | null+ started_epoch?: number | nullcompletion_reason?: string | nulldetached?: boolean | null[key: string]: unknowndiff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 8f07d578c25..f5a6b9e9a6a 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -27521,6 +27521,18 @@"default": null,"title": "Exited At"},+ "started_epoch": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Started Epoch"+ },"completion_reason": {"anyOf": [{@@ -27768,6 +27780,11 @@"killed": {"title": "Killed","type": "integer"+ },+ "delegations": {+ "default": 0,+ "title": "Delegations",+ "type": "integer"}},"required": [diff --git a/gateway/session_ancillary.py b/gateway/session_ancillary.pyindex 3fad343fce2..7d9978fed01 100644--- a/gateway/session_ancillary.py+++ b/gateway/session_ancillary.py@@ -17,6 +17,7 @@ _SUBAGENT_FIELDS = ('started_at', 'status', 'tool_count', 'last_tool', 'accepting_steer',)_TAIL_BYTES = 16384+_PROCESS_TAIL_CHARS = 32768 # main's dock tail view (cli_process_dock.process_tail)def handlers(connection):@@ -213,7 +214,18 @@ async def stop_processes(connection, ref, params):results = [registry.kill_process(pid, source='process.stop', consume_output=False) for pid in targets]return sum(r.get('status') in {'killed', 'already_exited'} and 'scope_stop_failed' not in rfor r in results)- return {'killed': await asyncio.to_thread(kill) if targets else 0}+ killed = await asyncio.to_thread(kill) if targets else 0+ return {'killed': killed, 'delegations': await asyncio.to_thread(_interrupt_delegations, connection.authority, ref)}+++def _interrupt_delegations(authority, ref):+ """Main's ``/stop`` also interrupted the background (async) delegations; here only the ones this+ session dispatched (its route or its durable id), never another chat's."""+ module = sys.modules.get('tools.async_delegation')+ if module is None:+ return 0+ return module.interrupt_for_session(session_key=authority.sessions[ref.session_id].route,+ parent_session_id=physical_target(authority, ref), reason='/stop')def _require_current_route(authority, ref):@@ -334,4 +346,7 @@ def process_snapshot(authority, ref, agent, records):with registry._lock:return [{'session_id': p.id, 'command': p.command[:200],'status': 'exited' if p.exited else 'running', 'exit_code': p.exit_code,- 'output_tail': p.output_buffer[-4000:]} for p in _owned_locked(registry, keys, owners)]+ # The classic CLI dock's elapsed / exit-age / verdict and its 32k tail view.+ 'started_epoch': p.started_at, 'exited_at': p.exited_at or None,+ 'completion_reason': p.completion_reason if p.exited else None,+ 'output_tail': p.output_buffer[-_PROCESS_TAIL_CHARS:]} for p in _owned_locked(registry, keys, owners)]diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.pyindex 837614a04ff..760639a9840 100644--- a/hermes_cli/cli_agent_setup_mixin.py+++ b/hermes_cli/cli_agent_setup_mixin.py@@ -721,6 +721,8 @@ class CLIAgentSetupMixin:# subagent/background completion notice never splits the reply mid-paragraph.self.agent._print_fn = self._agent_status_printself.agent._finite = single_query_mode # -q/-Q: a finite gateway admission (headless clarify)+ from hermes_cli.gateway_tools import bind+ bind(self.agent) # main's dock / status bar / /stop read this session's gateway processes# Hydrate credits notices at session OPEN (parity with the TUI) so a depletion# warning shows before the first message. Idempotent + fail-open in the helper.try:diff --git a/hermes_cli/cli_commands_session_tools.py b/hermes_cli/cli_commands_session_tools.pyindex a2cc2be3b31..e318c2316a6 100644--- a/hermes_cli/cli_commands_session_tools.py+++ b/hermes_cli/cli_commands_session_tools.py@@ -101,18 +101,25 @@ class CLICommandsSessionToolsMixin:See #14602."""- from tools.process_registry import process_registry+ from hermes_cli.gateway_tools import process_registry as _registry, process_view+ process_registry, view = _registry(), process_view()+ if view is not None:+ view.refresh(force=True)running = [p for p in process_registry.list_sessions() if p.get("status") == "running"]# Background subagents live in their own registry, not the process registry.- n_async = _probe("tools.async_delegation", "active_count", 0)+ n_async = view.active_delegations() if view is not None else _probe("tools.async_delegation", "active_count", 0)if not running and not n_async:return print(f" {_t('stop.none_running')}")if running:print(f" {_t('stop.stopping', count=len(running))}")print(f" {_t('stop.stopped', count=process_registry.kill_all(source='cli.stop'))}")if n_async:- from tools.async_delegation import interrupt_all- print(f" {_t('stop.interrupted_delegations', count=interrupt_all(reason='/stop'))}")+ if view is not None:+ interrupted = view.interrupt_delegations() # the gateway interrupts this session's own+ else:+ from tools.async_delegation import interrupt_all+ interrupted = interrupt_all(reason='/stop')+ print(f" {_t('stop.interrupted_delegations', count=interrupted)}")def _handle_agents_command(self):"""Handle /agents — show background processes and agent status."""diff --git a/hermes_cli/cli_process_dock.py b/hermes_cli/cli_process_dock.pyindex ceee075a9fb..3336cceee2d 100644--- a/hermes_cli/cli_process_dock.py+++ b/hermes_cli/cli_process_dock.py@@ -43,7 +43,8 @@ def process_rows(now: float | None = None) -> list:spawns and any a child handed back) belongs to this dock; gateway-hosted surfaces scopeby session key in ``tui_gateway`` instead."""- from tools.process_registry import process_registry+ from hermes_cli.gateway_tools import process_registry as _registry+ process_registry = _registry() # the gateway session's processes (rewired CLI)now = time.time() if now is None else nowrows = []@@ -93,7 +94,8 @@ def process_glyph(row: dict) -> str:def process_tail(process_id: str) -> str:- from tools.process_registry import process_registry+ from hermes_cli.gateway_tools import process_registry as _registry+ process_registry = _registry() # the gateway session's processes (rewired CLI)proc = process_registry.get(process_id)if proc is None:@@ -104,6 +106,7 @@ def process_tail(process_id: str) -> str:def kill(process_id: str) -> dict:- from tools.process_registry import process_registry+ from hermes_cli.gateway_tools import process_registry as _registry+ process_registry = _registry() # the gateway session's processes (rewired CLI)return process_registry.kill_process(process_id)diff --git a/hermes_cli/cli_status_bar_mixin.py b/hermes_cli/cli_status_bar_mixin.pyindex 67aac0e1261..89a92e28de9 100644--- a/hermes_cli/cli_status_bar_mixin.py+++ b/hermes_cli/cli_status_bar_mixin.py@@ -273,13 +273,18 @@ class CLIStatusBarMixin:except Exception:passtry:- from tools.process_registry import process_registry- snapshot["active_background_processes"] = process_registry.count_running()+ from hermes_cli.gateway_tools import process_registry+ snapshot["active_background_processes"] = process_registry().count_running()except Exception:passtry:- from tools.async_delegation import active_count as _async_active_count- snapshot["active_background_subagents"] = _async_active_count()+ from hermes_cli.gateway_tools import process_view+ _view = process_view()+ if _view is not None:+ snapshot["active_background_subagents"] = _view.active_delegations()+ else:+ from tools.async_delegation import active_count as _async_active_count+ snapshot["active_background_subagents"] = _async_active_count()except Exception:passdiff --git a/hermes_cli/gateway_agent.py b/hermes_cli/gateway_agent.pyindex a47e5168de6..0e09d58c9be 100644--- a/hermes_cli/gateway_agent.py+++ b/hermes_cli/gateway_agent.py@@ -610,6 +610,8 @@ class GatewayAgent:self.tool_progress_callback("tool.completed", name, None, None, duration=duration,is_error=bool(payload.get("is_error")), result=result)self._usage_stale = True+ from hermes_cli.gateway_tools import mark_dirty+ mark_dirty() # a terminal/process call may have started or stopped a background processif name == "todo":self._todo_from_result(result)diff = payload.get("inline_diff")diff --git a/hermes_cli/gateway_tools.py b/hermes_cli/gateway_tools.pynew file mode 100644index 00000000000..cf62b2f8590--- /dev/null+++ b/hermes_cli/gateway_tools.py@@ -0,0 +1,157 @@+"""The background-process registry main's classic CLI reads, served by the gateway session.++On main the CLI process ran every ``terminal(background=true)`` itself, so the live-work dock,+the status bar's ``⚙ N`` segment, ``/stop`` and the dock's tail view read+``tools.process_registry`` in-process. Rewired, the processes run in the gateway: this view+answers the same calls (``list_sessions`` / ``get`` / ``count_running`` / ``kill_process`` /+``kill_all``) from the session's ``process.list`` / ``process.kill`` / ``process.stop`` verbs, so+main's dock and command code render unchanged.++Polling: the dock ticks once a second. The view only asks the gateway while it has a reason to+(a tool finished since the last poll, or a listed process is still running or recently+exited); the status bar reads the cached count and never blocks a repaint on an RPC.+"""+from __future__ import annotations++import logging+import threading+import time++from hermes_cli.gateway_client import GatewayClientError++logger = logging.getLogger(__name__)++_POLL_SECONDS = 1.0+# A finished process stays interesting this long (main's dock RETAIN_SECONDS).+_RETAIN_SECONDS = 60++_view = None+++class _Proc:+ """The ``ProcessSession`` attributes main's dock reads."""++ def __init__(self, row):+ self.id = row.get("session_id") or ""+ self.command = row.get("command") or ""+ self.exit_code = row.get("exit_code")+ self.started_at = float(row.get("started_epoch") or 0.0)+ self.exited_at = float(row.get("exited_at") or 0.0)+ self.output_buffer = row.get("output_tail") or ""+ self.completion_reason = row.get("completion_reason") or "exited"+ self.exited = row.get("status") == "exited"+++class GatewayProcessView:+ def __init__(self, agent):+ self.agent = agent+ self.connection = agent.connection+ self.rows: list = []+ self.dirty = True+ self.delegations = 0+ self._polled = 0.0+ self._lock = threading.Lock()++ @property+ def session_id(self):+ return self.agent.session_id # follows /new, /resume and compression rotations++ # -- polling ---------------------------------------------------------------------------+ def mark_dirty(self):+ self.dirty = True++ def _interesting(self, now):+ return any(not p.exited or (p.exited_at and now - p.exited_at <= _RETAIN_SECONDS) for p in self.rows)++ def refresh(self, *, force=False):+ now = time.time()+ if not force and (now - self._polled < _POLL_SECONDS or not (self.dirty or self._interesting(now))):+ return+ if not self._lock.acquire(blocking=False):+ return+ try:+ self._polled = now+ self.dirty = False+ result = self.connection.call("process.list", session_id=self.session_id, timeout=5)+ self.rows = [_Proc(row) for row in (result or {}).get("processes") or []]+ except (GatewayClientError, RuntimeError) as exc:+ logger.debug("process.list failed: %s", exc)+ finally:+ self._lock.release()++ # -- the tools.process_registry surface main's CLI calls ---------------------------------+ def list_sessions(self):+ self.refresh()+ now = time.time()+ return [{"session_id": p.id, "command": p.command[:200],+ "status": "exited" if p.exited else "running", "exit_code": p.exit_code,+ "completion_reason": p.completion_reason if p.exited else None,+ "uptime_seconds": int(now - p.started_at) if p.started_at else 0} for p in self.rows]++ def get(self, process_id):+ return next((p for p in self.rows if p.id == process_id), None)++ def count_running(self):+ """Cached (the status bar repaints off the render thread)."""+ return sum(1 for p in self.rows if not p.exited)++ def kill_process(self, process_id, **_kw):+ try:+ result = self.connection.call("process.kill", session_id=self.session_id, process_id=process_id)+ except GatewayClientError as exc:+ return {"status": "error", "error": str(exc)}+ self.refresh(force=True)+ return result++ def kill_all(self, **_kw):+ """``/stop``: the session's own processes plus its background delegations (``process.stop``)."""+ result = self.connection.call("process.stop", session_id=self.session_id) or {}+ self.delegations = int(result.get("delegations") or 0)+ self.refresh(force=True)+ return int(result.get("killed") or 0)++ def interrupt_delegations(self):+ """The delegation half of ``/stop`` (``kill_all`` already ran it when processes were live)."""+ if self.delegations:+ count, self.delegations = self.delegations, 0+ return count+ self.kill_all()+ count, self.delegations = self.delegations, 0+ return count++ def active_delegations(self):+ """Running background subagents (the gateway's ``session.usage.active_subagents``)."""+ try:+ usage = self.connection.state(self.session_id).usage or {}+ except Exception: # health: allow BLE001 -- a missing usage cache reads as none running+ return 0+ value = usage.get("active_subagents")+ return value if isinstance(value, int) else 0+++def bind(agent):+ """Called when the CLI's gateway-backed agent is built."""+ global _view+ _view = GatewayProcessView(agent) if getattr(agent, "connection", None) is not None else None+ return _view+++def mark_dirty():+ if _view is not None:+ _view.mark_dirty()+++def process_view():+ """The gateway-backed registry, or None when this process runs its own tools (not rewired) or+ its gateway connection is gone."""+ view = _view+ return view if view is not None and not view.connection.closed else None+++def process_registry():+ """``tools.process_registry.process_registry`` for main's dock, status bar and ``/stop``."""+ view = process_view()+ if view is not None:+ return view+ from tools.process_registry import process_registry as local+ return localdiff --git a/tests/hermes_cli/test_gateway_tools.py b/tests/hermes_cli/test_gateway_tools.pynew file mode 100644index 00000000000..73cbc5a35d3--- /dev/null+++ b/tests/hermes_cli/test_gateway_tools.py@@ -0,0 +1,98 @@+"""Main's process dock, status-bar ``⚙ N`` and ``/stop`` read the gateway session's processes.++Rewired, ``terminal(background=true)`` runs in the gateway, so the CLI process's own+``tools.process_registry`` is empty. ``hermes_cli.gateway_tools`` answers main's registry calls from+``process.list`` / ``process.kill`` / ``process.stop`` (scripted fake gateway, no live gateway).+"""+import asyncio+import time+from contextlib import asynccontextmanager++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 = []+ now = time.time()+ self.processes = [+ {"session_id": "proc_1", "command": "sleep 300", "status": "running", "exit_code": None,+ "started_epoch": now - 5, "exited_at": None, "completion_reason": None,+ "output_tail": "tick 1\ntick 2\n"},+ {"session_id": "proc_2", "command": "echo hi", "status": "exited", "exit_code": 0,+ "started_epoch": now - 9, "exited_at": now - 3, "completion_reason": "exited",+ "output_tail": "hi\n"},+ ]++ async def rpc(self, method, *, _timeout=None, **params):+ self.calls.append((method, params))+ if method == "process.list":+ return {"processes": self.processes}+ if method == "process.stop":+ for row in self.processes:+ if row["status"] == "running":+ row.update(status="exited", exited_at=time.time(), completion_reason="killed", exit_code=-15)+ return {"killed": 1, "delegations": 0}+ if method == "process.kill":+ return {"status": "killed", "session_id": params["process_id"]}+ return {}+++def gateway():+ 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_dock_rows_come_from_the_gateway_session(gateway):+ from hermes_cli import cli_process_dock as dock+ _agent, client = gateway+ rows = dock.process_rows()+ assert [(r["id"], r["status"]) for r in rows] == [("proc_1", "running"), ("proc_2", "done")]+ assert rows[0]["command"] == "sleep 300" and rows[0]["detail"] == "tick 2" and rows[0]["elapsed"] >= 4+ assert rows[1]["exit_code"] == 0 and rows[1]["since_exit"] >= 2+ assert ("process.list", {"session_id": SID}) in client.calls+ assert dock.process_tail("proc_1") == "tick 1\ntick 2\n"+++def test_status_bar_count_reads_the_cached_gateway_count(gateway):+ _agent, client = gateway+ gateway_tools.process_registry().list_sessions()+ polls = len(client.calls)+ assert gateway_tools.process_registry().count_running() == 1+ assert len(client.calls) == polls # the render thread never waits on an RPC+++def test_stop_kills_the_session_processes_through_the_gateway(gateway, capsys):+ from hermes_cli.cli_commands_session_tools import CLICommandsSessionToolsMixin+ _agent, client = gateway+ CLICommandsSessionToolsMixin._handle_stop_command(object())+ out = capsys.readouterr().out+ assert "Stopping 1 background process(es)..." in out and "Stopped 1 process(es)." in out+ assert any(method == "process.stop" for method, _ in client.calls)+++def test_dock_stop_kills_one_process_through_the_gateway(gateway):+ from hermes_cli import cli_process_dock as dock+ _agent, client = gateway+ dock.process_rows()+ assert dock.kill("proc_1")["status"] == "killed"+ assert ("process.kill", {"session_id": SID, "process_id": "proc_1"}) in client.callsdiff --git a/tui_gateway/contracts/tools_commands.py b/tui_gateway/contracts/tools_commands.pyindex cc88e8962be..6026b97d65a 100644--- a/tui_gateway/contracts/tools_commands.py+++ b/tui_gateway/contracts/tools_commands.py@@ -58,6 +58,7 @@ class ProcessStopParams(Params):class ProcessStopResult(Result):killed: int+ delegations: int = 0method("process.stop", params=ProcessStopParams, result=ProcessStopResult,@@ -108,6 +109,7 @@ class ProcessEntry(_Open):notify_on_complete: bool | None = Noneexit_code: int | None = Noneexited_at: float | None = None+ started_epoch: float | None = Nonecompletion_reason: str | None = Nonedetached: bool | None = None