react_to_message_tool.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. #!/usr/bin/env python3
  2. """Agent emoji reaction in the Hermes desktop app: the counterpart to the user's tapback
  3. (same store, one-per-author, ``author="agent"``). Lives in the ``desktop_ui`` toolset so it
  4. costs nothing elsewhere (adapters expose reactions via ``send_message(action="react")``);
  5. defaults to the triggering message and emits ``message.reaction`` for live painting."""
  6. import contextlib
  7. import json
  8. from gateway.session_context import get_session_env
  9. from tools import desktop_ui
  10. from tools.registry import registry, tool_error
  11. def _open_session_db():
  12. """Open the SessionDB for the profile owning this turn, or ``None``."""
  13. try:
  14. from hermes_state_registry import acquire
  15. return acquire()
  16. except Exception:
  17. return None
  18. def react_to_message_tool(emoji: str, message_row_id=None, messages_back=None) -> str:
  19. """Attach (or with an empty ``emoji`` retract) the agent's reaction."""
  20. emoji = (emoji or "").strip()
  21. # Routing keys identify a channel; message rows belong to the live durable session.
  22. session_key = get_session_env("HERMES_SESSION_ID", "") or get_session_env("HERMES_SESSION_KEY", "")
  23. if not session_key:
  24. return tool_error("No active session — reactions need a persisted conversation.")
  25. db = _open_session_db()
  26. if db is None:
  27. return tool_error("Session storage is unavailable.")
  28. try:
  29. row_id, target_role = message_row_id, "user"
  30. if row_id is None:
  31. # Default: the latest user message; `messages_back` steps to earlier user turns
  32. # (ids aren't visible to the model; "two messages ago" is how a person thinks).
  33. back = max(0, int(messages_back or 0))
  34. row_id = db.latest_message_row_id(session_key, role="user", offset=back)
  35. if row_id is None:
  36. return tool_error(f"No user message found {back} back." if back else "No user message to react to yet.")
  37. else:
  38. target_role = db.get_message_role(session_key, int(row_id)) or "user"
  39. try:
  40. reactions = db.set_message_reaction(session_key, int(row_id), emoji or None, author="agent")
  41. except Exception as exc:
  42. return tool_error(f"Failed to set the reaction: {exc}")
  43. if reactions is None:
  44. return tool_error(f"Message {row_id} is not part of this conversation.")
  45. # Paint it live; a missing bridge (non-desktop) is not an error — the reaction is
  46. # persisted. `role` lets the renderer match a live message without a durable row id.
  47. with contextlib.suppress(Exception):
  48. desktop_ui.emit("message.reaction", {"row_id": int(row_id), "reactions": reactions, "role": target_role})
  49. return json.dumps({"success": True, "row_id": int(row_id), "reactions": reactions}, ensure_ascii=False)
  50. finally:
  51. with contextlib.suppress(Exception):
  52. from hermes_state_registry import release_or_close
  53. release_or_close(db)
  54. def check_react_requirements() -> bool:
  55. """Opt-in flag (Settings → Appearance); ``desktop_ui`` already restricts to GUI sessions."""
  56. return desktop_ui.user_enabled("message_reactions", default=False)
  57. REACT_TO_MESSAGE_SCHEMA = {
  58. "name": "react_to_message",
  59. "description": (
  60. "React to a message with a single emoji, the way you'd tapback in iMessage. "
  61. "Reach for it when a reaction is what a person would do: something funny gets "
  62. "a 😂, warmth gets a ❤️, a plan you're on board with gets a 👍 — then just "
  63. "carry on with whatever the message actually needs. If a reaction says it "
  64. "all, it can BE the reply (skip the redundant 'sounds good!' turn). Use it "
  65. "like a person would: occasionally, when felt — not on every message, and "
  66. "never as a status signal. NEVER narrate or explain a reaction ('I reacted "
  67. "with...', 'Reacting now') — the emoji appearing on the bubble is the whole "
  68. "point, and commentary kills it. Defaults to the user's most recent message. "
  69. "One reaction per message: a different emoji replaces yours, an empty string "
  70. "retracts it."
  71. ),
  72. "parameters": {
  73. "type": "object",
  74. "properties": {
  75. "emoji": {
  76. "type": "string",
  77. "description": (
  78. "The emoji to react with (e.g. '❤️', '😂', '👍'). Pass an empty "
  79. "string to remove your reaction."
  80. ),
  81. },
  82. "message_row_id": {
  83. "type": "integer",
  84. "description": (
  85. "Optional. The specific message to react to. Omit to react to the "
  86. "user's latest message, which is almost always what you want."
  87. ),
  88. },
  89. "messages_back": {
  90. "type": "integer",
  91. "description": (
  92. "Optional. React to an EARLIER user message: 1 = the one before "
  93. "the latest, 2 = two before, and so on. For when something lands "
  94. "late — the joke you only got after answering."
  95. ),
  96. },
  97. },
  98. "required": ["emoji"],
  99. },
  100. }
  101. registry.register(
  102. name="react_to_message", toolset="desktop_ui", schema=REACT_TO_MESSAGE_SCHEMA,
  103. handler=lambda args, **kw: react_to_message_tool(
  104. emoji=args.get("emoji", ""), message_row_id=args.get("message_row_id"),
  105. messages_back=args.get("messages_back")),
  106. check_fn=check_react_requirements, emoji="💛",
  107. )