permissions.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. """ACP permission bridging for Hermes dangerous-command approvals."""
  2. from __future__ import annotations
  3. import asyncio
  4. import logging
  5. from concurrent.futures import TimeoutError as FutureTimeout
  6. from itertools import count
  7. from typing import Callable
  8. from acp.schema import AllowedOutcome, PermissionOption
  9. logger = logging.getLogger(__name__)
  10. # ACP permission option id -> Hermes approval result. Ids are stable across the
  11. # ``allow_permanent=True`` and ``False`` paths even though the option list differs.
  12. _OPTION_ID_TO_HERMES = {
  13. "allow_once": "once", "allow_session": "session", "allow_always": "always", "deny": "deny", "deny_always": "deny"
  14. }
  15. _PERMISSION_REQUEST_IDS = count(1)
  16. def _permission_option_supports_kind(kind: str) -> bool:
  17. """Return whether the installed ACP SDK accepts a permission option kind."""
  18. try:
  19. PermissionOption(option_id="__probe__", kind=kind, name="probe")
  20. return True
  21. except Exception:
  22. return False
  23. def _build_permission_options(
  24. *, allow_permanent: bool, allow_session: bool = True, smart_denied: bool = False,
  25. ) -> list[PermissionOption]:
  26. """Return ACP options that match Hermes approval semantics."""
  27. # A gate that re-asks every time (allow_session=False, e.g. protected
  28. # agent-instruction writes) collapses to the same two options as a Smart
  29. # DENY override — offering a scope Hermes discards would re-prompt every write.
  30. # See #81887.
  31. once_only = smart_denied or not allow_session
  32. options = [PermissionOption(option_id="allow_once", kind="allow_once", name="Allow once")]
  33. if not once_only:
  34. # ACP has no session-scoped kind: closest persistent hint, Hermes semantics in the id.
  35. options.append(PermissionOption(option_id="allow_session", kind="allow_always", name="Allow for session"))
  36. if allow_permanent:
  37. options.append(PermissionOption(option_id="allow_always", kind="allow_always", name="Allow always"))
  38. options.append(PermissionOption(option_id="deny", kind="reject_once", name="Deny"))
  39. if not once_only and _permission_option_supports_kind("reject_always"):
  40. options.append(PermissionOption(option_id="deny_always", kind="reject_always", name="Deny always"))
  41. return options
  42. def _build_permission_tool_call(command: str, description: str):
  43. """Return the ``ToolCallUpdate`` (not ``ToolCallStart``) payload attached to a
  44. permission request; unique ``perm-check-N`` ids keep concurrent requests apart."""
  45. import acp as _acp
  46. content_text = f"{description}\n$ {command}" if description else f"$ {command}"
  47. return _acp.update_tool_call(
  48. f"perm-check-{next(_PERMISSION_REQUEST_IDS)}", title=f"{description}: {command}" if description else command,
  49. kind="execute", status="pending", content=[_acp.tool_content(_acp.text_block(content_text))],
  50. raw_input={"command": command, "description": description},
  51. )
  52. def _map_outcome_to_hermes(outcome: object, *, allowed_option_ids: set[str]) -> str:
  53. """Map an ACP permission outcome into Hermes approval strings."""
  54. if not isinstance(outcome, AllowedOutcome):
  55. return "deny"
  56. if outcome.option_id not in allowed_option_ids:
  57. logger.warning("Permission request returned unknown option_id: %s", outcome.option_id)
  58. return "deny"
  59. return _OPTION_ID_TO_HERMES.get(outcome.option_id, "deny")
  60. def await_permission(
  61. request_permission_fn: Callable, loop: asyncio.AbstractEventLoop, session_id: str, *,
  62. tool_call, options: list[PermissionOption], timeout: float, what: str,
  63. send_update: Callable[[object], None] | None = None,
  64. ) -> tuple[object | None, bool]:
  65. """Schedule ``request_permission`` on ``loop`` from a worker thread and block for the answer.
  66. Returns ``(response, timed_out)``; ``(None, False)`` when scheduling or the request failed.
  67. Clients materialise the request's ``tool_call`` as a pending bubble, so once the answer is
  68. in, ``send_update`` (when given) closes it: ``completed`` for an allow, ``failed`` otherwise."""
  69. from agent.async_utils import safe_schedule_threadsafe
  70. coro = request_permission_fn(session_id=session_id, tool_call=tool_call, options=options)
  71. future = safe_schedule_threadsafe(coro, loop, logger=logger, log_message=f"{what}: failed to schedule on loop")
  72. if future is None:
  73. return None, False
  74. response, timed_out = None, False
  75. try:
  76. response = future.result(timeout=timeout)
  77. except FutureTimeout:
  78. future.cancel()
  79. logger.warning("%s timed out after %ss", what, timeout)
  80. timed_out = True
  81. except Exception as exc:
  82. future.cancel()
  83. logger.warning("%s failed: %s", what, exc)
  84. if send_update is not None:
  85. import acp as _acp
  86. # Duck-typed like the callers' own allow checks (``outcome == "selected"`` is the wire
  87. # discriminator), so the bubble's terminal status always matches the decision taken.
  88. outcome = getattr(response, "outcome", None)
  89. allowed = getattr(outcome, "outcome", None) == "selected" and any(
  90. option.option_id == getattr(outcome, "option_id", None) and option.kind.startswith("allow")
  91. for option in options
  92. )
  93. send_update(_acp.update_tool_call(tool_call.tool_call_id, status="completed" if allowed else "failed"))
  94. return response, timed_out
  95. def resolve_permission_timeout(timeout: float | None) -> float:
  96. """``None`` → the user's ``approvals.timeout`` (same knob as CLI/gateway prompts, default
  97. 300 s). The ACP bridges used to hardcode 60 s, so a host whose approval card was still
  98. waiting saw Hermes self-deny under it (#73403)."""
  99. if timeout is not None:
  100. return float(timeout)
  101. from tools.approval_context import _get_approval_timeout
  102. return float(_get_approval_timeout())
  103. def make_approval_callback(request_permission_fn: Callable, loop: asyncio.AbstractEventLoop,
  104. session_id: str, timeout: float | None = None,
  105. send_update: Callable[[object], None] | None = None) -> Callable[..., str]:
  106. """Return a Hermes approval callback (``command, description, **kw`` as used by
  107. ``tools.approval.prompt_dangerous_approval()``) that bridges to the ACP
  108. connection's ``request_permission`` coroutine on ``loop``; auto-denies after ``timeout`` s
  109. (``None`` → ``approvals.timeout``, read per request)."""
  110. def _callback(command: str, description: str, *, allow_permanent: bool = True,
  111. allow_session: bool = True, smart_denied: bool = False, **_: object) -> str:
  112. options = _build_permission_options(allow_permanent=allow_permanent, allow_session=allow_session,
  113. smart_denied=smart_denied)
  114. response, timed_out = await_permission(
  115. request_permission_fn, loop, session_id, tool_call=_build_permission_tool_call(command, description),
  116. options=options, timeout=resolve_permission_timeout(timeout), what="Permission request",
  117. send_update=send_update,
  118. )
  119. if timed_out:
  120. # Distinct from an explicit deny: tools.approval reports "timed out
  121. # without user response" instead of a user denial.
  122. return "timeout"
  123. if response is None:
  124. return "deny"
  125. return _map_outcome_to_hermes(response.outcome, allowed_option_ids={option.option_id for option in options})
  126. return _callback