Skip to content

The agent that grows with you

fix(gateway): the sudo password prompt reaches a local viewer

Teknium2e0188deece7
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.py
index 85f58b6810f..e5c7c8c5453 100644
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@ -1238,8 +1238,10 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
persist_msg, persist_ts = self._prepare_turn_message(agent_history)
compressions = getattr(getattr(agent, "context_compressor", None), "compression_count", None)
from gateway.session_cli_turn import run_classic_cli_turn
- result = run_classic_cli_turn(self, lambda: self._run_conversation_with_approval(
- agent, agent_history, observed_group_context, persist_msg, persist_ts))
+ from gateway.session_sudo_prompt import sudo_prompt_scope
+ with sudo_prompt_scope(self, agent):
+ result = run_classic_cli_turn(self, lambda: self._run_conversation_with_approval(
+ agent, agent_history, observed_group_context, persist_msg, persist_ts))
finally:
if local_sinks is not None:
from gateway import local_viewer_events
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 5f049b5715a..95f41d62775 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -109,6 +109,13 @@ class AuthorityConnection:
return handlers
async def dispatch(self, request):
+ from gateway.session_sudo_prompt import is_response_frame
+ if is_response_frame(request):
+ # A viewer answering one of the owner's server→client requests (the sudo prompt): a
+ # response gets no reply (JSON-RPC), and only a viewer entitled to respond on that
+ # session settles it.
+ self._resolve_response(request)
+ return None
rid = request.get('id')
method = request.get('method')
params = request.get('params') or {}
@@ -526,6 +533,19 @@ class AuthorityConnection:
return asdict(self.authority._handle(ref))
return asdict(await self.authority.interrupt(self.actor, ref, params.get('execution_generation')))
+ def _resolve_response(self, frame):
+ from gateway.session_sudo_prompt import resolve
+
+ def entitled(session_id):
+ try:
+ self.authority.authorize(self.actor, SessionRef(self.actor.profile_id, session_id), 'session:respond')
+ except RuntimeStoreError:
+ return False
+ return True
+ if not resolve(frame, session_ok=entitled):
+ import logging
+ logging.getLogger(__name__).debug('dropping response for unknown server request id=%r', frame.get('id'))
+
async def respond(self, ref, params):
if set(params) != {"session_id", "execution_generation", "prompt_id", "choice"}:
raise RuntimeStoreError("invalid_params")
diff --git a/gateway/session_sudo_prompt.py b/gateway/session_sudo_prompt.py
new file mode 100644
index 00000000000..4791c2aa734
--- /dev/null
+++ b/gateway/session_sudo_prompt.py
@@ -0,0 +1,114 @@
+"""The masked sudo password prompt for a local viewer's turn.
+
+Main's TUI sidecar registered ``set_sudo_password_callback`` per session (``tui_gateway/agent_callbacks.py``):
+the terminal tool's sudo rewrite asked the renderer through a ``sudo`` server→client request and the
+Ink card answered with ``{value}``. On the session authority no callback was registered, so the tool
+took the headless path (``sudo: a terminal is required``). Here the owner sends the same ``sudo``
+request frame (``tui_gateway/contracts/server_requests.py``) to the viewers attached to the session's
+event stream and blocks the agent thread until one answers, the turn is interrupted, or it times out.
+The password is never published, journaled or logged: it travels only in the viewer's response frame.
+"""
+from __future__ import annotations
+
+import contextlib
+import logging
+import threading
+import uuid
+
+logger = logging.getLogger(__name__)
+
+SUDO_TIMEOUT_S = 120 # main: ``_ask("sudo", ..., timeout=120)``
+_POLL_S = 0.25
+
+
+class _Pending:
+ __slots__ = ("event", "session_id", "value")
+
+ def __init__(self, session_id):
+ self.event = threading.Event()
+ self.session_id = session_id
+ self.value = ""
+
+
+_lock = threading.Lock()
+_open: dict[str, _Pending] = {}
+
+
+def is_response_frame(frame) -> bool:
+ """A viewer's answer to one of the owner's requests: a string ``srq-`` id, a result/error, no method."""
+ return (isinstance(frame, dict) and "method" not in frame and isinstance(frame.get("id"), str)
+ and frame["id"].startswith("srq-") and ("result" in frame or "error" in frame))
+
+
+def resolve(frame, *, session_ok=lambda session_id: True) -> bool:
+ """Settle the open request *frame* answers; False when nothing (here) waits for that id.
+ ``session_ok`` lets the caller refuse an answer from a connection not entitled to that session."""
+ with _lock:
+ pending = _open.get(frame["id"])
+ if pending is None or not session_ok(pending.session_id):
+ return False
+ _open.pop(frame["id"], None)
+ result = frame.get("result")
+ value = result.get("value") if isinstance(result, dict) and "error" not in frame else ""
+ pending.value = value if isinstance(value, str) else ""
+ pending.event.set()
+ return True
+
+
+def ask_sudo(events, session_id, command, *, cancelled=lambda: False, timeout=SUDO_TIMEOUT_S) -> str:
+ """Send one ``sudo`` request to the session's attached viewers and wait for its ``value``.
+ "" when nobody is attached, the viewer skipped, the turn was interrupted, or it timed out."""
+ if not events.fanout.transports():
+ return ""
+ request_id = f"srq-{uuid.uuid4().hex[:12]}"
+ pending = _Pending(session_id)
+ with _lock:
+ _open[request_id] = pending
+ events.fanout.write({"jsonrpc": "2.0", "id": request_id, "method": "sudo",
+ "params": {"session_id": session_id, "command": command}})
+ waited = 0.0
+ reason = "timeout"
+ while not pending.event.wait(_POLL_S):
+ waited += _POLL_S
+ if cancelled():
+ reason = "interrupted"
+ break
+ if waited >= timeout:
+ break
+ with _lock:
+ still_open = _open.pop(request_id, None) is pending
+ if still_open:
+ # The same teardown main's renderers key on (``request.cancel``): the card closes and a
+ # timed-out password prompt says so.
+ with contextlib.suppress(Exception):
+ events.publish(session_id, {"id": request_id, "method": "sudo", "reason": reason},
+ event_type="request.cancel")
+ return ""
+ return pending.value
+
+
+def sudo_prompt_scope(turn, agent):
+ """Install the sudo callback on this (agent) thread for a local viewer's turn; restore after."""
+ from gateway.run_turn_progress import local_viewer_turn
+ if not local_viewer_turn(turn):
+ yield
+ return
+ from tools.terminal_tool import _get_sudo_password_callback, set_sudo_password_callback
+ authority, session_id, _generation = turn._approval_owner
+
+ def callback():
+ from gateway.run import _redact_approval_command
+ from tools.terminal_tool_sudo import get_sudo_prompt_command
+ live = authority.sessions.get(session_id)
+ if live is None:
+ return ""
+ return ask_sudo(live.event_stream, session_id, _redact_approval_command(get_sudo_prompt_command()),
+ cancelled=lambda: bool(getattr(agent, "_interrupt_requested", False)))
+
+ previous = _get_sudo_password_callback()
+ set_sudo_password_callback(callback)
+ try:
+ yield
+ finally:
+ set_sudo_password_callback(previous)
diff --git a/tests/gateway/test_local_viewer_sudo_prompt.py b/tests/gateway/test_local_viewer_sudo_prompt.py
new file mode 100644
index 00000000000..75cb337d377
--- /dev/null
+++ b/tests/gateway/test_local_viewer_sudo_prompt.py
@@ -0,0 +1,111 @@
+"""A local viewer's turn asks for the sudo password through the TUI's masked prompt, as main's sidecar
+did (``tui_gateway/agent_callbacks.py`` ``set_sudo_password_callback``): FINDINGS row 9, where the
+canonical owner registered no callback and ``sudo`` failed headless in 0.1 s."""
+import threading
+import time
+from types import SimpleNamespace
+
+import pytest
+
+from gateway.config import Platform
+
+
+class _Peer:
+ def __init__(self):
+ self.frames = []
+
+ def write(self, frame):
+ self.frames.append(frame)
+ return True
+
+ def close(self):
+ pass
+
+
+def _events():
+ from gateway.session_events import SessionEvents
+ events, peer = SessionEvents(), _Peer()
+ events.fanout.attach(peer)
+ return events, peer
+
+
+def _wait_for(predicate, timeout=5.0):
+ deadline = time.monotonic() + timeout
+ while not predicate():
+ assert time.monotonic() < deadline
+ time.sleep(0.01)
+
+
+def test_sudo_request_reaches_the_viewer_and_its_answer_returns():
+ from gateway.session_sudo_prompt import ask_sudo, is_response_frame, resolve
+ events, peer = _events()
+ out = {}
+ worker = threading.Thread(target=lambda: out.setdefault('value', ask_sudo(events, 's1', 'sudo true')))
+ worker.start()
+ _wait_for(lambda: any(f.get('method') == 'sudo' for f in peer.frames))
+ request = next(f for f in peer.frames if f.get('method') == 'sudo')
+ assert request['params'] == {'session_id': 's1', 'command': 'sudo true'}
+ from tui_gateway.contracts.registry import SERVER_REQUESTS, validate_params
+ assert validate_params(SERVER_REQUESTS['sudo'], request['params'])[1] is None
+ answer = {'jsonrpc': '2.0', 'id': request['id'], 'result': {'value': 'hunter2'}}
+ assert is_response_frame(answer) and resolve(answer)
+ worker.join(5)
+ assert out['value'] == 'hunter2'
+ # The password never rides the event stream.
+ assert not any('hunter2' in repr(f) for f in peer.frames)
+
+
+def test_interrupt_withdraws_the_card():
+ from gateway.session_sudo_prompt import ask_sudo
+ events, peer = _events()
+ flag = threading.Event()
+ out = {}
+ worker = threading.Thread(target=lambda: out.setdefault(
+ 'value', ask_sudo(events, 's1', 'sudo true', cancelled=flag.is_set)))
+ worker.start()
+ _wait_for(lambda: any(f.get('method') == 'sudo' for f in peer.frames))
+ flag.set()
+ worker.join(5)
+ assert out['value'] == ''
+ _wait_for(lambda: any(f.get('params', {}).get('type') == 'request.cancel' for f in peer.frames))
+
+
+def test_no_attached_viewer_is_headless():
+ from gateway.session_events import SessionEvents
+ from gateway.session_sudo_prompt import ask_sudo
+ assert ask_sudo(SessionEvents(), 's1', 'sudo true', timeout=0.1) == ''
+
+
[email protected](('platform', 'installed'), [(Platform.LOCAL, True), (Platform.TELEGRAM, False)])
+def test_scope_installs_the_callback_only_for_local_viewer_turns(platform, installed):
+ from gateway.session_sudo_prompt import sudo_prompt_scope
+ from tools.terminal_tool import _get_sudo_password_callback
+ events, _ = _events()
+ authority = SimpleNamespace(sessions={'s1': SimpleNamespace(event_stream=events)})
+ turn = SimpleNamespace(_approval_owner=(authority, 's1', 1),
+ _ctx=SimpleNamespace(source=SimpleNamespace(platform=platform)))
+ before = _get_sudo_password_callback()
+ with sudo_prompt_scope(turn, SimpleNamespace()):
+ assert (_get_sudo_password_callback() is not None) is installed
+ assert _get_sudo_password_callback() is before
+
+
+async def test_the_viewer_response_frame_is_routed_by_the_authority_connection(tmp_path, monkeypatch):
+ from gateway import session_sudo_prompt
+ from gateway.session_controls import AuthorityConnection
+ from tests.gateway.test_surface_admission import _authority
+
+ async def answer(event):
+ return 'ok'
+ authority = await _authority(tmp_path, monkeypatch, answer)
+ connection = AuthorityConnection(authority, object(), {'user_id': 'owner'})
+ pending = session_sudo_prompt._Pending('s')
+ session_sudo_prompt._open['srq-abc'] = pending
+ try:
+ reply = await connection.dispatch({'jsonrpc': '2.0', 'id': 'srq-abc', 'result': {'value': 'pw'}})
+ assert reply is None
+ assert pending.event.is_set() and pending.value == 'pw'
+ finally:
+ session_sudo_prompt._open.pop('srq-abc', None)
+ await connection.close()