send_message_targets.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. """Target parsing and resolution for send_message (platform:chat_id[:thread] → ids)."""
  2. import logging
  3. import re
  4. logger = logging.getLogger("tools.send_message_tool")
  5. # E.164 phone recipients ("+1555..."): the '+' fails the isdigit() rule and the channel directory
  6. # cannot resolve a raw number, so keep the '+' and treat it as explicit.
  7. _PHONE_PLATFORMS = frozenset({"photon", "signal", "sms", "whatsapp"})
  8. _E164_TARGET_RE = re.compile(r"^\s*\+(\d{7,15})\s*$")
  9. # Exceptions to "<PLATFORM>_HOME_CHANNEL" for error hints (email reads EMAIL_HOME_ADDRESS).
  10. _HOME_CHANNEL_ENV_OVERRIDES = {"email": "EMAIL_HOME_ADDRESS"}
  11. def _target_syntax_fn(platform_name: str):
  12. """The plugin's declared native target syntax, or None. A fresh CLI/cron process can parse a
  13. target before plugin discovery registered the platform, so discover first when the name is
  14. unknown (idempotent manifest scan; only this platform's adapter is materialized)."""
  15. from gateway.platform_registry import platform_registry
  16. if not platform_registry.is_registered(platform_name):
  17. from hermes_cli.plugins import discover_plugins
  18. discover_plugins()
  19. entry = platform_registry.get(platform_name)
  20. return entry.target_ref_syntax_fn if entry is not None else None
  21. def _parse_target_ref(platform_name: str, target_ref: str):
  22. """(chat_id, thread_id, explicit): the plugin's ``target_ref_syntax_fn`` first, then in order
  23. E.164 phone numbers (keeping the '+'), bare numeric ids, Matrix ``!room``/``@user``, XMPP JIDs.
  24. Anything else goes to channel-directory resolution."""
  25. from gateway.platforms.send_targets import NOT_EXPLICIT
  26. parser = _target_syntax_fn(platform_name)
  27. if parser is not None:
  28. parsed = parser(target_ref)
  29. if parsed is NOT_EXPLICIT:
  30. return None, None, False
  31. if parsed is not None:
  32. return parsed[0], parsed[1], True
  33. if platform_name in _PHONE_PLATFORMS and _E164_TARGET_RE.fullmatch(target_ref):
  34. return target_ref.strip(), None, True
  35. if (target_ref.lstrip("-").isdigit() or (platform_name == "matrix" and target_ref.startswith(("!", "@")))
  36. or (platform_name == "xmpp" and "@" in target_ref)):
  37. return target_ref, None, True
  38. return None, None, False
  39. def unknown_platform_error(platform_name: str) -> str:
  40. from hermes_cli.left_core_migration import platform_install_hint
  41. return f"Unknown or unregistered plugin platform: {platform_name}{platform_install_hint(platform_name)}"
  42. def resolve_send_target(
  43. platform_name: str, target_ref: str, *, pass_unresolved_references: bool = False
  44. ) -> tuple[str | None, str | None, str | None]:
  45. """Resolve one send target the same way for every caller (model tool, CLI, cron).
  46. Channel-directory IDs are trusted; plugin parsers are the authority on native syntax. By
  47. default an unresolvable target is an error the model can act on. ``pass_unresolved_references``
  48. (no model in the loop: cron, react/unreact on native ids) hands an unresolvable target on a
  49. built-in platform, or a plugin platform without a parser, to the adapter as written; a plugin
  50. WITH a parser stays strict. The optional validator has the final say over every returned id."""
  51. from gateway.config import Platform
  52. from gateway.platform_registry import platform_registry
  53. entry = platform_registry.get(platform_name)
  54. def _validated(chat_id, thread_id):
  55. """``(chat_id, thread_id, None)`` when the plugin validator (if any) accepts, else an error."""
  56. if entry is None or entry.validate_target_ref_fn is None:
  57. return chat_id, thread_id, None
  58. try:
  59. verdict = entry.validate_target_ref_fn(chat_id)
  60. except Exception:
  61. logger.debug("Plugin target validator failed for %s", platform_name, exc_info=True)
  62. return None, None, f"Target validator failed for platform '{platform_name}'"
  63. if verdict is True:
  64. return chat_id, thread_id, None
  65. detail = f": {verdict}" if isinstance(verdict, str) and verdict else ""
  66. return None, None, f"Invalid target '{target_ref}' on {platform_name}{detail}"
  67. if entry is not None and entry.parse_target_ref_fn is not None:
  68. try:
  69. parsed = entry.parse_target_ref_fn(target_ref)
  70. except Exception:
  71. logger.debug("Plugin target parser failed for %s", platform_name, exc_info=True)
  72. return None, None, f"Target parser failed for platform '{platform_name}'"
  73. if parsed is not None:
  74. if (not isinstance(parsed, tuple) or len(parsed) != 2 or not isinstance(parsed[0], str)
  75. or not parsed[0] or (parsed[1] is not None and not isinstance(parsed[1], str))):
  76. return None, None, f"Target parser for platform '{platform_name}' returned an invalid result"
  77. return _validated(*parsed)
  78. parsed_chat_id, parsed_thread_id, explicit = _parse_target_ref(platform_name, target_ref)
  79. if explicit and parsed_chat_id is not None:
  80. return _validated(parsed_chat_id, parsed_thread_id)
  81. resolution_failed = False
  82. try:
  83. from gateway.channel_directory import resolve_channel_name
  84. resolved = resolve_channel_name(platform_name, target_ref)
  85. except Exception:
  86. resolved = None
  87. resolution_failed = True
  88. if resolved:
  89. parsed_chat_id, parsed_thread_id, _ = _parse_target_ref(platform_name, resolved)
  90. return _validated(parsed_chat_id or resolved, parsed_thread_id)
  91. is_builtin = platform_name in {member.value for member in Platform}
  92. if entry is None and not is_builtin:
  93. return None, None, unknown_platform_error(platform_name)
  94. is_plugin = entry is not None and entry.source == "plugin" and not is_builtin
  95. if pass_unresolved_references and (not is_plugin or entry.parse_target_ref_fn is None):
  96. # Hand the raw target to the adapter unchanged (it validates).
  97. chat_id, thread_id, error = _validated(target_ref, None)
  98. if not error:
  99. logger.debug("Handing unresolved target '%s' to the %s adapter unchanged "
  100. "(the adapter validates it)", target_ref, platform_name)
  101. return chat_id, thread_id, error
  102. if is_plugin:
  103. hint = "The plugin parser did not recognize it and no channel-directory entry matched."
  104. elif resolution_failed:
  105. hint = "Try using a numeric channel ID instead."
  106. else:
  107. hint = "Use send_message(action='list') to see available targets."
  108. return None, None, f"Could not resolve '{target_ref}' on {platform_name}. {hint}"