hosted_room_execution_policy.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. """Target-issued execution authority for RoomLink member turns."""
  2. from __future__ import annotations
  3. import hashlib
  4. from contextvars import ContextVar, Token
  5. from dataclasses import asdict, dataclass
  6. from typing import Any, Mapping
  7. from gateway.hosted_rooms_common import bounded_int, compact_json, identifier
  8. POLICY_VERSION = 1
  9. MAX_POLICY_TOOLSETS = 128
  10. MAX_POLICY_ITERATIONS = (1 << 53) - 1
  11. _POLICY_FIELDS = {"version", "target_profile", "enabled_toolsets", "approval_mode", "max_iterations", "policy_digest"}
  12. class RoomExecutionPolicyError(ValueError): """A RoomLink execution policy is malformed or no longer current."""
  13. def _policy_digest(unsigned: Mapping[str, Any]) -> str:
  14. return hashlib.sha256(compact_json(unsigned).encode("ascii")).hexdigest()
  15. def _identifier(value: Any, *, field: str) -> str:
  16. # Stringifies first (``None`` -> ""), so non-strings also fail as "is invalid".
  17. return identifier(str(value or ""), label=field, error=RoomExecutionPolicyError, invalid=f"{field} is invalid")
  18. @dataclass(frozen=True)
  19. class RoomExecutionPolicy:
  20. """Immutable target policy applied at the agent and approval boundaries."""
  21. version: int
  22. target_profile: str
  23. enabled_toolsets: tuple[str, ...]
  24. approval_mode: str
  25. max_iterations: int
  26. policy_digest: str
  27. @classmethod
  28. def from_mapping(cls, value: Mapping[str, Any]) -> RoomExecutionPolicy:
  29. if not isinstance(value, Mapping) or set(value) != _POLICY_FIELDS:
  30. raise RoomExecutionPolicyError("execution policy fields are invalid")
  31. if value["version"] != POLICY_VERSION:
  32. raise RoomExecutionPolicyError("execution policy version is unsupported")
  33. target_profile = _identifier(value["target_profile"], field="target_profile")
  34. raw_toolsets = value["enabled_toolsets"]
  35. if not isinstance(raw_toolsets, list) or not 1 <= len(raw_toolsets) <= MAX_POLICY_TOOLSETS:
  36. raise RoomExecutionPolicyError("enabled_toolsets are invalid")
  37. toolsets = tuple(sorted(_identifier(item, field="enabled_toolset") for item in raw_toolsets))
  38. if len(set(toolsets)) != len(toolsets) or "bot_room" not in toolsets:
  39. raise RoomExecutionPolicyError("enabled_toolsets are invalid")
  40. approval_mode = str(value["approval_mode"] or "").strip().lower()
  41. if approval_mode not in {"manual", "smart", "off"}:
  42. raise RoomExecutionPolicyError("approval_mode is invalid")
  43. max_iterations = bounded_int(
  44. value["max_iterations"], error=RoomExecutionPolicyError, message="max_iterations is invalid", low=1,
  45. high=MAX_POLICY_ITERATIONS)
  46. unsigned = {
  47. "version": POLICY_VERSION, "target_profile": target_profile, "enabled_toolsets": list(toolsets),
  48. "approval_mode": approval_mode, "max_iterations": max_iterations}
  49. supplied = str(value["policy_digest"] or "").strip().lower()
  50. if supplied != _policy_digest(unsigned):
  51. raise RoomExecutionPolicyError("policy_digest does not match the execution policy")
  52. return cls(**unsigned, policy_digest=supplied)
  53. def as_mapping(self) -> dict[str, Any]:
  54. return {**asdict(self), "enabled_toolsets": list(self.enabled_toolsets)}
  55. def _served_profile_scope(target_profile: str):
  56. """Runtime scope of the SERVED profile: a no-op when it is the active home, else the profile's
  57. own home + secret scope (fail closed on an unknown profile). The advertised policy is signed
  58. for ``target_profile``, so its config and credentials must be read there, never from the
  59. launch profile's env or whatever home happens to be active (#116900)."""
  60. from contextlib import nullcontext
  61. from hermes_cli.profiles import get_profile_dir, normalize_profile_name, profile_exists, profile_matches_home
  62. # "default" is the launch home (a `-p x` multiplexer hosts it too), never a switch to ~/.hermes.
  63. if normalize_profile_name(target_profile) == "default" or profile_matches_home(target_profile):
  64. return nullcontext()
  65. if not profile_exists(target_profile):
  66. raise RoomExecutionPolicyError(f"target_profile {target_profile!r} is not a live profile")
  67. from gateway.run import _profile_runtime_scope
  68. return _profile_runtime_scope(get_profile_dir(target_profile))
  69. def execution_policy_mapping(*, target_profile: str, config: Mapping[str, Any] | None = None) -> dict[str, Any]:
  70. """Resolve the effective API-server policy from the served ``target_profile``'s own config."""
  71. target_profile = _identifier(target_profile, field="target_profile")
  72. if config is None:
  73. from gateway.run import _load_gateway_config
  74. with _served_profile_scope(target_profile):
  75. config = _load_gateway_config()
  76. return execution_policy_mapping(target_profile=target_profile, config=config)
  77. if not isinstance(config, Mapping):
  78. raise RoomExecutionPolicyError("gateway config is invalid")
  79. from hermes_cli.config import resolve_turn_limit
  80. from hermes_cli.tools_config import _get_platform_tools
  81. from tools.approval import _YOLO_MODE_FROZEN
  82. from tools.approval_context import _normalize_approval_mode
  83. toolsets = sorted({*_get_platform_tools(dict(config), "api_server"), "bot_room"})
  84. agent = config.get("agent") if isinstance(config.get("agent"), Mapping) else {}
  85. approvals = config.get("approvals") if isinstance(config.get("approvals"), Mapping) else {}
  86. unsigned = {
  87. "version": POLICY_VERSION, "target_profile": _identifier(target_profile, field="target_profile"),
  88. "enabled_toolsets": toolsets,
  89. "approval_mode": ("off" if _YOLO_MODE_FROZEN else _normalize_approval_mode(approvals.get("mode", "manual"))),
  90. "max_iterations": min(resolve_turn_limit(agent.get("max_turns")), MAX_POLICY_ITERATIONS)}
  91. value = {**unsigned, "policy_digest": _policy_digest(unsigned)}
  92. return RoomExecutionPolicy.from_mapping(value).as_mapping()
  93. _CURRENT_POLICY: ContextVar[RoomExecutionPolicy | None] = ContextVar("hosted_room_execution_policy", default=None)
  94. def bind_room_execution_policy(policy: RoomExecutionPolicy) -> Token:
  95. return _CURRENT_POLICY.set(policy)
  96. def reset_room_execution_policy(token: Token) -> None:
  97. _CURRENT_POLICY.reset(token)
  98. def current_room_execution_policy() -> RoomExecutionPolicy | None:
  99. return _CURRENT_POLICY.get()
  100. __all__ = [
  101. "MAX_POLICY_ITERATIONS", "POLICY_VERSION", "RoomExecutionPolicy", "RoomExecutionPolicyError",
  102. "bind_room_execution_policy", "current_room_execution_policy", "execution_policy_mapping",
  103. "reset_room_execution_policy"]