platform_actions.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. """Capability-gated platform action facade for plugins (#64176, action half).
  2. Every verb returns a structured result dict — ``{"ok": True, ...}`` on success, ``{"ok": False,
  3. "error": <code>, "detail": <str>}`` on failure — and never raises into hook dispatch.
  4. """
  5. from __future__ import annotations
  6. import logging
  7. from typing import Any, Dict
  8. logger = logging.getLogger(__name__)
  9. ACTIONS_CONTRACT_VERSION = 1
  10. CAPABILITY_ID = "gateway.platform_actions"
  11. def _err(code: str, detail: str = "") -> dict[str, Any]:
  12. result: dict[str, Any] = {"ok": False, "error": code}
  13. if detail:
  14. result["detail"] = detail
  15. return result
  16. def _ok(**fields: Any) -> dict[str, Any]:
  17. return {"ok": True, **fields}
  18. # -- per-platform verb implementations (adapter, *args) -> result ------------
  19. async def _telegram_add_reaction(adapter, chat_id, message_id, emoji):
  20. if await adapter._set_reaction(chat_id, message_id, emoji):
  21. return _ok(action="add_reaction")
  22. return _err("action_failed", "telegram set_message_reaction failed")
  23. async def _discord_add_reaction(adapter: Any, chat_id: str, message_id: str, emoji: str) -> dict[str, Any]:
  24. client = getattr(adapter, "_client", None)
  25. if client is None:
  26. return _err("adapter_disconnected", "discord client unavailable")
  27. try:
  28. channel_id = int(str(chat_id))
  29. msg_id = int(str(message_id))
  30. except (TypeError, ValueError):
  31. return _err("invalid_argument", "discord ids must be numeric")
  32. channel = client.get_channel(channel_id)
  33. if channel is None:
  34. channel = await client.fetch_channel(channel_id)
  35. message = await channel.fetch_message(msg_id)
  36. await message.add_reaction(emoji)
  37. return _ok(action="add_reaction")
  38. async def _telegram_set_thread_title(adapter, chat_id, thread_id, title):
  39. await adapter.rename_dm_topic(chat_id, int(thread_id), title)
  40. return _ok(action="set_thread_title")
  41. async def _discord_set_thread_title(adapter, chat_id, thread_id, title):
  42. if await adapter.rename_thread(thread_id, title):
  43. return _ok(action="set_thread_title")
  44. return _err("action_failed", "discord thread rename failed")
  45. _VERBS = {
  46. "add_reaction": {"telegram": _telegram_add_reaction, "discord": _discord_add_reaction},
  47. "set_thread_title": {"telegram": _telegram_set_thread_title, "discord": _discord_set_thread_title},
  48. }
  49. class PlatformActions:
  50. """Per-plugin facade over the live gateway adapter registry.
  51. Instances are cheap and hold only the owning plugin id; the gateway runner and adapters are
  52. resolved at call time so a facade created before the gateway starts (plugin ``register()`` runs
  53. first) still works once adapters connect.
  54. """
  55. def __init__(self, plugin_id: str):
  56. self._plugin_id = plugin_id
  57. # -- shared plumbing ----------------------------------------------------
  58. def _capability_granted(self) -> bool:
  59. try:
  60. from hermes_cli.plugin_capabilities import plugin_capability_granted
  61. return plugin_capability_granted(self._plugin_id, CAPABILITY_ID)
  62. except Exception:
  63. # Ground rule: failure to read consent state = not granted.
  64. logger.debug("platform_actions capability check failed for %s", self._plugin_id, exc_info=True)
  65. return False
  66. def _resolve_adapter(self, platform: str):
  67. """Return ``(adapter, error_dict)``; exactly one is non-None."""
  68. try:
  69. from gateway.run import _gateway_runner_ref
  70. runner = _gateway_runner_ref()
  71. except Exception:
  72. runner = None
  73. if runner is None:
  74. return None, _err("gateway_unavailable", "no gateway runner is active in this process")
  75. try:
  76. from gateway.config import Platform
  77. platform_enum = Platform(str(platform).strip().lower())
  78. except Exception:
  79. return None, _err("unknown_platform", f"unknown platform {platform!r}")
  80. # Multiplex/Team-Gateway: a secondary profile's adapters live in runner._profile_adapters,
  81. # not runner.adapters. Every adapter-resolution path goes through the same profile-aware,
  82. # fail-closed lookup so a plugin scoped to one profile can never act through another
  83. # profile's bot identity. The bare default-profile lookup is only for a runner predating
  84. # _authorization_adapter (defensive, not expected).
  85. resolve_fn = getattr(runner, "_authorization_adapter", None)
  86. if callable(resolve_fn):
  87. try:
  88. from hermes_cli.profiles import get_active_profile_name
  89. profile_name = get_active_profile_name()
  90. except Exception:
  91. # Fail closed: an unresolvable profile must not degrade to the default profile's bot.
  92. logger.debug(
  93. "platform_actions: profile resolution failed for %s",
  94. self._plugin_id, exc_info=True,
  95. )
  96. return None, _err(
  97. "adapter_not_registered",
  98. f"no {platform_enum.value} adapter is registered "
  99. "(active profile could not be resolved)",
  100. )
  101. adapter = resolve_fn(platform_enum, profile_name)
  102. else:
  103. adapter = getattr(runner, "adapters", {}).get(platform_enum)
  104. if adapter is None:
  105. return None, _err("adapter_not_registered", f"no {platform_enum.value} adapter is registered")
  106. try:
  107. connected = bool(adapter.is_connected)
  108. except Exception:
  109. connected = False
  110. if not connected:
  111. return None, _err("adapter_disconnected", f"the {platform_enum.value} adapter is not connected")
  112. return adapter, None
  113. def _gate(self, platform: str, **required: Any):
  114. """Run the shared gate chain. Returns ``(adapter, error_dict)``."""
  115. if not self._capability_granted():
  116. return None, _err(
  117. "capability_not_granted",
  118. f"plugin {self._plugin_id!r} lacks the {CAPABILITY_ID!r} "
  119. "capability (grant via consent flow or "
  120. f"plugins.entries.{self._plugin_id}.allow_platform_actions)",
  121. )
  122. for name, value in required.items():
  123. if not isinstance(value, str) or not value.strip():
  124. return None, _err("invalid_argument", f"{name} must be a non-empty string")
  125. return self._resolve_adapter(platform)
  126. async def _run(self, verb: str, platform: str, *args: str, **required: Any) -> dict[str, Any]:
  127. """Gate, dispatch *verb* to the adapter's platform implementation, audit, return."""
  128. adapter, error = self._gate(platform, **required)
  129. if error is None and adapter is not None:
  130. try:
  131. impl = _VERBS[verb].get(getattr(adapter.platform, "value", None))
  132. if impl is None:
  133. result = _err("unsupported_platform_action", f"{verb} is not implemented for {platform}")
  134. else:
  135. result = await impl(adapter, *args)
  136. except Exception as exc:
  137. result = _err("action_failed", str(exc)[:512])
  138. else:
  139. result = error or _err("gateway_unavailable")
  140. self._audit(verb, platform, result)
  141. return result
  142. # -- v1 verbs -----------------------------------------------------------
  143. async def add_reaction(self, platform: str, chat_id: str, message_id: str, emoji: str) -> dict[str, Any]:
  144. """Add/set an emoji reaction on a platform message."""
  145. return await self._run(
  146. "add_reaction", platform, chat_id, message_id, emoji,
  147. chat_id=chat_id, message_id=message_id, emoji=emoji,
  148. )
  149. async def set_thread_title(self, platform: str, chat_id: str, thread_id: str, title: str) -> dict[str, Any]:
  150. """Rename a thread / forum topic."""
  151. return await self._run(
  152. "set_thread_title", platform, chat_id, thread_id, title,
  153. chat_id=chat_id, thread_id=thread_id, title=title,
  154. )
  155. def _audit(self, verb: str, platform: str, result: dict[str, Any]) -> None:
  156. """Every platform action is logged (the #64176 'all actions logged' rule)."""
  157. logger.info(
  158. "platform_action plugin=%s verb=%s platform=%s ok=%s%s",
  159. self._plugin_id,
  160. verb,
  161. platform,
  162. result.get("ok"),
  163. "" if result.get("ok") else f" error={result.get('error')}",
  164. )