session_sudo_prompt.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. """The masked sudo password prompt for a local viewer's turn.
  2. Main's TUI sidecar registered ``set_sudo_password_callback`` per session (``tui_gateway/agent_callbacks.py``):
  3. the terminal tool's sudo rewrite asked the renderer through a ``sudo`` server→client request and the
  4. Ink card answered with ``{value}``. On the session authority no callback was registered, so the tool
  5. took the headless path (``sudo: a terminal is required``). Here the owner sends the same ``sudo``
  6. request frame (``tui_gateway/contracts/server_requests.py``) to the viewers attached to the session's
  7. event stream and blocks the agent thread until one answers, the turn is interrupted, or it times out.
  8. The password is never published, journaled or logged: it travels only in the viewer's response frame.
  9. The request registry itself is ``gateway/session_server_requests.py``.
  10. """
  11. from __future__ import annotations
  12. import contextlib
  13. import logging
  14. logger = logging.getLogger(__name__)
  15. SUDO_TIMEOUT_S = 120 # main: ``_ask("sudo", ..., timeout=120)``
  16. def ask_sudo(events, session_id, command, *, cancelled=lambda: False, timeout=SUDO_TIMEOUT_S) -> str:
  17. """Send one ``sudo`` request to the session's attached viewers and wait for its ``value``.
  18. "" when nobody is attached, the viewer skipped, the turn was interrupted, or it timed out."""
  19. from gateway.session_server_requests import ask_viewer
  20. return ask_viewer(events, session_id, "sudo", {"command": command}, cancelled=cancelled, timeout=timeout)
  21. @contextlib.contextmanager
  22. def sudo_prompt_scope(turn, agent):
  23. """Install the sudo callback on this (agent) thread for a local viewer's turn; restore after."""
  24. from gateway.run_turn_progress import local_viewer_turn
  25. if not local_viewer_turn(turn):
  26. yield
  27. return
  28. from tools.terminal_tool import _get_sudo_password_callback, set_sudo_password_callback
  29. authority, session_id, _generation = turn._approval_owner
  30. def callback():
  31. from gateway.run import _redact_approval_command
  32. from tools.terminal_tool_sudo import get_sudo_prompt_command
  33. live = authority.sessions.get(session_id)
  34. if live is None:
  35. return ""
  36. return ask_sudo(live.event_stream, session_id, _redact_approval_command(get_sudo_prompt_command()),
  37. cancelled=lambda: bool(getattr(agent, "_interrupt_requested", False)))
  38. previous = _get_sudo_password_callback()
  39. set_sudo_password_callback(callback)
  40. try:
  41. yield
  42. finally:
  43. set_sudo_password_callback(previous)