adapter_choice_cards.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. """Feishu clarify cards and the finite-choice picker card.
  2. Mixed into ``FeishuAdapter``: the ``send_clarify`` / ``retire_clarify_card`` / ``send_choice_picker``
  3. capabilities from ``BasePlatformAdapter`` plus their card-action handlers. The card builders,
  4. ``_send_interactive_card``, ``_validate_card_action`` and ``_card_response`` live on the facade, so
  5. every click passes the same operator authorization and chat check as an exec-approval click before
  6. it answers anything.
  7. """
  8. from __future__ import annotations
  9. import itertools
  10. import json
  11. import logging
  12. from typing import Any, Optional
  13. from agent.i18n import t
  14. from gateway.platforms.base import SendResult
  15. logger = logging.getLogger(__name__)
  16. _BUTTON_LABEL_MAX = 40
  17. class FeishuChoiceCardsMixin:
  18. """Clarify and choice-picker cards for ``FeishuAdapter`` (needs its card/state helpers)."""
  19. # Card-action value key -> handler; the first key a click's value carries routes it.
  20. _CARD_ACTION_ROUTES = (
  21. ("hermes_action", "_handle_approval_card_action"),
  22. ("hermes_update_prompt_action", "_handle_update_prompt_card_action"),
  23. ("hermes_clarify_action", "_handle_clarify_card_action"),
  24. ("hermes_choice_picker_action", "_handle_choice_picker_card_action"),
  25. )
  26. def _init_choice_card_state(self) -> None:
  27. # clarify_id -> {session_key, message_id, chat_id, question}
  28. self._clarify_state: dict[str, dict[str, str]] = {}
  29. # picker_id -> {session_key, message_id, chat_id, body, choices, on_choice_selected, metadata}
  30. self._choice_picker_state: dict[int, dict[str, Any]] = {}
  31. self._choice_picker_counter = itertools.count(1)
  32. # --- clarify ---
  33. async def send_clarify(
  34. self, chat_id: str, question: str, choices: Optional[list], clarify_id: str,
  35. session_key: str, metadata: Optional[dict[str, Any]] = None,
  36. ) -> SendResult:
  37. """Multiple choice: a card with one numbered button per option plus "Other" (flips the entry
  38. to text capture). Open-ended: the base text prompt, answered by the next message."""
  39. if not choices:
  40. return await super().send_clarify(
  41. chat_id=chat_id, question=question, choices=choices, clarify_id=clarify_id,
  42. session_key=session_key, metadata=metadata)
  43. if not self._client:
  44. return SendResult(success=False, error="Not connected")
  45. from plugins.platforms.feishu.adapter import _card_button
  46. from tools.clarify_gateway import get_pending, mark_awaiting_text
  47. lines = [t("gateway.clarify.option_line", index=i, choice=c) for i, c in enumerate(choices, start=1)]
  48. body = f"{question}\n\n" + "\n".join(lines)
  49. entry = get_pending(clarify_id)
  50. if entry is not None and entry.multi_select:
  51. # A tap answers one option; several (or a free-form answer, as the hint says) are typed,
  52. # so typed text must be captured as the answer like the base text prompt does.
  53. body += "\n\n" + t("gateway.clarify.hint_multi")
  54. mark_awaiting_text(clarify_id)
  55. actions = [
  56. _card_button(str(i), "primary" if i == 1 else "default",
  57. {"hermes_clarify_action": str(i - 1), "clarify_id": clarify_id})
  58. for i in range(1, len(choices) + 1)]
  59. actions.append(_card_button(t("platform.feishu.clarify.other"), "default",
  60. {"hermes_clarify_action": "other", "clarify_id": clarify_id}))
  61. card = self._clarify_card(body, "blue", actions=actions)
  62. try:
  63. return await self._send_interactive_card(
  64. chat_id, card, metadata, "send_clarify failed", state_map=self._clarify_state,
  65. state_id=clarify_id, session_key=session_key, extra_state={"question": str(question)})
  66. except Exception as exc:
  67. logger.warning("[Feishu] send_clarify failed: %s", exc, exc_info=True)
  68. return SendResult(success=False, error=str(exc))
  69. @staticmethod
  70. def _clarify_card(body: str, template: str, *, actions: Optional[list] = None) -> dict[str, Any]:
  71. from plugins.platforms.feishu.adapter import _card
  72. card = _card(f"❓ {t('platform.feishu.clarify.title')}", template, body, actions=actions)
  73. # Shared card: PATCH (retire_clarify_card) only reaches every recipient when the sent AND
  74. # the updated card both declare it.
  75. card["config"]["update_multi"] = True
  76. return card
  77. @classmethod
  78. def _settled_clarify_card(cls, state: dict[str, str], line: str, template: str) -> dict[str, Any]:
  79. return cls._clarify_card(f"{state.get('question', '')}\n\n{line}", template)
  80. def _handle_clarify_card_action(self, *, event: Any, action_value: dict[str, Any], loop: Any) -> Any:
  81. """Answer a clarify from a tap and return the settled card inline (syncs every client).
  82. ``resolve_gateway_clarify`` is a locked Event set, safe from the SDK callback thread."""
  83. clarify_id = str(action_value.get("clarify_id") or "")
  84. state = self._clarify_state.get(clarify_id)
  85. if not state:
  86. logger.debug("[Feishu] Clarify %s already resolved or unknown", clarify_id or "<missing>")
  87. return self._card_response()
  88. checked = self._validate_card_action(event=event, state=state, label="clarify", ident=clarify_id)
  89. if checked is None:
  90. return self._card_response()
  91. user_name = checked[2]
  92. from tools import clarify_gateway
  93. entry = clarify_gateway.get_pending(clarify_id)
  94. token = str(action_value.get("hermes_clarify_action") or "")
  95. if entry is None or entry.session_key != state.get("session_key"):
  96. # The wait ended (timeout, /new) before the retire reached this card.
  97. self._clarify_state.pop(clarify_id, None)
  98. return self._card_response(self._settled_clarify_card(state, t("gateway.clarify.expired"), "grey"))
  99. if token == "other":
  100. # State stays so the typed answer's retire_clarify_card can settle this card.
  101. if not clarify_gateway.mark_awaiting_text(clarify_id):
  102. return self._card_response(self._settled_clarify_card(state, t("gateway.clarify.expired"), "grey"))
  103. awaiting = t("platform.feishu.clarify.awaiting_typed", user=user_name)
  104. return self._card_response(self._settled_clarify_card(state, f"*{awaiting}*", "blue"))
  105. choices = list(entry.choices or [])
  106. if not (token.isdigit() and int(token) < len(choices)):
  107. logger.debug("[Feishu] Clarify %s has invalid choice token=%r", clarify_id, token)
  108. return self._card_response()
  109. if self._clarify_state.pop(clarify_id, None) is None:
  110. return self._card_response() # a concurrent tap won
  111. answer = str(choices[int(token)])
  112. if not clarify_gateway.resolve_gateway_clarify(clarify_id, answer):
  113. return self._card_response(self._settled_clarify_card(state, t("gateway.clarify.expired"), "grey"))
  114. logger.info("Feishu clarify button resolved (id=%s, choice=%r, user=%s)", clarify_id, answer, user_name)
  115. return self._card_response(self._settled_clarify_card(state, f"**{user_name}:** {answer}", "green"))
  116. async def retire_clarify_card(self, clarify_id: str, notice: str) -> None:
  117. """Gateway hook for a clarify that ended without a tap (timeout, reset, superseding prose,
  118. typed answer): rewrite the card button-less. The state pop runs before the first await, so a
  119. tap racing this call is refused."""
  120. state = self._clarify_state.pop(clarify_id, None)
  121. if not state or not state.get("message_id") or not self._client:
  122. return
  123. from plugins.platforms.feishu import adapter as facade
  124. card = self._settled_clarify_card(state, notice, "grey")
  125. body = facade._sdk_build(facade.PatchMessageRequestBody, content=json.dumps(card, ensure_ascii=False))
  126. request = facade._sdk_build(facade.PatchMessageRequest, message_id=state["message_id"], request_body=body)
  127. response = await self._run_blocking(self._client.im.v1.message.patch, request)
  128. if not self._response_succeeded(response):
  129. logger.debug("[Feishu] Retiring clarify card %s rejected: code=%s", clarify_id, getattr(response, "code", None))
  130. # --- finite-choice picker ---
  131. async def send_choice_picker(
  132. self, chat_id: str, title: str, choices: list, session_key: str, on_choice_selected,
  133. metadata: Optional[dict[str, Any]] = None,
  134. ) -> SendResult:
  135. """One-tap picker card for /reasoning, /fast, etc.; choice dicts are
  136. ``{"value", "label", "is_current"}``. One live picker per chat, like Telegram."""
  137. if not self._client:
  138. return SendResult(success=False, error="Not connected")
  139. if not choices:
  140. return SendResult(success=False, error="No choices")
  141. from plugins.platforms.feishu.adapter import _card_button
  142. picker_id = next(self._choice_picker_counter)
  143. actions = []
  144. for i, choice in enumerate(choices):
  145. label = str(choice.get("label") or choice.get("value") or "")
  146. label = self._truncate_preview(f"✓ {label}" if choice.get("is_current") else label, _BUTTON_LABEL_MAX, "…")
  147. actions.append(_card_button(label, "primary" if choice.get("is_current") else "default",
  148. {"hermes_choice_picker_action": str(i), "picker_id": picker_id}))
  149. heading, _, rest = str(title or "").partition("\n")
  150. header = heading.replace("*", "").strip()
  151. # A one-line title (usage-limit offer) gets the full labels as body: buttons truncate them.
  152. body = rest.strip() or "\n".join(f"• {c.get('label') or c.get('value') or ''}" for c in choices)
  153. try:
  154. result = await self._send_interactive_card(
  155. chat_id, self._picker_card(header, "blue", body, actions=actions), metadata, "send_choice_picker failed",
  156. state_map=self._choice_picker_state, state_id=picker_id, session_key=session_key,
  157. extra_state={"header": header, "body": body, "choices": choices,
  158. "on_choice_selected": on_choice_selected, "metadata": metadata})
  159. except Exception as exc:
  160. logger.warning("[Feishu] send_choice_picker failed: %s", exc, exc_info=True)
  161. return SendResult(success=False, error=str(exc))
  162. if result.success:
  163. # Snapshot: the SDK callback thread pops from this dict concurrently.
  164. for stale in [k for k, v in list(self._choice_picker_state.items()) if k != picker_id and v["chat_id"] == chat_id]:
  165. self._choice_picker_state.pop(stale, None)
  166. return result
  167. def _handle_choice_picker_card_action(self, *, event: Any, action_value: dict[str, Any], loop: Any) -> Any:
  168. """Settle the picker card inline and run the selection's applier on the adapter loop."""
  169. picker_id = action_value.get("picker_id")
  170. state = self._choice_picker_state.get(picker_id)
  171. if not state:
  172. logger.debug("[Feishu] Choice picker %s already resolved or unknown", picker_id)
  173. return self._card_response()
  174. checked = self._validate_card_action(event=event, state=state, label="choice picker", ident=picker_id)
  175. if checked is None:
  176. return self._card_response()
  177. token = str(action_value.get("hermes_choice_picker_action") or "")
  178. choices = state["choices"]
  179. if not (token.isdigit() and int(token) < len(choices)):
  180. return self._card_response()
  181. if self._choice_picker_state.pop(picker_id, None) is None:
  182. return self._card_response() # a concurrent tap won
  183. choice = choices[int(token)]
  184. if not self._submit_on_loop(loop, self._apply_choice_picker_selection(state, str(choice.get("value") or ""))):
  185. self._choice_picker_state[picker_id] = state
  186. return self._card_response()
  187. label = str(choice.get("label") or choice.get("value") or "")
  188. return self._card_response(self._picker_card(state["header"], "green", f"{state['body']}\n\n✓ **{label}** — {checked[2]}"))
  189. @staticmethod
  190. def _picker_card(header: str, template: str, body: str, *, actions: Optional[list] = None) -> dict[str, Any]:
  191. from plugins.platforms.feishu.adapter import _card
  192. card = _card(header, template, body, actions=actions)
  193. card["config"]["update_multi"] = True # shared: the inline settle reaches the whole group
  194. return card
  195. def _on_webhook_card_action(self, payload: dict[str, Any]) -> dict[str, Any]:
  196. """A card tap over HTTP, handled as the SDK delivers it: the button value stays a dict (the
  197. routes key on it) and the settled card goes back as the response body."""
  198. data = self._namespace_from_mapping(payload)
  199. action = getattr(getattr(data, "event", None), "action", None)
  200. if action is not None:
  201. action.value = ((payload.get("event") or {}).get("action") or {}).get("value")
  202. card = getattr(self._on_card_action_trigger(data), "card", None)
  203. return {"card": {"type": card.type, "data": card.data}} if card is not None else {}
  204. async def _apply_choice_picker_selection(self, state: dict[str, Any], value: str) -> None:
  205. """Run the picker's applier and send its confirmation to the chat."""
  206. try:
  207. result_text = await state["on_choice_selected"](state["chat_id"], value)
  208. except Exception as exc:
  209. logger.exception("[Feishu] Choice picker selection failed: %s", exc)
  210. result_text = t("platform.feishu.picker.apply_error", error=str(exc))
  211. if result_text:
  212. await self.send(state["chat_id"], str(result_text), metadata=state.get("metadata"))