approval_prompt.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. """Human prompt surfaces for :mod:`tools.approval`.
  2. The interactive CLI prompt (callback panel or ``input()`` fallback) and the
  3. operator-selected plugin approval transport. Detection, allowed scopes,
  4. persistence, timeout policy and the final authorization stay host-owned in
  5. ``tools.approval``; this module only asks and reports the answer.
  6. """
  7. import logging
  8. import os
  9. import sys
  10. import threading
  11. from tools import approval_context as _ctx, approval_gateway_wait as _gw
  12. from tools.approval_human_wait import activity_heartbeat, human_wait_window
  13. from tools.interrupt import is_interrupted
  14. logger = logging.getLogger("tools.approval")
  15. def prompt_dangerous_approval(command: str, description: str, timeout_seconds: int | None = None,
  16. allow_permanent: bool = True, approval_callback=None,
  17. *, allow_session: bool = True, smart_denied: bool = False,
  18. title: str | None = None) -> str:
  19. """Prompt the user to approve a dangerous command (CLI only).
  20. allow_permanent=False hides [a]lways. allow_session=False hides
  21. [s]ession too — the caller grants one operation and re-asks next time (the
  22. protected agent-instruction gate in ``tools/file_tools.py``); offering a scope
  23. the caller discards makes every later write re-prompt and reads as broken.
  24. smart_denied: owner override of a Smart DENY, offer only once/deny.
  25. title: header for the plain-input prompt when the question is not a dangerous command
  26. ("Save to memory?", "<server> is asking"); the default header stays the dangerous-command one.
  27. approval_callback: CLI prompt_toolkit callback ``(command, description, *,
  28. allow_permanent=True, allow_session=True, smart_denied=False) -> str``; legacy
  29. signatures keep working while both keywords hold their defaults.
  30. Returns 'once', 'session', 'always', 'deny', 'timeout', or 'cancelled'. 'timeout'
  31. means no user response — still blocked (fail-closed), but callers report "no
  32. response" rather than an explicit denial. 'cancelled' is an :class:`Unanswered`
  33. sentinel: the prompt never reached a human (callback raised, no callback under
  34. prompt_toolkit, interrupted read) and ``.cause`` says why (#22992).
  35. See #81887.
  36. """
  37. if timeout_seconds is None:
  38. timeout_seconds = _ctx._get_approval_timeout()
  39. from tools.human_input_hooks import human_input_request
  40. # Everything below is a human prompt (callback panel or input() fallback, both bounded by the approval deadline):
  41. # record it as human-wait time so the concurrent batch deadline excludes it.
  42. # See #79719.
  43. with human_input_request("approval", prompt=command) as human, human_wait_window():
  44. human.outcome = choice = _ask_human(command, description, timeout_seconds, allow_permanent,
  45. approval_callback, allow_session, smart_denied, title=title)
  46. return choice
  47. class Unanswered(str):
  48. """Choice ``"cancelled"`` carrying the reason nobody answered. Compares equal to the gateway's
  49. withdrawn-prompt choice so every consumer already handling ``cancelled`` fails closed without
  50. attributing a denial to the user."""
  51. __slots__ = ("cause",)
  52. def __new__(cls, cause: str):
  53. self = super().__new__(cls, "cancelled")
  54. self.cause = cause
  55. return self
  56. _CLI_CHOICE_ALIASES = {
  57. "o": "once", "once": "once",
  58. "s": "session", "session": "session",
  59. "a": "always", "always": "always",
  60. }
  61. _CLI_CHOICE_I18N = {
  62. "once": "approval.allowed_once",
  63. "session": "approval.allowed_session",
  64. "always": "approval.allowed_always",
  65. "deny": "approval.denied",
  66. }
  67. def _read_choice(prompt: str, timeout_seconds: int) -> str | None:
  68. """Read one answer on a daemon thread; None when the user never answered."""
  69. result = {"choice": ""}
  70. def get_input():
  71. try:
  72. result["choice"] = input(prompt).strip().lower()
  73. except (EOFError, OSError):
  74. result["choice"] = ""
  75. thread = threading.Thread(target=get_input, daemon=True)
  76. thread.start()
  77. thread.join(timeout=timeout_seconds)
  78. return None if thread.is_alive() else result["choice"]
  79. def callback_accepts(callback, keyword: str) -> bool:
  80. """True when *callback* takes ``keyword`` (or ``**kwargs``); approval callbacks predate ``title``
  81. and a TypeError inside the callback would read as a deny."""
  82. import inspect
  83. try:
  84. params = inspect.signature(callback).parameters
  85. except (TypeError, ValueError):
  86. return False
  87. return keyword in params or any(p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values())
  88. def _ask_human(command: str, description: str, timeout_seconds: int, allow_permanent: bool,
  89. approval_callback, allow_session: bool, smart_denied: bool, title: str | None = None) -> str:
  90. # Redact before any user-visible rendering; the original `command` still executes after approval. Same redactor as
  91. # memory/log sanitization so tokens mask consistently across surfaces.
  92. from agent.redact import redact_approval_display
  93. display_command = redact_approval_display(command)
  94. display_description = redact_approval_display(description)
  95. # Smart DENY and a session-less gate both reduce the menu to once/deny.
  96. once_only = smart_denied or not allow_session
  97. if approval_callback is not None:
  98. try:
  99. # Non-default scopes only: legacy callbacks lack the newer keywords.
  100. callback_kwargs = {"allow_permanent": allow_permanent,
  101. **({"allow_session": False} if not allow_session else {}),
  102. **({"smart_denied": True} if smart_denied else {}),
  103. **({"title": title} if title and callback_accepts(approval_callback, "title") else {})}
  104. return approval_callback(display_command, display_description, **callback_kwargs)
  105. except Exception as e:
  106. logger.error("Approval callback failed: %s", e, exc_info=True)
  107. return Unanswered(f"the approval callback failed: {type(e).__name__}")
  108. # Fail-closed guard: when prompt_toolkit owns the terminal and no callback is registered on this thread, the
  109. # input() fallback would spawn a daemon thread whose read never sees Enter (keystrokes go to prompt_toolkit) — an
  110. # invisible deadlock. Fail closed loudly instead; threads needing interactive approval must install a callback via
  111. # tools.terminal_tool.set_approval_callback() first.
  112. try:
  113. # Fail fast and log loudly so the caller can surface a real error to the agent. Any thread
  114. # that needs interactive approval must install a callback via
  115. # tools.terminal_tool.set_approval_callback() before reaching this point (see delegate_tool.py,
  116. # run_agent.py _execute_tool_calls_concurrent / _spawn_background_review for the established
  117. # pattern). See #15216.
  118. from prompt_toolkit.application.current import get_app_or_none
  119. if get_app_or_none() is not None:
  120. logger.warning("Dangerous-command approval requested on a thread with no "
  121. "approval callback while prompt_toolkit is active; failing closed "
  122. "to avoid stdin deadlock. command=%r description=%r", command, description)
  123. return Unanswered("no approval callback is registered on this thread while prompt_toolkit owns "
  124. "the terminal, so the prompt could not be shown")
  125. except Exception:
  126. pass # prompt_toolkit absent or detection failed: legacy input() path is safe
  127. os.environ["HERMES_SPINNER_PAUSE"] = "1"
  128. try:
  129. from agent.i18n import t
  130. # (prompt key, menu key) by menu shape: once/deny, full, or no [a]lways.
  131. shape = "smart_deny" if once_only else "long" if allow_permanent else "short"
  132. prompt_key, menu_key = f"approval.prompt_{shape}", f"approval.choose_{shape}"
  133. header = title or t('approval.dangerous_header', description=display_description)
  134. print(f"\n {header}"
  135. f"\n {display_command}\n\n{t(menu_key)}\n")
  136. sys.stdout.flush()
  137. choice = _read_choice(t(prompt_key), timeout_seconds)
  138. if choice is None:
  139. print("\n" + t("approval.timeout", **_ctx.approval_timeout_notice_kwargs()))
  140. return "timeout" # distinct from deny: the user never answered
  141. if once_only:
  142. decision = {**dict.fromkeys(t("approval.smart_deny_once_inputs").split(","), "once"),
  143. **dict.fromkeys(t("approval.smart_deny_deny_inputs").split(","), "deny"),
  144. }.get(choice, "deny")
  145. else:
  146. decision = _CLI_CHOICE_ALIASES.get(choice, "deny")
  147. if decision == "always" and not allow_permanent:
  148. decision = "session"
  149. print(t(_CLI_CHOICE_I18N[decision]))
  150. return decision
  151. except (EOFError, KeyboardInterrupt):
  152. print("\n" + t("approval.cancelled"))
  153. return Unanswered("the prompt was interrupted before an answer was given")
  154. finally:
  155. os.environ.pop("HERMES_SPINNER_PAUSE", None)
  156. print()
  157. sys.stdout.flush()
  158. def get_plugin_manager():
  159. """Lazy plugin-manager seam used by tests and early tool-only imports."""
  160. from hermes_cli.plugins import discover_plugins, get_plugin_manager as _get_manager
  161. # Approval can be imported before model_tools (which triggers discovery); make an explicitly selected transport
  162. # available on the first approval instead of treating the undiscovered registry as unavailable.
  163. discover_plugins()
  164. return _get_manager()
  165. def _attempt(name: str, choice, failure, fallback) -> dict:
  166. """Result shape of :func:`_present_with_selected_transport` once a transport is selected."""
  167. return {"selected": True, "choice": choice, "failure": failure, "fallback": fallback, "name": name}
  168. def _present_with_selected_transport(*, command: str, description: str, pattern_key: str,
  169. pattern_keys: list[str], session_key: str, surface: str,
  170. allow_session: bool, allow_permanent: bool) -> dict:
  171. """Present through an explicitly selected plugin transport, if any. A selected
  172. transport replaces every built-in prompt surface; detection, allowed scopes,
  173. persistence, timeout, and final authorization stay host-owned. A failed
  174. transport reaches a built-in surface only under the explicit
  175. ``transport_fallback: builtin`` opt-in."""
  176. name, fallback = _ctx._get_approval_transport_config()
  177. if name == "builtin":
  178. return {"selected": False}
  179. try:
  180. registered = get_plugin_manager().get_approval_transport(name)
  181. except Exception:
  182. # Plugin/discovery exception text may contain plugin-owned secrets.
  183. logger.warning("Could not resolve selected approval transport %r", name)
  184. registered = None
  185. if registered is None:
  186. logger.warning("Selected approval transport %r is unavailable", name)
  187. return _attempt(name, "deny", "unavailable", fallback)
  188. try:
  189. from agent.redact import redact_approval_display
  190. from hermes_cli.approval_transport import ApprovalRequest, invoke_approval_transport
  191. timeout_seconds = _ctx._get_approval_timeout()
  192. request = ApprovalRequest.create(
  193. command=redact_approval_display(command, force=True),
  194. description=redact_approval_display(description, force=True), pattern_key=pattern_key,
  195. pattern_keys=tuple(pattern_keys), session_key=session_key, surface=surface, allow_session=allow_session,
  196. allow_permanent=allow_permanent, timeout_seconds=timeout_seconds,
  197. )
  198. except Exception:
  199. # Never fall back to raw text if redaction or request construction fails:
  200. # fail closed without calling the plugin or leaking the unredacted payload.
  201. logger.warning("Could not build redacted plugin approval request")
  202. return _attempt(name, "deny", "error", None)
  203. hook_kwargs = dict(
  204. command=request.command, description=request.description, pattern_key=pattern_key,
  205. pattern_keys=list(pattern_keys), session_key=session_key, surface=f"transport:{name}",
  206. request_id=request.request_id, request_digest=request.digest,
  207. )
  208. _ctx._fire_approval_hook("pre_approval_request", **hook_kwargs)
  209. from tools.human_input_hooks import human_input_request
  210. with human_input_request("approval", prompt=request.command, session_key=session_key) as human, \
  211. human_wait_window(session_key):
  212. result = invoke_approval_transport(
  213. registered.present, request, timeout_seconds=timeout_seconds,
  214. on_poll=activity_heartbeat("waiting for plugin approval transport"),
  215. is_interrupted=is_interrupted,
  216. )
  217. human.outcome = result.choice if result.failure is None else f"transport_{result.failure}"
  218. _ctx._fire_approval_hook("post_approval_response", **hook_kwargs, choice=human.outcome)
  219. return _attempt(name, result.choice, result.failure, fallback)
  220. def _transport_choice(attempt: dict, *, pattern_key: str, description: str):
  221. """Interpret a ``_present_with_selected_transport`` attempt into
  222. ``(choice, denied_result)``: both None when the built-in surfaces should run
  223. (no transport selected, or a failure with the explicit builtin fallback); a
  224. denied result for any other failure; else the user's choice."""
  225. if not attempt.get("selected"):
  226. return None, None
  227. failure = attempt.get("failure")
  228. if not failure:
  229. return attempt.get("choice"), None
  230. if attempt.get("fallback") == "builtin":
  231. logger.warning("Approval transport %r failed (%s); using explicit builtin fallback",
  232. attempt.get("name"), failure)
  233. return None, None
  234. from tools import approval as _a
  235. breaker_addendum = _a._denial_breaker_addendum(_ctx.get_current_session_key())
  236. return None, _a._denied(
  237. f"BLOCKED: Selected approval transport failed ({failure}); the user "
  238. "has NOT consented to this action. Do NOT retry this command or "
  239. f"attempt the same outcome through another route.{breaker_addendum}",
  240. pattern_key=pattern_key, description=description, outcome=f"transport_{failure}",
  241. )
  242. def _consent(choice, unresolved: str) -> str:
  243. """Map an approval choice to an elicitation verdict; *unresolved* is the no-answer outcome."""
  244. if choice in ("once", "session", "always"):
  245. return "accept"
  246. return unresolved if choice in ("timeout", "cancelled") else "decline"
  247. def _remembered_consent(session_key: str, choice, remember_key: str | None, unresolved: str) -> str:
  248. """:func:`_consent`, recording a ``session``/``always`` answer under *remember_key*. Without a key
  249. those scopes were never offered, so a stale or typed broader answer covers this call only."""
  250. if remember_key is not None:
  251. from tools import approval as _a
  252. _a._persist_choice(session_key, choice, [remember_key])
  253. return _consent(choice, unresolved)
  254. def request_elicitation_consent(message: str, description: str, *,
  255. timeout_seconds: int | None = None,
  256. surface: str = "mcp-elicitation", title: str = "Confirm this action?",
  257. remember_key: str | None = None) -> str:
  258. """Route an MCP elicitation request to the surface owning the active session:
  259. gateway sessions through ``_await_gateway_decision``, CLI/TUI through
  260. ``prompt_dangerous_approval``. Always fails closed: a missing notify_cb in a
  261. gateway session, timeouts, and exceptions map to ``"decline"`` so a server
  262. treats them as "user did not approve" rather than retrying or hanging.
  263. Returns ``"accept" | "decline" | "cancel"``.
  264. Without *remember_key* the consent covers one call, so every surface offers only
  265. once/deny. With it, the session and always choices are offered and recorded under
  266. that approval key; the caller checks ``tools.approval.is_approved`` before asking."""
  267. from tools import approval as _a
  268. try:
  269. session_key = _ctx.get_current_session_key()
  270. except Exception as exc: # pragma: no cover -- defensive
  271. logger.warning("Elicitation consent: session lookup failed: %s", exc)
  272. return "decline"
  273. # A finite gateway turn (``chat -q`` / ``-z`` over the daemon) has no one to answer: parking the prompt
  274. # would detach the viewer mid-turn instead of failing closed like the in-process ``-q`` input() path.
  275. if _ctx._is_single_query_approval_context():
  276. return "decline"
  277. scoped = remember_key is not None
  278. # api_server is an unattended *platform* for the dangerous-command gate, but a live ``/v1/runs`` run
  279. # registers an approval notify callback and answers via ``POST /v1/runs/{id}/approval``
  280. # (gateway/platforms/api_server_runs.py), so its per-call MCP consent takes the gateway path too.
  281. # A run without a callback still fails closed below; cron and ``-q`` workers stay excluded.
  282. api_run_context = (
  283. _ctx._get_session_platform() == "api_server"
  284. and not _ctx._is_cron_approval_context()
  285. and not _ctx._is_single_query_approval_context()
  286. )
  287. if _ctx._is_gateway_approval_context() or api_run_context:
  288. notify_cb = _a._gateway_notify_cb(session_key)
  289. if notify_cb is None:
  290. logger.warning("Elicitation requested in gateway session %s but no "
  291. "notify_cb is registered — failing closed", session_key)
  292. return "decline"
  293. try:
  294. decision = _gw._await_gateway_decision(
  295. session_key, notify_cb, {"command": message, "description": description,
  296. "pattern_key": "mcp_elicitation",
  297. "pattern_keys": ["mcp_elicitation"],
  298. "allow_session": scoped, "allow_permanent": scoped}, surface=surface)
  299. except Exception as exc:
  300. logger.error("Elicitation gateway dispatch failed: %s", exc, exc_info=True)
  301. return "decline"
  302. if decision.get("notify_failed"):
  303. return "decline"
  304. if not decision.get("resolved") or decision.get("cancelled"):
  305. return "cancel" # nobody answered (timeout / prompt withdrawn) — not a user refusal
  306. return _remembered_consent(session_key, decision.get("choice"), remember_key, "decline")
  307. # Nobody can answer a -q, cron or unattended-platform worker. A `hermes chat -q` turn still has the CLI's
  308. # panel callback registered, which would wait the full approval timeout before failing closed.
  309. if _ctx._no_user_can_answer():
  310. logger.info("Elicitation consent (%s) declined: no user can answer in this session", surface)
  311. return "decline"
  312. # Same observer payload as the gateway branch (#131876); post fires in a finally so the
  313. # wait settles for observers on the early fail-closed return too.
  314. hook_kwargs = dict(command=message, description=description, pattern_key="mcp_elicitation",
  315. pattern_keys=["mcp_elicitation"], session_key=session_key, surface=surface)
  316. _ctx._fire_approval_hook("pre_approval_request", **hook_kwargs)
  317. hook_choice = "cancelled"
  318. try:
  319. from tools.terminal_tool import _get_approval_callback
  320. # Pass the agent thread's panel callback: without it prompt_toolkit fails the prompt closed unseen.
  321. choice = prompt_dangerous_approval(message, description, timeout_seconds=timeout_seconds,
  322. allow_permanent=scoped, allow_session=scoped, title=title,
  323. approval_callback=_get_approval_callback())
  324. hook_choice = choice
  325. except Exception as exc:
  326. logger.error("Elicitation CLI prompt failed: %s", exc, exc_info=True)
  327. return "decline"
  328. finally:
  329. _ctx._fire_approval_hook("post_approval_response", **hook_kwargs, choice=hook_choice)
  330. return _remembered_consent(session_key, choice, remember_key, "cancel") # timeout mirrors the gateway