send_cmd.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. """CLI subcommand: ``hermes send`` — pipe text from shell scripts to any configured messaging platform
  2. (Telegram, Discord, Slack, Signal, SMS, etc.).
  3. """
  4. from __future__ import annotations
  5. import argparse
  6. import json
  7. import sys
  8. from pathlib import Path
  9. from typing import Optional
  10. _USAGE_EXIT = 2
  11. _FAILURE_EXIT = 1
  12. _SUCCESS_EXIT = 0
  13. def _fail(msg: str, exit_code: int | None = None) -> int:
  14. """Print ``msg`` to stderr; exit with ``exit_code`` when given, else return ``_FAILURE_EXIT``."""
  15. print(msg, file=sys.stderr)
  16. if exit_code is not None:
  17. sys.exit(exit_code)
  18. return _FAILURE_EXIT
  19. def _read_message_body(positional: Optional[str], file_path: Optional[str]) -> Optional[str]:
  20. """Resolve the message body: positional arg, then ``--file PATH`` / ``--file -`` (stdin), then
  21. piped stdin when not attached to a TTY. ``None`` when nothing is available (a usage error)."""
  22. if positional:
  23. return positional
  24. if file_path:
  25. if file_path == "-":
  26. return sys.stdin.read()
  27. try:
  28. return Path(file_path).read_text(encoding="utf-8-sig")
  29. except UnicodeDecodeError:
  30. _fail(
  31. f"hermes send: {file_path} is not a text file. --file reads the "
  32. "message *body* (logs, reports, markdown).\n"
  33. "To send an image/document/audio file as a native attachment, "
  34. "reference it with MEDIA: in the message text instead:\n"
  35. f' hermes send --to telegram "MEDIA:{file_path}"\n'
  36. f' hermes send --to telegram "optional caption MEDIA:{file_path}"\n'
  37. "Add [[as_document]] to deliver an image as an uncompressed file:\n"
  38. f' hermes send --to telegram "[[as_document]] MEDIA:{file_path}"',
  39. _USAGE_EXIT)
  40. except OSError as exc:
  41. _fail(f"hermes send: cannot read {file_path}: {exc}", _USAGE_EXIT)
  42. # Reading from a TTY would block the user in a half-broken "type your message" state.
  43. return (sys.stdin.read() or None) if not sys.stdin.isatty() else None
  44. def _invalid_whatsapp_mentions(mentions: list[str]) -> list[str]:
  45. """Return mention values that cannot identify a WhatsApp participant."""
  46. from gateway.whatsapp_identity import normalize_whatsapp_mention_jid
  47. return [mention for mention in mentions if not normalize_whatsapp_mention_jid(mention)]
  48. def _emit_result(result_json: str, *, json_mode: bool, quiet: bool) -> int:
  49. """Print the ``send_message_tool`` JSON result in the requested format; return the exit code.
  50. Unknown / unexpected shapes are failures so scripts notice."""
  51. try:
  52. payload = json.loads(result_json) if result_json else {}
  53. except json.JSONDecodeError:
  54. # Pass the raw string through so the user can still see what went wrong.
  55. payload = {"error": "invalid JSON from send_message_tool", "raw": result_json}
  56. if json_mode:
  57. print(json.dumps(payload, indent=2))
  58. elif not quiet:
  59. if payload.get("error"):
  60. print(f"hermes send: {payload['error']}", file=sys.stderr)
  61. elif payload.get("success"):
  62. print(payload.get("note") or "sent")
  63. else:
  64. print(json.dumps(payload, indent=2)) # unknown shape — dump it, drop nothing
  65. if not payload.get("error") and (payload.get("skipped") or payload.get("success")):
  66. return _SUCCESS_EXIT
  67. return _FAILURE_EXIT
  68. def _list_targets(platform_filter: Optional[str], *, json_mode: bool) -> int:
  69. """Print the channel directory (all configured targets across platforms), reusing the
  70. ``format_directory_for_display`` rendering the send_message tool shows the model."""
  71. try:
  72. from gateway.channel_directory import format_directory_for_display, load_directory
  73. except Exception as exc:
  74. return _fail(f"hermes send: failed to load channel directory: {exc}")
  75. try:
  76. raw = load_directory()
  77. except Exception as exc:
  78. return _fail(f"hermes send: failed to read channel directory: {exc}")
  79. platforms = dict(raw.get("platforms") or {})
  80. # Merge in configured-but-undiscovered platforms (e.g. a fresh SimpleX setup used only for
  81. # outbound sends) so `--list` never hides a working send target.
  82. try:
  83. from gateway.config import load_gateway_config
  84. for plat in load_gateway_config().get_connected_platforms():
  85. plat_name = getattr(plat, "value", str(plat))
  86. if plat_name not in ("local", "api_server", "webhook"):
  87. platforms.setdefault(plat_name, [])
  88. except Exception:
  89. pass # directory contents alone are still useful; don't fail --list on a config problem
  90. if platform_filter:
  91. key = platform_filter.strip().lower()
  92. filtered = {k: v for k, v in platforms.items() if k.lower() == key}
  93. if not filtered:
  94. return _fail(
  95. f"hermes send: no targets found for platform '{platform_filter}'. "
  96. f"Configured: {', '.join(sorted(platforms)) or '(none)'}")
  97. platforms = filtered
  98. if json_mode:
  99. print(json.dumps({"platforms": platforms}, indent=2, default=str))
  100. return _SUCCESS_EXIT
  101. if not platforms:
  102. print("No messaging platforms configured or no channels discovered yet.")
  103. print("Set one up with `hermes gateway setup`, or run the gateway once so")
  104. from hermes_constants import get_default_hermes_root, get_hermes_home, hermes_home_key
  105. home, root = get_hermes_home(), get_default_hermes_root()
  106. print(f"channel discovery can populate {home / 'channel_directory.json'}.")
  107. # A gateway started from the default root writes that root's directory, never this profile's.
  108. if hermes_home_key(root) != hermes_home_key(home) and (root / "channel_directory.json").exists():
  109. print(f"A gateway running from {root} already has {root / 'channel_directory.json'}; "
  110. f"this shell is scoped to profile home {home}, which has none.")
  111. return _SUCCESS_EXIT
  112. # Unfiltered: the shared formatter over the merged view. Filtered: a minimal view of our own.
  113. if platform_filter is None:
  114. print(format_directory_for_display(platforms))
  115. return _SUCCESS_EXIT
  116. for plat_name in sorted(platforms):
  117. print(f"{plat_name}:")
  118. if not platforms[plat_name]:
  119. print(" (no channels discovered yet)")
  120. continue
  121. for ch in platforms[plat_name]:
  122. name = ch.get("name", "?")
  123. chat_id = ch.get("id") or ch.get("chat_id") or ""
  124. print(f" {plat_name}:{name}" + (f" [{chat_id}]" if chat_id and chat_id != name else ""))
  125. print()
  126. return _SUCCESS_EXIT
  127. def _load_hermes_env() -> None:
  128. """Populate the credential environment from ``<HERMES_HOME>/.env`` AND bridge top-level ``config.yaml``
  129. keys into it so the gateway config loader sees platform credentials and home channels.
  130. The target is ``os.environ`` for the standalone CLI. Inside a multi-profile host (dashboard console
  131. running ``send`` for profile B under its secret scope) it is the installed scope mapping: writing B's
  132. ``.env`` into the shared process env would hand every other profile's later reads B's tokens
  133. (``gateway.config._getenv`` reads the scope first, so the loader sees the same values either way).
  134. The installed scope is already ``build_profile_secret_scope``'s composition — user ``.env``, then
  135. the profile's external secret sources over it — so it is authoritative as-is; replaying raw
  136. ``.env`` over it would let a stale user value beat the secret-manager one for this request.
  137. """
  138. from hermes_cli.config_backend import config_exists
  139. import os
  140. try:
  141. from hermes_cli.config import get_hermes_home
  142. home = get_hermes_home()
  143. except Exception:
  144. return
  145. from agent.secret_scope import current_secret_scope, is_multiplex_active
  146. scope = current_secret_scope() if is_multiplex_active() else None
  147. if isinstance(scope, dict):
  148. target: dict = scope
  149. else:
  150. target = os.environ
  151. env_path = home / ".env"
  152. if env_path.exists():
  153. try:
  154. from hermes_cli.env_loader import _load_dotenv_with_fallback
  155. _load_dotenv_with_fallback(env_path, override=True)
  156. except Exception:
  157. pass
  158. # Bridge top-level scalars the user (or the managed layer) actually wrote — never DEFAULT_CONFIG —
  159. # into the environment, without overriding existing values.
  160. config_path = home / "config.yaml"
  161. if not config_exists(config_path):
  162. return
  163. try:
  164. from hermes_cli.config_effective import load_user_config_effective
  165. cfg = load_user_config_effective(config_path)
  166. except Exception:
  167. return
  168. for key, val in cfg.items():
  169. if isinstance(val, (str, int, float, bool)) and key not in target:
  170. target[key] = str(val)
  171. def cmd_send(args: argparse.Namespace) -> None:
  172. """Entry point wired into the top-level argparse dispatcher."""
  173. _load_hermes_env() # the downstream gateway config loader reads credentials from os.environ
  174. if getattr(args, "list_targets", False): # --list short-circuits everything else
  175. # `hermes send --list telegram` lands "telegram" in the `message` positional.
  176. exit_code = _list_targets(getattr(args, "message", None), json_mode=getattr(args, "json", False))
  177. sys.exit(exit_code)
  178. target = (getattr(args, "to", None) or "").strip()
  179. if not target:
  180. _fail(
  181. "hermes send: --to PLATFORM[:channel[:thread]] is required\n"
  182. "Examples:\n"
  183. " hermes send --to telegram \"hello\"\n"
  184. " hermes send --to discord:#ops --file report.md\n"
  185. " hermes send --list # list available targets",
  186. _USAGE_EXIT)
  187. mentions = list(getattr(args, "mentions", None) or [])
  188. if mentions and target.split(":", 1)[0].strip().lower() != "whatsapp":
  189. _fail("hermes send: --mention is only supported for WhatsApp targets.", _USAGE_EXIT)
  190. invalid_mentions = _invalid_whatsapp_mentions(mentions)
  191. if invalid_mentions:
  192. _fail(
  193. "hermes send: invalid --mention value(s): "
  194. f"{', '.join(invalid_mentions)}. Use a phone number or participant JID.",
  195. _USAGE_EXIT)
  196. message = _read_message_body(getattr(args, "message", None), getattr(args, "file", None))
  197. if message is None or not message.strip():
  198. _fail(
  199. "hermes send: no message provided. Pass text as a positional "
  200. "argument, use --file PATH, or pipe data via stdin.",
  201. _USAGE_EXIT)
  202. # Optional subject line: a consistent header for alerting scripts.
  203. subject = getattr(args, "subject", None)
  204. if subject:
  205. message = f"{subject}\n\n{message.lstrip()}"
  206. # Lazy import keeps `hermes send --help` fast (no tool registry / gateway config stack).
  207. from tools.send_message_tool import send_message_tool
  208. # Routes to the platform adapter (bot-token path for built-ins, live-adapter path for plugin
  209. # platforms); takes the standard tool-call dict and returns a JSON string.
  210. tool_args = {"action": "send", "target": target, "message": message}
  211. if mentions:
  212. tool_args["mentions"] = mentions
  213. result = send_message_tool(tool_args)
  214. sys.exit(_emit_result(result, json_mode=getattr(args, "json", False), quiet=getattr(args, "quiet", False)))
  215. # (flags, add_argument kwargs) in --help order.
  216. _SEND_ARGUMENTS = (
  217. (("-t", "--to"), dict(metavar="TARGET", default=None, help=(
  218. "Delivery target. Format: 'platform' (home channel), "
  219. "'platform:chat_id', 'platform:chat_id:thread_id', or "
  220. "'platform:#channel-name'. Examples: telegram, "
  221. "telegram:-1001234567890:17585, discord:#ops, slack:C0123ABCD, signal:+15551234567."))),
  222. (("message",), dict(nargs="?", default=None, help="Message text. If omitted, read from --file or stdin.")),
  223. (("-f", "--file"), dict(metavar="PATH", default=None, help=(
  224. "Read message body from PATH (text only). Use '-' to force stdin. "
  225. "To send an image/document as an attachment, use MEDIA:<path> in the message text instead."))),
  226. (("-s", "--subject"), dict(metavar="LINE", default=None, help="Prepend a subject/header line before the message body.")),
  227. (("--mention",), dict(dest="mentions", action="append", default=None, metavar="PHONE_OR_JID", help=(
  228. "WhatsApp only: add a native participant mention. Repeat for multiple recipients; "
  229. "bare phone numbers are normalized to JIDs. Include each matching @<number> near the start of the message text."))),
  230. (("-l", "--list"), dict(dest="list_targets", action="store_true", default=False,
  231. help="List available targets. Optional positional filter: `hermes send --list telegram`.")),
  232. (("-q", "--quiet"), dict(action="store_true", default=False, help="Suppress stdout on success (exit code only).")),
  233. (("--json",), dict(action="store_true", default=False, help="Emit raw JSON result instead of human-readable output.")),
  234. )
  235. def register_send_subparser(subparsers) -> argparse.ArgumentParser:
  236. """Create the ``send`` subparser and return it."""
  237. from hermes_constants import get_hermes_home
  238. hermes_home = get_hermes_home()
  239. parser = subparsers.add_parser(
  240. "send",
  241. help="Send a message to a configured platform (scripts, cron jobs, CI).",
  242. description=(
  243. "Pipe text from any shell script to any messaging platform Hermes "
  244. "is already configured for. Reuses the gateway's platform "
  245. f"credentials ({hermes_home / '.env'} + "
  246. f"{hermes_home / 'config.yaml'}) — no LLM, "
  247. "no agent loop, no running gateway required for bot-token "
  248. "platforms like Telegram/Discord/Slack/Signal."
  249. ),
  250. epilog=(
  251. "Examples:\n"
  252. " hermes send --to telegram \"deploy finished\"\n"
  253. " echo \"RAM 92%\" | hermes send --to telegram:-1001234567890\n"
  254. " hermes send --to discord:#ops --file ./report.md\n"
  255. " hermes send --to slack:#eng --subject \"[CI]\" --file build.log\n"
  256. " hermes send --to whatsapp:GROUP@g.us --mention 15551234567 \"@15551234567 hello\"\n"
  257. " hermes send --to telegram \"MEDIA:./chart.png\" # send a media attachment\n"
  258. " hermes send --list # all platforms\n"
  259. " hermes send --list telegram # filter by platform\n"
  260. "\n"
  261. "Exit codes: 0 ok, 1 delivery/backend error, 2 usage error."
  262. ),
  263. formatter_class=argparse.RawDescriptionHelpFormatter)
  264. for flags, kwargs in _SEND_ARGUMENTS:
  265. parser.add_argument(*flags, **kwargs)
  266. parser.set_defaults(func=cmd_send)
  267. return parser
  268. __all__ = ["cmd_send", "register_send_subparser"]