slack_cli.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. """``hermes slack manifest`` — generate the Slack app manifest JSON that registers every gateway
  2. command as a native Slack slash (``/btw``, ``/stop``, ``/model``, …)."""
  3. from __future__ import annotations
  4. import json
  5. import sys
  6. from pathlib import Path
  7. SLACK_LONG_DESCRIPTION_MIN_CHARACTERS = 175
  8. SLACK_LONG_DESCRIPTION_MAX_CHARACTERS = 4000
  9. def _build_full_manifest(
  10. bot_name: str, bot_description: str, include_assistant: bool = True,
  11. messaging_experience: str | None = None, long_description: str | None = None) -> dict:
  12. """Build a full Slack manifest: display info + slash list from ``COMMAND_REGISTRY``.
  13. Other sections (OAuth scopes, socket mode) are sensible Hermes defaults, tweakable in the Slack
  14. UI after pasting.
  15. """
  16. from hermes_cli.commands_platforms import slack_app_manifest
  17. if messaging_experience is None:
  18. messaging_experience = "assistant" if include_assistant else "none"
  19. messaging_experience = str(messaging_experience).strip().lower()
  20. if messaging_experience not in {"assistant", "agent", "none"}:
  21. raise ValueError("messaging_experience must be one of: assistant, agent, none")
  22. features = {
  23. "app_home": {
  24. "home_tab_enabled": False,
  25. "messages_tab_enabled": True,
  26. "messages_tab_read_only_enabled": False},
  27. "bot_user": {"display_name": bot_name[:80], "always_online": True},
  28. "slash_commands": slack_app_manifest()["features"]["slash_commands"]}
  29. bot_scopes = [
  30. "app_mentions:read", "channels:history", "channels:read", "chat:write", "commands",
  31. "files:read", "files:write", "groups:history", "groups:read", "im:history", "im:read",
  32. "im:write", "mpim:history", "mpim:read", "reactions:read", "users:read"]
  33. bot_events = [
  34. "app_mention", "message.channels", "message.groups", "message.im", "message.mpim",
  35. "reaction_added", "reaction_removed"]
  36. if messaging_experience == "assistant":
  37. features["assistant_view"] = {
  38. "assistant_description": "Chat with Hermes in threads and DMs."}
  39. bot_scopes.append("assistant:write")
  40. bot_events.extend(["assistant_thread_context_changed", "assistant_thread_started"])
  41. elif messaging_experience == "agent":
  42. features["agent_view"] = {"agent_description": "Chat with Hermes in Slack Messages."}
  43. bot_scopes.append("assistant:write")
  44. # Slack includes current viewing context in Agent DM events only after this subscription
  45. # is enabled; the adapter uses it to preserve the referred channel across the agent turn.
  46. bot_events.extend(["app_context_changed", "app_home_opened"])
  47. bot_scopes.sort()
  48. bot_events.sort()
  49. display_information = {
  50. "name": bot_name[:35],
  51. "description": (bot_description or "Your Hermes agent on Slack")[:140],
  52. "background_color": "#1a1a2e"}
  53. if long_description is not None:
  54. display_information["long_description"] = long_description
  55. return {
  56. "_metadata": {"major_version": 1, "minor_version": 1},
  57. "display_information": display_information,
  58. "features": features,
  59. "oauth_config": {"scopes": {"bot": bot_scopes}},
  60. "settings": {
  61. "event_subscriptions": {"bot_events": bot_events},
  62. "interactivity": {"is_enabled": True},
  63. "org_deploy_enabled": False,
  64. "socket_mode_enabled": True,
  65. "token_rotation_enabled": False}}
  66. def slack_manifest_command(args) -> int:
  67. """Print or write a Slack app manifest JSON (flags documented in ``hermes_cli/main.py``)."""
  68. name = getattr(args, "name", None) or "Hermes"
  69. description = getattr(args, "description", None) or "Your Hermes agent on Slack"
  70. long_description = getattr(args, "long_description", None)
  71. long_description_file = getattr(args, "long_description_file", None)
  72. slashes_only = getattr(args, "slashes_only", False)
  73. def fail(msg: str) -> int:
  74. print(f"hermes slack manifest: {msg}", file=sys.stderr)
  75. return 2
  76. if slashes_only and (long_description is not None or long_description_file is not None):
  77. return fail("long description options cannot be used with --slashes-only")
  78. if long_description_file is not None:
  79. source_arg = str(long_description_file)
  80. try:
  81. source = Path(source_arg).expanduser()
  82. with source.open("r", encoding="utf-8-sig", newline="") as handle:
  83. long_description = handle.read()
  84. except (OSError, UnicodeError, RuntimeError) as exc:
  85. return fail(f"cannot read long description from {source_arg}: {exc}")
  86. if long_description is not None:
  87. n = len(long_description)
  88. if n < SLACK_LONG_DESCRIPTION_MIN_CHARACTERS:
  89. return fail(f"long description must be at least "
  90. f"{SLACK_LONG_DESCRIPTION_MIN_CHARACTERS} characters (got {n})")
  91. if n > SLACK_LONG_DESCRIPTION_MAX_CHARACTERS:
  92. return fail(f"long description must be at most "
  93. f"{SLACK_LONG_DESCRIPTION_MAX_CHARACTERS} characters (got {n})")
  94. if getattr(args, "agent_view", False):
  95. messaging_experience = "agent"
  96. elif getattr(args, "no_assistant", False):
  97. messaging_experience = "none"
  98. else:
  99. messaging_experience = "assistant"
  100. if slashes_only:
  101. from hermes_cli.commands_platforms import slack_app_manifest
  102. manifest = slack_app_manifest()["features"]["slash_commands"]
  103. else:
  104. manifest = _build_full_manifest(
  105. name, description, messaging_experience=messaging_experience,
  106. long_description=long_description)
  107. payload = json.dumps(manifest, indent=2, ensure_ascii=False) + "\n"
  108. write_target = getattr(args, "write", None)
  109. if write_target is None:
  110. sys.stdout.write(payload)
  111. return 0
  112. if isinstance(write_target, bool) and write_target: # bare --write → default location
  113. from hermes_constants import get_hermes_home
  114. target = Path(get_hermes_home()) / "slack-manifest.json"
  115. else:
  116. target = Path(write_target).expanduser()
  117. target.parent.mkdir(parents=True, exist_ok=True)
  118. target.write_text(payload, encoding="utf-8")
  119. print(f"Slack manifest written to: {target}", file=sys.stderr)
  120. print(
  121. "\nNext steps:\n"
  122. " 1. Open https://api.slack.com/apps and pick your Hermes app\n"
  123. " (or create a new one: Create New App → From an app manifest).\n"
  124. f" 2. Features → App Manifest → paste the contents of\n"
  125. f" {target}\n"
  126. " 3. Save; Slack will prompt to reinstall the app if scopes or\n"
  127. " slash commands changed.\n"
  128. " 4. Make sure Socket Mode is enabled and you have a bot token\n"
  129. " (xoxb-...) and app token (xapp-...) configured via\n"
  130. " `hermes setup`.\n", file=sys.stderr)
  131. return 0