mirror.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. """Session mirroring for cross-platform message delivery.
  2. When a message is sent to a platform (send_message or cron delivery), append a
  3. "delivery-mirror" record to the target session's transcript so the receiving-side
  4. agent knows what was sent. Standalone: works from CLI, cron and gateway contexts.
  5. """
  6. import json
  7. import logging
  8. from datetime import datetime
  9. from pathlib import Path
  10. from typing import Optional
  11. from hermes_cli.config import get_hermes_home
  12. logger = logging.getLogger(__name__)
  13. _SESSIONS_DIR = get_hermes_home() / "sessions"
  14. _SESSIONS_INDEX = _SESSIONS_DIR / "sessions.json"
  15. _SESSIONS_INDEX_AT_IMPORT = _SESSIONS_INDEX
  16. def _resolve_sessions_index() -> Path:
  17. """Active profile's ``sessions.json`` at call time: the patched ``_SESSIONS_INDEX`` when a test
  18. changed it, else live profile-scoped HERMES_HOME — under the multiplexed gateway one process
  19. serves every profile, so the import-time constant would resolve every profile's pre-migration
  20. session lookup against the launch profile's index."""
  21. return (_SESSIONS_INDEX if _SESSIONS_INDEX != _SESSIONS_INDEX_AT_IMPORT
  22. else get_hermes_home() / "sessions" / "sessions.json")
  23. def _origin_user_id(entry: dict) -> str:
  24. return str((entry.get("origin") or {}).get("user_id") or "")
  25. def mirror_to_session(
  26. platform: str, chat_id: str, message_text: str, source_label: str = "cli", thread_id: Optional[str] = None,
  27. user_id: Optional[str] = None, role: str = "assistant", session_id: Optional[str] = None,
  28. ) -> bool:
  29. """Append a delivery-mirror message to the target session's SQLite transcript.
  30. Pass ``session_id`` when the caller already holds the exact session (e.g. the
  31. cron in_channel seed) to skip the origin scan, which refuses to guess on a
  32. populated chat (flat + N thread sessions per chat_id) and would drop the mirror.
  33. Text that is NOT the agent speaking (e.g. a cron brief) must pass
  34. ``role="user"``: ``mirror`` metadata is dropped at the SQLite boundary, so an
  35. assistant-role mirror replays as a real turn and yields assistant→assistant
  36. pairs that break strict-alternation providers, while a user-role mirror
  37. collapses safely via the consecutive-user merge.
  38. Returns True if mirrored, False if no matching session or error. Never raises.
  39. ``role`` defaults to ``"assistant"`` — correct for the interactive ``send_message`` mirror, where the
  40. mirrored text is the agent's own outgoing reply (a genuine assistant turn). See #2221.
  41. """
  42. try:
  43. if not session_id:
  44. session_id = _find_session_id(platform, str(chat_id), thread_id=thread_id, user_id=user_id)
  45. if not session_id:
  46. logger.warning(
  47. "Mirror: no session found for %s:%s thread=%s user=%s (explicit_id=none, origin-scan bailed)",
  48. platform, chat_id, thread_id, user_id,
  49. )
  50. return False
  51. _append_to_sqlite(session_id, {
  52. "role": role, "content": message_text, "timestamp": datetime.now().isoformat(),
  53. "mirror": True, "mirror_source": source_label,
  54. })
  55. logger.debug("Mirror: wrote to session %s (from %s)", session_id, source_label)
  56. return True
  57. except Exception as e:
  58. # WARNING, not debug: a silent mirror drop is the cron continuation-amnesia bug.
  59. logger.warning("Mirror failed for %s:%s thread=%s user=%s session=%s: %s", platform, chat_id, thread_id, user_id, session_id, e)
  60. return False
  61. def _find_session_id(platform: str, chat_id: str, thread_id: Optional[str] = None, user_id: Optional[str] = None) -> Optional[str]:
  62. """Active session_id for a platform + chat_id pair.
  63. state.db is primary; sessions.json is the pre-migration fallback. DM keys
  64. don't embed the chat_id ("agent:main:telegram:dm"), so match on the persisted
  65. origin. With *user_id*, exact sender matches win; several same-chat candidates
  66. with no user match → None rather than contaminate another participant's session.
  67. Queries state.db gateway session rows (primary source since #9006); falls back to scanning sessions.json
  68. for pre-migration databases.
  69. """
  70. try:
  71. from hermes_state_registry import acquire, release_or_close
  72. db = acquire()
  73. try:
  74. finder = getattr(db, "find_session_by_origin", None)
  75. session_id = finder(platform=platform, chat_id=chat_id, thread_id=thread_id, user_id=user_id) if callable(finder) else None
  76. if session_id:
  77. return str(session_id)
  78. finally:
  79. release_or_close(db)
  80. except Exception as e:
  81. logger.debug("Mirror state.db session lookup failed: %s", e)
  82. sessions_index = _resolve_sessions_index()
  83. if not sessions_index.exists():
  84. return None
  85. try:
  86. data = json.loads(sessions_index.read_text(encoding="utf-8-sig"))
  87. except Exception:
  88. return None
  89. def _matches(entry: dict) -> bool:
  90. origin = entry.get("origin") or {}
  91. return ((origin.get("platform") or entry.get("platform", "")).lower() == platform.lower()
  92. and str(origin.get("chat_id", "")) == str(chat_id)
  93. and (thread_id is None or str(origin.get("thread_id") or "") == str(thread_id)))
  94. # Keys starting with "_" (e.g. the gateway's "_README") are metadata sentinels.
  95. candidates = [e for k, e in data.items() if not str(k).startswith("_") and isinstance(e, dict) and _matches(e)]
  96. if not candidates:
  97. return None
  98. if user_id:
  99. exact_user_matches = [e for e in candidates if _origin_user_id(e) == str(user_id)]
  100. if exact_user_matches:
  101. candidates = exact_user_matches
  102. elif len(candidates) > 1:
  103. return None
  104. elif len(candidates) > 1 and len({u.strip() for u in map(_origin_user_id, candidates) if u.strip()}) > 1:
  105. return None
  106. return max(candidates, key=lambda entry: entry.get("updated_at", "")).get("session_id")
  107. def _append_to_sqlite(session_id: str, message: dict) -> None:
  108. """Append a message to the SQLite session database.
  109. Raises on failure: ``mirror_to_session`` reports ``False`` (and warns) only when the
  110. exception reaches it — swallowing it here made every failed write look mirrored (#10130).
  111. """
  112. from hermes_state_registry import acquire, release_or_close
  113. db = acquire()
  114. try:
  115. db.append_message(session_id=session_id, role=message.get("role", "assistant"), content=message.get("content"))
  116. finally:
  117. release_or_close(db)