human_input_hooks.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. """Plugin observers for every point where the agent blocks waiting on a human (#132333).
  2. ``on_human_input_request`` fires right before a prompt is shown (sudo password, clarify question,
  3. dangerous-command approval) and ``on_human_input_resolved`` fires exactly once when the wait ends,
  4. with the same ``request_id`` and an ``outcome``. Observers only: return values are ignored and a
  5. failing plugin never affects the prompt. Payloads never carry what the human typed (password,
  6. answers), and ``prompt`` is force-redacted (with hidden characters shown) so credentials in a command never reach a plugin.
  7. """
  8. from __future__ import annotations
  9. import contextlib
  10. import logging
  11. import os
  12. import uuid
  13. from dataclasses import dataclass
  14. logger = logging.getLogger(__name__)
  15. @dataclass
  16. class HumanInputRequest:
  17. """Handle yielded by :func:`human_input_request`; set ``outcome`` before the block exits."""
  18. request_id: str
  19. outcome: str = ""
  20. def _redacted(text: str) -> str:
  21. try:
  22. from agent.redact import redact_approval_display
  23. return redact_approval_display(text, force=True)
  24. except Exception:
  25. logger.debug("human-input hook prompt redaction failed", exc_info=True)
  26. return "" # never fall back to the raw text
  27. def _identity() -> dict:
  28. try:
  29. from gateway.session_context import get_session_env
  30. from tools import approval_context
  31. session_id = approval_context._approval_session_id.get() or get_session_env("HERMES_SESSION_ID")
  32. platform = (os.getenv("HERMES_PLATFORM") or get_session_env("HERMES_SESSION_PLATFORM")
  33. or get_session_env("HERMES_SESSION_SOURCE") or "cli")
  34. return {"session_id": session_id, "session_key": approval_context.get_current_session_key(default=""),
  35. "platform": platform}
  36. except Exception: # a broken lookup must not take the human prompt down with it
  37. logger.debug("human-input hook identity lookup failed", exc_info=True)
  38. return {"session_id": "", "session_key": "", "platform": ""}
  39. def _fire(hook_name: str, payload: dict) -> None:
  40. try:
  41. from hermes_cli.lifecycle import invoke_hook
  42. invoke_hook(hook_name, **payload)
  43. except Exception: # observability must never break a human prompt
  44. logger.debug("%s dispatch failed", hook_name, exc_info=True)
  45. @contextlib.contextmanager
  46. def human_input_request(kind: str, *, prompt: str = "", session_key: str | None = None, **extra):
  47. """Fire the request hook, run the block (the human wait), then fire the resolved hook.
  48. An exception escaping the block, or a block that never sets ``outcome``, resolves as ``error``."""
  49. payload = {"kind": kind, "request_id": uuid.uuid4().hex, **_identity(), "prompt": _redacted(prompt), **extra}
  50. if session_key is not None:
  51. payload["session_key"] = session_key
  52. request = HumanInputRequest(payload["request_id"])
  53. _fire("on_human_input_request", payload)
  54. try:
  55. yield request
  56. finally:
  57. _fire("on_human_input_resolved", {**payload, "outcome": str(request.outcome or "error")})