The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): /bg and /btw run in the gateway (prompt.background / prompt.btw), not in the CLI process
Tekniumf13bfa004a4e
diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.pyindex bf273c46da0..1bd5ccd7834 100644--- a/hermes_cli/cli_commands_mixin.py+++ b/hermes_cli/cli_commands_mixin.py@@ -1601,17 +1601,26 @@ class CLICommandsMixin(CLICommandsSessionToolsMixin):def _handle_background_command(self, cmd: str):"""Handle /bg <prompt> — run a prompt in a separate background session (its own AIAgenton a thread); the result prints here without touching the active history."""- from cli import set_approval_callback, set_secret_capture_callback, set_sudo_password_callback- from run_agent import AIAgentprompt = _command_arg(cmd)if not prompt:return _cp(*_lines(_t("background.usage")))self._background_task_counter += 1task_num = self._background_task_counter+ preview = _ellipsize(prompt, 60)+ from hermes_cli import gateway_side+ connection = gateway_side.connection_for(self)+ if connection is not None:+ # The gateway runs the side agent on this session's route (prompt.background); this+ # process never builds one.+ task_id, wait = gateway_side.start(connection, self.session_id, "background", prompt)+ _cp(f" {_t('background.started', number=task_num, preview=preview)}",+ f" {_t('background.task_id', task_id=task_id)}", f" {_t('background.keep_chatting')}\n")+ return self._start_background_worker(task_id, task_num, preview, wait)+ from cli import set_approval_callback, set_secret_capture_callback, set_sudo_password_callback+ from run_agent import AIAgenttask_id = f"bg_{datetime.now().strftime('%H%M%S')}_{uuid.uuid4().hex[:6]}"if not self._ensure_runtime_credentials():return _cp(f" {_t('background.no_credentials')}")- preview = _ellipsize(prompt, 60)_cp(f" {_t('background.started', number=task_num, preview=preview)}",f" {_t('background.task_id', task_id=task_id)}", f" {_t('background.keep_chatting')}\n")turn_route = self._resolve_turn_agent_config(prompt)@@ -1674,6 +1683,10 @@ class CLICommandsMixin(CLICommandsSessionToolsMixin):set_save_login_prompt_callback(None)set_code_prompt_callback(None)+ self._start_background_worker(task_id, task_num, preview, produce)++ def _start_background_worker(self, task_id, task_num, preview, produce):+ """The /bg result panel's daemon thread (``produce()`` returns the answer text)."""def done():self._background_tasks.pop(task_id, None)if not self._agent_running: # clear spinner only if no foreground agent owns it@@ -1766,6 +1779,19 @@ class CLICommandsMixin(CLICommandsSessionToolsMixin):question = _command_arg(cmd)if not question:return _cp(*_lines(_t("btw.usage")))+ from hermes_cli import gateway_side+ connection = gateway_side.connection_for(self)+ if connection is not None:+ # The gateway answers from its own copy of the conversation (prompt.btw): the live+ # agent's fork when it has one, else the stored transcript.+ _task_id, wait = gateway_side.start(connection, self.session_id, "btw", question)+ preview = _ellipsize(question, 60)+ _cp(*_lines(_gt("btw.started", preview=preview)), "")+ self._side_worker(wait, name="btw-side-question", fail_label="/btw",+ header_lines=[f" {_t('btw.header', preview=preview)}"],+ title_suffix=_t("btw.title_suffix"),+ empty_note=f" {_t('btw.no_answer')}").start()+ returnif not self._ensure_runtime_credentials():return _cp(f" {_t('btw.no_credentials')}")# Snapshot NOW, on the UI thread — the foreground turn keeps appending todiff --git a/hermes_cli/gateway_connection.py b/hermes_cli/gateway_connection.pyindex 5347fed9bbf..372ec7fd95e 100644--- a/hermes_cli/gateway_connection.py+++ b/hermes_cli/gateway_connection.py@@ -87,6 +87,10 @@ class GatewayConnection:self._stop = Noneself._start_lock = threading.Lock()self.closed = False+ # /bg and /btw answers by task id (hermes_cli/gateway_side.py); created by whichever of the+ # waiter or the frame comes first, so an answer faster than the verb's reply is kept.+ self._side: dict[str, queue.Queue] = {}+ self._side_lock = threading.Lock()@classmethoddef shared(cls):@@ -158,6 +162,8 @@ class GatewayConnection:self.events.put(frame)returnparams = frame.get("params") if isinstance(frame, dict) else None+ if isinstance(params, dict) and self._take_side(params):+ continueif isinstance(params, dict):sid = params.get("session_id")if sid in self.states:@@ -167,6 +173,22 @@ class GatewayConnection:logger.debug("session state update failed", exc_info=True)self.events.put(frame)+ def _take_side(self, params):+ from hermes_cli.gateway_side import SIDE_EVENTS+ payload = params.get("payload")+ if params.get("type") not in SIDE_EVENTS or not isinstance(payload, dict) or not payload.get("task_id"):+ return False+ self.side_waiter(payload["task_id"]).put(payload)+ return True++ def side_waiter(self, task_id) -> queue.Queue:+ with self._side_lock:+ return self._side.setdefault(task_id, queue.Queue())++ def drop_side_waiter(self, task_id):+ with self._side_lock:+ self._side.pop(task_id, None)+def close(self):loop, stop = self.loop, self._stopif loop is not None and stop is not None and not self.closed:diff --git a/hermes_cli/gateway_side.py b/hermes_cli/gateway_side.pynew file mode 100644index 00000000000..0c5a8098cf1--- /dev/null+++ b/hermes_cli/gateway_side.py@@ -0,0 +1,51 @@+"""``/bg`` and ``/btw`` on the shared gateway session (``prompt.background`` / ``prompt.btw``).++On main the classic CLI built a second ``AIAgent`` (``/bg``) or made a one-shot auxiliary call+(``/btw``) in its own process. Rewired, the side work runs in the gateway, like Ink's: the verb+replies ``{task_id}`` at once and the answer arrives later on the session's event stream as+``background.complete`` / ``btw.complete`` ``{task_id, text}`` (``error: <exc>`` on failure,+``gateway/session_tui_side.py``). The connection's pump hands those frames to the waiter+registered here, so neither the turn pump nor the idle notification tick can drop them.+"""+from __future__ import annotations++import queue++SIDE_EVENTS = frozenset({"background.complete", "btw.complete"})+_POLL_SECONDS = 1.0+++def connection_for(cli):+ """The CLI's gateway connection when its session is open, else None (not rewired)."""+ from hermes_cli.gateway_tools_notify import gateway_store+ store = gateway_store(cli)+ if store is None or not getattr(cli, "_gateway_session_open", False) or store.connection.closed:+ return None+ return store.connection+++def start(connection, session_id, verb, text):+ """Admit the side task on the owner: ``(task_id, wait)``; ``wait()`` -> the answer (raises on failure)."""+ result = connection.call(f"prompt.{verb}", session_id=session_id, text=text) or {}+ task_id = result.get("task_id")+ if not task_id:+ raise RuntimeError(f"prompt.{verb} returned no task id")+ inbox = connection.side_waiter(task_id)++ def wait():+ try:+ while True:+ try:+ payload = inbox.get(timeout=_POLL_SECONDS)+ except queue.Empty:+ if connection.closed:+ from hermes_cli.gateway_connection import DISCONNECTED+ raise RuntimeError(DISCONNECTED) from None+ continue+ answer = str((payload or {}).get("text") or "")+ if answer.startswith("error: "):+ raise RuntimeError(answer[len("error: "):])+ return answer+ finally:+ connection.drop_side_waiter(task_id)+ return task_id, waitdiff --git a/tests/hermes_cli/test_gateway_side.py b/tests/hermes_cli/test_gateway_side.pynew file mode 100644index 00000000000..c83c6529721--- /dev/null+++ b/tests/hermes_cli/test_gateway_side.py@@ -0,0 +1,59 @@+"""/bg and /btw on the shared gateway: the side task runs in the gateway (prompt.background /+prompt.btw) and its answer is routed off the event stream by task id, never built in the CLI."""+import asyncio+from contextlib import asynccontextmanager++import pytest++from hermes_cli import gateway_side+from hermes_cli.gateway_connection import GatewayConnection++SID = "local-side"+++class _Client:+ def __init__(self, text):+ self.events = asyncio.Queue()+ self.calls = []+ self.text = text++ async def rpc(self, method, *, _timeout=None, **params):+ self.calls.append((method, params))+ kind = "background.complete" if method == "prompt.background" else "btw.complete"+ # The answer can land before the verb's reply reaches the caller.+ await self.events.put({"jsonrpc": "2.0", "method": "event", "params": {+ "type": kind, "session_id": SID, "payload": {"task_id": "bg_1", "text": self.text}}})+ return {"task_id": "bg_1"}+++def _connection(client):+ @asynccontextmanager+ async def connect():+ yield client+ conn = GatewayConnection(connect=connect)+ conn.start(5)+ return conn++[email protected]("verb", ["background", "btw"])+def test_side_task_runs_on_the_gateway_and_its_answer_is_routed_by_task_id(verb):+ client = _Client("DOG14 background answer")+ conn = _connection(client)+ try:+ task_id, wait = gateway_side.start(conn, SID, verb, "compute something")+ assert task_id == "bg_1"+ assert wait() == "DOG14 background answer"+ assert client.calls == [(f"prompt.{verb}", {"session_id": SID, "text": "compute something"})]+ assert conn.events.empty() # never left for the turn pump / idle tick to drop+ finally:+ conn.close()+++def test_a_failed_side_task_raises_the_gateways_error():+ conn = _connection(_Client("error: model unavailable"))+ try:+ _task_id, wait = gateway_side.start(conn, SID, "background", "x")+ with pytest.raises(RuntimeError, match="model unavailable"):+ wait()+ finally:+ conn.close()