approval_context.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. """Approval context: who is asking, from where, under which policy.
  2. Session identity and observability contextvars, the interactive/gateway/cron/
  3. unattended predicates, and the ``approvals.*`` config readers used by every
  4. gate in :mod:`tools.approval`.
  5. """
  6. import contextvars
  7. import logging
  8. import os
  9. from agent.i18n import t
  10. from hermes_cli.config import cfg_get
  11. from utils import env_var_enabled, is_truthy_value
  12. logger = logging.getLogger("tools.approval")
  13. def _ctx(name: str, default: str | None = "") -> contextvars.ContextVar:
  14. return contextvars.ContextVar(name, default=default)
  15. # Per-thread/per-task gateway session identity: gateway runs agent turns concurrently in executor threads, so a
  16. # process-global env var is racy (the env fallback stays for legacy single-threaded callers).
  17. _approval_session_key: contextvars.ContextVar[str] = _ctx("approval_session_key")
  18. _approval_turn_id: contextvars.ContextVar[str] = _ctx("approval_turn_id")
  19. _approval_tool_call_id: contextvars.ContextVar[str] = _ctx("approval_tool_call_id")
  20. # Hermes session id (observability identity, distinct from the gateway routing session_key), forwarded to approval
  21. # hooks so observer plugins attach marks to the REAL session scope — otherwise they fall back to a synthetic "default"
  22. # session whose scope never closes, so close-time exporters never ship them.
  23. _approval_session_id: contextvars.ContextVar[str] = _ctx("approval_session_id")
  24. # Interactive-CLI flag. Concurrent ACP sessions share a ThreadPoolExecutor, so mutating
  25. # os.environ["HERMES_INTERACTIVE"] races: one session's `finally` restore can clobber another's set mid-run, dropping
  26. # it onto the non-interactive auto-approve path so a dangerous command runs without the approval callback firing
  27. # (GHSA-96vc-wcxf-jjff). None = unset → env fallback.
  28. _hermes_interactive_ctx: contextvars.ContextVar[str | None] = _ctx("hermes_interactive", None)
  29. def set_hermes_interactive_context(interactive: bool) -> contextvars.Token:
  30. """Bind interactive mode for the current context instead of mutating os.environ."""
  31. return _hermes_interactive_ctx.set("1" if interactive else "")
  32. def reset_hermes_interactive_context(token: contextvars.Token) -> None:
  33. """Restore the prior value from :func:`set_hermes_interactive_context`."""
  34. _hermes_interactive_ctx.reset(token)
  35. def _is_interactive_cli() -> bool:
  36. """True for an interactive CLI/ACP session (contextvar first, env fallback)."""
  37. ctx_val = _hermes_interactive_ctx.get()
  38. return is_truthy_value(ctx_val) if ctx_val is not None else env_var_enabled("HERMES_INTERACTIVE")
  39. def _fire_approval_hook(hook_name: str, **kwargs) -> None:
  40. """Invoke a plugin lifecycle hook (pre_approval_request / post_approval_response).
  41. Lazy-imports the plugin manager (approval.py is imported long before plugins
  42. are discovered). Never raises: approval flow is safety-critical, plugin
  43. observability is not.
  44. """
  45. try:
  46. from hermes_cli.lifecycle import invoke_hook
  47. except Exception:
  48. return # plugin system unavailable (bare tool-only imports, minimal tests)
  49. try:
  50. kwargs.setdefault("turn_id", _approval_turn_id.get())
  51. kwargs.setdefault("tool_call_id", _approval_tool_call_id.get())
  52. if _approval_session_id.get():
  53. kwargs.setdefault("session_id", _approval_session_id.get())
  54. invoke_hook(hook_name, **kwargs)
  55. except Exception as exc:
  56. # invoke_hook() swallows per-callback errors; this is the dispatch layer itself failing.
  57. logger.debug("Approval hook %s dispatch failed: %s", hook_name, exc)
  58. def gateway_approval_surface() -> str:
  59. """Surface a gateway-rendered approval reports: ``cli`` for a classic CLI session's turn (main
  60. prompted those in the CLI process), else ``gateway``."""
  61. from hermes_cli.plugin_session import session_surface
  62. return "cli" if session_surface() == "cli" else "gateway"
  63. # Launch sources of a local session whose viewer answers per-command prompts (classic CLI, TUI, Desktop, ACP editor).
  64. _LOCAL_INTERACTIVE_SOURCES = frozenset({"cli", "tui", "gui", "acp"})
  65. def is_local_interactive_session() -> bool:
  66. """True for a classic CLI, TUI, Desktop or ACP session's turn, read from the launch policy the gateway
  67. froze at ``session.create`` (never a per-turn client flag). Kanban, cron and forwarded routes keep
  68. their own sources and stay out."""
  69. try:
  70. from gateway.session_policy import active_policy
  71. except ImportError: # install without the gateway package: no local session can be running
  72. return False
  73. policy = active_policy()
  74. return policy is not None and policy.source in _LOCAL_INTERACTIVE_SOURCES
  75. def is_viewer_turn_with_approver() -> bool:
  76. """True while the executing turn is one its session's viewer submitted through ``session.submit`` (as the
  77. gateway's FIFO drain recorded for this admission) and a viewer that can answer approvals is attached now:
  78. a subscriber holding ``session:approve``, the only answer the gateway's approval resolver accepts. A plugin
  79. ``inject_message`` turn, a delegation completion, a background-process or watch notice, a /loop tick, a
  80. heartbeat or a hosted-room task is never a viewer turn."""
  81. try:
  82. from gateway.session_ingress import viewer_turn
  83. except ImportError: # install without the gateway package: no admission is executing
  84. return False
  85. live = viewer_turn.get()
  86. if live is None:
  87. return False
  88. with live.event_stream.lock:
  89. return any("session:approve" in member.capabilities for member in live.subscribers.values())
  90. def set_current_session_key(session_key: str) -> contextvars.Token[str]:
  91. """Bind the active approval session key to the current context."""
  92. return _approval_session_key.set(session_key or "")
  93. def reset_current_session_key(token: contextvars.Token[str]) -> None:
  94. """Restore the prior approval session key context."""
  95. _approval_session_key.reset(token)
  96. _Tokens = tuple[contextvars.Token[str], contextvars.Token[str], contextvars.Token[str]]
  97. def set_current_observability_context(*, turn_id: str = "", tool_call_id: str = "", session_id: str = "") -> _Tokens:
  98. """Bind active tool correlation IDs to approval hooks."""
  99. return (_approval_turn_id.set(turn_id or ""), _approval_tool_call_id.set(tool_call_id or ""),
  100. _approval_session_id.set(session_id or ""))
  101. def reset_current_observability_context(tokens: _Tokens) -> None:
  102. """Restore prior approval hook correlation IDs."""
  103. turn_token, tool_token, session_token = tokens
  104. _approval_session_id.reset(session_token)
  105. _approval_tool_call_id.reset(tool_token)
  106. _approval_turn_id.reset(turn_token)
  107. def get_current_session_key(default: str = "default") -> str:
  108. """Return the active session key: approval contextvar → session_context → os.environ."""
  109. if session_key := _approval_session_key.get():
  110. return session_key
  111. from gateway.session_context import get_session_env
  112. return get_session_env("HERMES_SESSION_KEY", default)
  113. def _session_env(name: str) -> str:
  114. """Session-scoped env value, contextvar-first so one cron/-q job cannot taint
  115. unrelated gateway/API/TUI turns in the same process; process env is the
  116. fallback for CLI tests and older entrypoints."""
  117. try:
  118. from gateway.session_context import get_session_env
  119. return get_session_env(name, "") or ""
  120. except Exception:
  121. return os.getenv(name, "") or ""
  122. def _get_session_platform() -> str:
  123. """Return the current gateway platform from contextvars/env fallback."""
  124. return _session_env("HERMES_SESSION_PLATFORM")
  125. def _is_cron_approval_context() -> bool:
  126. """True when the current approval decision is running inside cron."""
  127. return is_truthy_value(_session_env("HERMES_CRON_SESSION"))
  128. # Programmatic/unattended platforms: no human can answer a prompt and the adapter has no ``send_exec_approval`` /
  129. # ``/approve`` surface. Governed by ``approvals.unattended_mode`` (default deny), mirroring ``cron_mode`` — never an
  130. # interactive round-trip that blocks for the full timeout with nobody to answer.
  131. _UNATTENDED_APPROVAL_PLATFORMS = frozenset({"webhook", "msgraph_webhook", "api_server"})
  132. def _is_unattended_platform_approval_context() -> bool:
  133. """True when the session platform is a programmatic/unattended surface.
  134. Webhook, msgraph_webhook, and api_server sessions bind ``HERMES_SESSION_PLATFORM`` like chat gateways
  135. do, but there is no human who can resolve a pending approval. Treating them as gateway approval contexts
  136. blocks the session for the full approval timeout (60-300s) and then fails closed anyway — the deadlock
  137. in #37284/#87509.
  138. """
  139. return _get_session_platform() in _UNATTENDED_APPROVAL_PLATFORMS
  140. # Platforms where a *registered* gateway notify callback still does not mean a human can answer:
  141. # the generic TurnRunner lane registers one for every inbound turn
  142. # (``_run_conversation_with_approval`` registers unconditionally, no platform branch), while the
  143. # adapter renders no ``send_exec_approval``/``/approve`` surface and the inbound lane is a
  144. # fire-and-forget ``POST -> 202`` with no reader. Notifier presence is only a meaningful
  145. # "someone can answer" discriminator on api_server, whose turn paths choose whether to register one.
  146. _NOTIFIER_BLIND_APPROVAL_PLATFORMS = frozenset({"webhook", "msgraph_webhook"})
  147. def _is_single_query_approval_context() -> bool:
  148. """True for a single-query (-q) session: ``hermes chat -q`` exports
  149. ``HERMES_INTERACTIVE=1`` (so sudo password prompts work) but nobody is waiting
  150. to answer approvals; without this marker the gate would wait the full timeout,
  151. fail closed and push the agent toward workarounds (e.g. execute_code).
  152. ``approvals.single_query_mode`` makes the path deterministic. A gateway-admitted turn
  153. carries the same fact as the submission's ``finite`` flag (``hermes -z`` / ``chat -q``
  154. over the daemon): the viewer detaches on the first prompt, so nobody answers there either."""
  155. try:
  156. from gateway.session_finite import finite_turn_required
  157. except ImportError: # install without the gateway package: no admitted turn to carry the flag
  158. pass
  159. else:
  160. if finite_turn_required() is True:
  161. return True
  162. return is_truthy_value(_session_env("HERMES_SINGLE_QUERY_SESSION"))
  163. def _no_user_can_answer() -> bool:
  164. """True in single-query (-q), cron and unattended-platform sessions. `hermes chat -q` still registers the
  165. CLI panel callback, so a prompt that only checks for a callback would wait the full timeout for nobody."""
  166. return (_is_single_query_approval_context() or _is_cron_approval_context()
  167. or _is_unattended_platform_approval_context())
  168. def _is_gateway_approval_context() -> bool:
  169. """True inside a gateway/API session that can answer an approval.
  170. Legacy integrations set HERMES_GATEWAY_SESSION; concurrent paths bind
  171. HERMES_SESSION_PLATFORM via contextvars. Cron is NEVER a gateway approval
  172. context even when it originated from a platform (cron binds the platform for
  173. delivery routing): falling through would submit a pending approval with no
  174. listener and block the job indefinitely; unattended platforms likewise.
  175. Unattended programmatic platforms (webhook, msgraph_webhook, api_server) are excluded for the same
  176. reason: those adapters have no ``send_exec_approval`` and no way to receive ``/approve`` replies.
  177. Submitting a pending approval there blocks the session for the full approval timeout (60-300 s) with no
  178. human who can resolve it (#37284, 87509). Their dangerous-command handling is governed by
  179. ``approvals.unattended_mode`` config (default deny), mirroring cron.
  180. """
  181. if _is_cron_approval_context() or _is_unattended_platform_approval_context():
  182. return False
  183. return env_var_enabled("HERMES_GATEWAY_SESSION") or bool(_get_session_platform())
  184. def _resolve_cli_approval_callback(approval_callback=None):
  185. """Explicit callback, else the per-thread one from ``terminal_tool.set_approval_callback``."""
  186. if approval_callback is not None:
  187. return approval_callback
  188. try:
  189. from tools.terminal_tool import _get_approval_callback
  190. return _get_approval_callback()
  191. except Exception:
  192. return None
  193. def _should_fall_through_to_cli_approval(*, is_cli: bool, approval_callback, notify_cb) -> bool:
  194. """Prefer the CLI Dangerous Command panel over a silent pending approval:
  195. ``HERMES_EXEC_ASK`` (or a platform marker) can leak into an interactive CLI
  196. process (historically via ``import gateway.run``), and without a gateway notify
  197. listener the ask branch used to return ``pending_approval`` immediately and
  198. skip the panel the user can actually answer."""
  199. return bool(is_cli and approval_callback is not None and notify_cb is None)
  200. _VALID_MODES = ("manual", "smart", "off")
  201. def _normalize_approval_mode(mode) -> str:
  202. """Normalize approval mode values loaded from YAML/config. YAML 1.1 parses a
  203. bare ``off`` as False, so ``mode: off`` arrives as a bool; treat it as the
  204. intended string mode. Unknown strings (e.g. 'auto') warn and fall back to
  205. 'manual' instead of silently failing every mode check."""
  206. if isinstance(mode, bool):
  207. return "off" if mode is False else "manual"
  208. if isinstance(mode, str):
  209. normalized = mode.strip().lower()
  210. if normalized in _VALID_MODES:
  211. return normalized
  212. if normalized:
  213. logger.warning("Unknown approvals.mode %r — defaulting to 'manual'. "
  214. "Valid values: %s", mode, ", ".join(_VALID_MODES))
  215. return "manual"
  216. def _get_approval_config() -> dict:
  217. """Read the approvals config block: the LIVE config-cache sub-dict
  218. (load_config_readonly contract) — callers must not mutate it or any nested structure."""
  219. try:
  220. from hermes_cli.config import load_config_readonly
  221. return load_config_readonly().get("approvals", {}) or {}
  222. except Exception as e:
  223. logger.warning("Failed to load approval config: %s", e)
  224. return {}
  225. def _get_approval_mode() -> str:
  226. """Return 'manual', 'smart', or 'off' (a hosted-room policy overrides config)."""
  227. try:
  228. from gateway.hosted_room_execution_policy import current_room_execution_policy
  229. if (room_policy := current_room_execution_policy()) is not None:
  230. return room_policy.approval_mode
  231. except Exception:
  232. pass
  233. return _normalize_approval_mode(_get_approval_config().get("mode", "manual"))
  234. def _get_approval_timeout() -> int:
  235. """Read ``approvals.timeout`` (default 300s: gateway push notifications may
  236. not be seen for minutes; 60s failed closed before Telegram taps landed).
  237. Clamped to ``agent.deadline.MAX_SAFE_TIMEOUT_S`` (~1 year): a larger value
  238. overflows ``time_t`` inside ``Thread.join`` / ``Lock.acquire`` on macOS and
  239. crashed every parallel tool batch; clamping at the single config-read site
  240. keeps every consumer platform-safe at once."""
  241. try:
  242. raw = int(_get_approval_config().get("timeout", 300))
  243. except (ValueError, TypeError):
  244. return 300
  245. try:
  246. from agent.deadline import MAX_SAFE_TIMEOUT_S
  247. safe_cap = int(MAX_SAFE_TIMEOUT_S)
  248. except Exception:
  249. safe_cap = 300 # dependency failure must keep the safe default
  250. if raw > safe_cap:
  251. logger.warning("approvals.timeout=%s exceeds the platform-safe maximum; clamping to %ss", raw, safe_cap)
  252. return min(raw, safe_cap)
  253. def format_approval_window(seconds: int) -> str:
  254. """The ONE human wording for an approval timeout window, shared by the CLI timeout notice,
  255. the tool result's ``user_summary`` and the gateway card copy so every surface agrees:
  256. 300 → "5 minutes", 90 → "90 seconds", 7200 → "2 hours"."""
  257. seconds = max(int(seconds or 0), 0)
  258. if seconds and seconds % 3600 == 0:
  259. count, unit = seconds // 3600, "hour"
  260. elif seconds and seconds % 60 == 0:
  261. count, unit = seconds // 60, "minute"
  262. else:
  263. count, unit = seconds, "second"
  264. return t(f"approval.window.{unit}_one" if count == 1 else f"approval.window.{unit}_other", count=count)
  265. def approval_timeout_notice_kwargs() -> dict:
  266. """``{waited, suggested}`` for the ``approval.timeout`` copy: how long we waited (``5 minutes`` /
  267. ``90 seconds``) and a tripled ``approvals.timeout`` value the user can paste into ``hermes config set``."""
  268. seconds = _get_approval_timeout()
  269. return {"waited": format_approval_window(seconds), "suggested": seconds * 3}
  270. def _binary_approval_mode(key: str) -> str:
  271. """Read ``approvals.<key>`` as 'approve' or 'deny' (default deny)."""
  272. try:
  273. from hermes_cli.config import load_config_readonly
  274. mode = str(cfg_get(load_config_readonly(), "approvals", key, default="deny")).lower().strip()
  275. return "approve" if mode in {"approve", "off", "allow", "yes"} else "deny"
  276. except Exception:
  277. return "deny"
  278. def _get_cron_approval_mode() -> str:
  279. """Read the cron approval mode from config. Returns 'deny' or 'approve'."""
  280. return _binary_approval_mode("cron_mode")
  281. def _get_single_query_approval_mode() -> str:
  282. """Read the single-query (-q) approval mode from config. Returns 'deny' or 'approve'."""
  283. return _binary_approval_mode("single_query_mode")
  284. def _get_unattended_approval_mode() -> str:
  285. """Approval mode for webhook / msgraph_webhook / api_server sessions; default
  286. deny — an unattended session never silently runs a flagged action unless the
  287. operator explicitly trusts it."""
  288. return _binary_approval_mode("unattended_mode")
  289. def _get_approval_transport_config() -> tuple[str, str | None]:
  290. """Return explicitly selected transport and fail-closed fallback mode."""
  291. try:
  292. from hermes_cli.config import load_config_readonly
  293. cfg = ((load_config_readonly() or {}).get("security") or {}).get("approval") or {}
  294. selected = str(cfg.get("transport") or "builtin").strip().lower()
  295. fallback = str(cfg.get("transport_fallback") or "").strip().lower()
  296. except Exception:
  297. # An unreadable/malformed selection must not silently materialize a
  298. # prompt on a built-in surface the operator may not be watching.
  299. return "config-error", None
  300. return selected or "builtin", "builtin" if fallback == "builtin" else None