Skip to content

The agent that grows with you

fix(cli): the gateway's sudo prompt opens main's masked sudo panel and answers it

Teknium32b924e1055b
diff --git a/hermes_cli/gateway_agent.py b/hermes_cli/gateway_agent.py
index b7e94588a83..236b1f1980e 100644
--- a/hermes_cli/gateway_agent.py
+++ b/hermes_cli/gateway_agent.py
@@ -414,6 +414,9 @@ class GatewayAgent:
params = frame.get("params") if isinstance(frame, dict) else None
if not isinstance(params, dict) or params.get("session_id") != self.session_id:
continue
+ if frame.get("method") in _SERVER_REQUESTS and "id" in frame:
+ self._answer_request(frame)
+ continue
kind, payload = params.get("type"), params.get("payload") or {}
admission = params.get("admission_id") or (payload.get("admission_id") if isinstance(payload, dict) else None)
if self._admission and admission and admission != self._admission:
@@ -579,6 +582,22 @@ class GatewayAgent:
execution_generation=payload.get("execution_generation", self._generation),
prompt_id=payload.get("prompt_id"), answer=str(answer))
+ def _answer_request(self, frame):
+ """A gateway server→client request (``sudo``): main's own modal answers it on this (agent)
+ thread, through the callback HermesCLI registered for the turn; the value travels only in the
+ JSON-RPC response frame."""
+ try:
+ value = _SERVER_REQUESTS[frame["method"]](self, frame.get("params") or {})
+ except Exception: # health: allow BLE001 -- a broken modal is a skip, never a hung tool
+ logger.debug("server request %s failed", frame.get("method"), exc_info=True)
+ value = ""
+ self.connection.reply(frame["id"], {"value": value if isinstance(value, str) else ""})
+
+ def _ask_sudo(self, params):
+ from tools.terminal_tool import _get_sudo_password_callback
+ callback = _get_sudo_password_callback()
+ return (callback() or "") if callback is not None else ""
+
# -- result --------------------------------------------------------------------------------
def _user_row(self, user_message):
staged = self._pending_cli_user_message
@@ -713,6 +732,10 @@ def _moa_handler(kind):
return handler
+_SERVER_REQUESTS = {
+ "sudo": GatewayAgent._ask_sudo,
+}
+
_HANDLERS = {
"message.delta": GatewayAgent._on_delta,
"message.interim": GatewayAgent._on_interim,
diff --git a/hermes_cli/gateway_connection.py b/hermes_cli/gateway_connection.py
index 7ccc2450ac8..62b6668b499 100644
--- a/hermes_cli/gateway_connection.py
+++ b/hermes_cli/gateway_connection.py
@@ -177,6 +177,21 @@ class GatewayConnection:
self.closed = True
# -- requests ----------------------------------------------------------------------------
+ def reply(self, request_id, result):
+ """Answer one of the gateway's server→client requests (the ``sudo`` prompt): a JSON-RPC
+ response frame with the request's own id. Never raises; a lost reply times out gateway-side."""
+ import json
+ client, loop = self.client, self.loop
+ if client is None or loop is None:
+ return False
+ frame = json.dumps({"jsonrpc": "2.0", "id": request_id, "result": result})
+ try:
+ asyncio.run_coroutine_threadsafe(client.websocket.send(frame), loop).result(10)
+ except Exception as exc: # health: allow BLE001 -- the gateway's own wait bounds a lost answer
+ logger.debug("server request reply failed: %s", exc)
+ return False
+ return True
+
def call(self, method, *, timeout=None, **params):
if self._thread is not None and threading.current_thread() is self._thread:
raise RuntimeError("GatewayConnection.call() on the gateway loop thread would deadlock")
diff --git a/tests/hermes_cli/test_gateway_agent.py b/tests/hermes_cli/test_gateway_agent.py
index 39edd75ae14..f424917ea34 100644
--- a/tests/hermes_cli/test_gateway_agent.py
+++ b/tests/hermes_cli/test_gateway_agent.py
@@ -363,3 +363,40 @@ def test_reasoning_sink_sets_the_sessions_show_reasoning_flag_on_attach_and_togg
agent.reasoning_callback = shown.append # /reasoning show
values = [p["value"] for m, p in client.calls if m == "config.set" and p.get("key") == "show_reasoning"]
assert values == ["1", "0", "1"]
+
+
+def test_gateway_sudo_request_opens_mains_sudo_panel_and_replies_with_the_value(make_agent):
+ """The gateway's ``sudo`` server→client request (a JSON-RPC request frame with an ``srq-`` id)
+ is answered by main's masked sudo panel (the turn's registered callback) as a response frame."""
+ from tools.terminal_tool import set_sudo_password_callback
+ request = {"jsonrpc": "2.0", "id": "srq-abc", "method": "sudo",
+ "params": {"session_id": SID, "command": "sudo true"}}
+ agent, _ = make_agent([request, frame("message.complete", {"text": "ok", "outcome": "completed"})])
+ replies = []
+ agent.connection.reply = lambda rid, result: replies.append((rid, result)) or True
+ asked = []
+ set_sudo_password_callback(lambda: asked.append(1) or "pw-from-panel")
+ try:
+ agent.run_conversation("run sudo")
+ finally:
+ set_sudo_password_callback(None)
+ assert asked == [1]
+ assert replies == [("srq-abc", {"value": "pw-from-panel"})]
+
+
+def test_connection_reply_sends_a_jsonrpc_response_frame():
+ sent = []
+
+ class WS:
+ async def send(self, raw):
+ sent.append(raw)
+ client = FakeClient([])
+ client.websocket = WS()
+ conn = GatewayConnection(connect=connect_with(client))
+ conn.start(5)
+ try:
+ assert conn.reply("srq-1", {"value": ""}) is True
+ finally:
+ conn.close()
+ import json
+ assert [json.loads(raw) for raw in sent] == [{"jsonrpc": "2.0", "id": "srq-1", "result": {"value": ""}}]