gateway.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. """``hermes gateway`` and ``hermes proxy`` subcommand parsers."""
  2. from __future__ import annotations
  3. import argparse
  4. from typing import Callable
  5. from hermes_cli.subcommands._shared import add_accept_hooks_flag
  6. # `start`/`restart` on a named profile refuse while the default multiplexer serves it (a second gateway
  7. # would double-bind its platforms); `gateway run` carries its own broader --force text.
  8. _FORCE_SERVED_PROFILE_HELP = (
  9. "Start a separate gateway for this profile even when the default multiplexer already serves it "
  10. "(not recommended: two pollers on one bot token, port conflicts)")
  11. # `stop`/`restart` ask before interrupting live turns, cron jobs or background delegations.
  12. _INTERRUPT_HELP = (
  13. "{verb} without asking even while sessions are live (turns, cron jobs, background delegations): "
  14. "they are interrupted. Without it the command names the live work and asks y/N (refuses when "
  15. "there is no terminal). --interrupt is the same flag")
  16. class _GatewayCommandParser(argparse.ArgumentParser):
  17. """Ensure's parser errors share its machine-readable command boundary."""
  18. def __init__(self, *args, ensure_json=False, **kwargs):
  19. self.ensure_json = ensure_json
  20. super().__init__(*args, **kwargs)
  21. def parse_known_args(self, args=None, namespace=None):
  22. parsed, unknown = super().parse_known_args(args, namespace)
  23. if self.ensure_json and unknown:
  24. self.error("unknown arguments")
  25. return parsed, unknown
  26. def error(self, message):
  27. if not self.ensure_json:
  28. return super().error(message)
  29. print('{"endpoint":null,"reason_code":"invalid_invocation","state":"inaccessible"}')
  30. self.exit(2, "gateway ensure: invalid invocation\n")
  31. def _flag(parser, *names, help, **kw):
  32. parser.add_argument(*names, action="store_true", help=help, **kw)
  33. def _add_compat_platform_flag(parser: argparse.ArgumentParser) -> None:
  34. """Accept stale `gateway <verb> --platform X` docs without advertising it.
  35. Lifecycle commands operate on the gateway process, not one adapter; Photon briefly
  36. printed a per-platform start command during setup, so keep it parseable.
  37. """
  38. parser.add_argument("--platform", dest="platform", help=argparse.SUPPRESS)
  39. def _add_system_flag(parser: argparse.ArgumentParser) -> None:
  40. _flag(parser, "--system", help="Target the Linux system-level gateway service")
  41. def build_gateway_parser(
  42. subparsers, *, cmd_gateway: Callable, cmd_proxy: Callable, cmd_gateway_enroll: Callable
  43. ) -> None:
  44. """Attach the ``gateway`` and ``proxy`` subcommands to ``subparsers``."""
  45. gateway_parser = subparsers.add_parser("gateway", help="Messaging gateway management",
  46. description="Manage the messaging gateway (Telegram, Discord, WhatsApp, Weixin, and more)")
  47. gateway_subparsers = gateway_parser.add_subparsers(
  48. dest="gateway_command", parser_class=_GatewayCommandParser)
  49. gateway_run = gateway_subparsers.add_parser(
  50. "run", help="Run gateway in foreground (recommended for WSL and Docker)"
  51. )
  52. gateway_run.add_argument(
  53. "-v",
  54. "--verbose",
  55. action="count",
  56. default=0,
  57. help="Increase stderr log verbosity (-v=INFO, -vv=DEBUG)",
  58. )
  59. gateway_run.add_argument(
  60. "-q", "--quiet", action="store_true", help="Suppress all stderr log output"
  61. )
  62. gateway_run.add_argument(
  63. "--replace",
  64. action="store_true",
  65. help="Replace any existing gateway instance (useful for systemd)",
  66. )
  67. gateway_run.add_argument(
  68. "--force",
  69. action="store_true",
  70. help=(
  71. "Start a foreground gateway even when a systemd/launchd/s6 service "
  72. "already supervises this profile. Without --force, the command "
  73. "refuses because a second dispatcher escapes the service and can "
  74. "corrupt shared gateway state."
  75. ),
  76. )
  77. gateway_run.add_argument(
  78. "--no-supervise",
  79. action="store_true",
  80. help=(
  81. "Inside the s6-overlay Docker image, normally `gateway run` is "
  82. "automatically redirected to the supervised s6 service (so the "
  83. "gateway gets auto-restart on crash, plus a supervised dashboard "
  84. "if HERMES_DASHBOARD is set). Pass --no-supervise to opt out and "
  85. "get the historical pre-s6 foreground behavior: the gateway is "
  86. "the container's main process and the container exits with the "
  87. "gateway's exit code. No effect outside an s6 container."),
  88. )
  89. _flag(gateway_run, "--external-supervisor",
  90. help="Declare that an external process manager owns this foreground "
  91. "gateway. In-chat restarts and updates exit back to that manager "
  92. "instead of spawning a detached replacement. Use this when a "
  93. "launchd/systemd wrapper strips its native environment markers.")
  94. # Internal: set only by a client that auto-starts its own gateway (chat, TUI, cron/kanban
  95. # clients). Never in service units, Desktop's `gateway ensure` start or a hand-run gateway.
  96. _flag(gateway_run, "--idle-exit", help=argparse.SUPPRESS)
  97. add_accept_hooks_flag(gateway_run)
  98. add_accept_hooks_flag(gateway_parser)
  99. from hermes_cli.gateway_runtime_cli import cmd_gateway_ensure
  100. gateway_ensure = gateway_subparsers.add_parser(
  101. "ensure", ensure_json=True,
  102. help="Ensure a local runtime without installing or replacing a service",
  103. epilog="Exit codes: 0 ready; 2 invalid invocation; 3 incompatible; "
  104. "4 authorization/profile mismatch; 5 deadline; 6 draining/update-paused; "
  105. "7 inaccessible/conflicting supervisor. Pending startup is not readiness.")
  106. _flag(gateway_ensure, "--json", help="Emit one credential-free JSON result (default)")
  107. gateway_ensure.add_argument("--timeout", default="60",
  108. help="Total startup deadline in seconds (default: 60)")
  109. gateway_ensure.set_defaults(func=cmd_gateway_ensure)
  110. gateway_start = gateway_subparsers.add_parser(
  111. "start", help="Start the installed systemd/launchd background service")
  112. _add_system_flag(gateway_start)
  113. _flag(gateway_start, "--all",
  114. help="Kill ALL stale gateway processes across all profiles before starting")
  115. _flag(gateway_start, "--force", help=_FORCE_SERVED_PROFILE_HELP)
  116. _add_compat_platform_flag(gateway_start)
  117. gateway_stop = gateway_subparsers.add_parser("stop", help="Stop gateway service")
  118. _add_system_flag(gateway_stop)
  119. _flag(gateway_stop, "--all", help="Stop ALL gateway processes across all profiles")
  120. _flag(gateway_stop, "-y", "--yes", "--interrupt", dest="interrupt", help=_INTERRUPT_HELP.format(verb="stop"))
  121. gateway_restart = gateway_subparsers.add_parser("restart", help="Restart gateway service")
  122. _add_system_flag(gateway_restart)
  123. _flag(gateway_restart, "--all",
  124. help="Kill ALL gateway processes across all profiles before restarting")
  125. _flag(gateway_restart, "--force", help=_FORCE_SERVED_PROFILE_HELP)
  126. _flag(gateway_restart, "-y", "--yes", "--interrupt", dest="interrupt", help=_INTERRUPT_HELP.format(verb="restart"))
  127. _flag(gateway_restart, "--detach", help=(
  128. "Without an installed service, start the replacement in the background (as `gateway ensure` "
  129. "does) instead of in this terminal; used by apps that run the restart as a short-lived client"))
  130. _add_compat_platform_flag(gateway_restart)
  131. gateway_status = gateway_subparsers.add_parser("status", help="Show gateway status")
  132. _flag(gateway_status, "--deep", help="Deep status check")
  133. _flag(gateway_status, "-l", "--full",
  134. help="Show full, untruncated service/log output where supported")
  135. _add_system_flag(gateway_status)
  136. _add_compat_platform_flag(gateway_status)
  137. # gateway install
  138. gateway_install = gateway_subparsers.add_parser(
  139. "install", help="Install gateway as a systemd/launchd background service")
  140. _flag(gateway_install, "--force",
  141. help="Force reinstall, and install even when the default multiplexer already serves this profile")
  142. _flag(gateway_install, "--system",
  143. help="Install as a Linux system-level service (starts at boot)")
  144. gateway_install.add_argument("--run-as-user", dest="run_as_user",
  145. help="User account the Linux system service should run as")
  146. _flag(gateway_install, "--start-now", dest="start_now", default=None,
  147. help="Start the gateway service immediately after installing")
  148. gateway_install.add_argument("--no-start-now", dest="start_now", action="store_false",
  149. help="Do not start the gateway service after installing")
  150. _flag(gateway_install, "--start-on-login", dest="start_on_login", default=None,
  151. help="Enable the service to start automatically on login/boot")
  152. gateway_install.add_argument("--no-start-on-login", dest="start_on_login", action="store_false",
  153. help="Do not enable the service to start on login/boot")
  154. _flag(gateway_install, "--if-missing", dest="if_missing",
  155. help="Do nothing when a gateway service is already installed")
  156. _flag(gateway_install, "--force-unit-path", dest="force_unit_path",
  157. help="Repoint a service definition that pins another HERMES_HOME at this one")
  158. _flag(gateway_install, "--elevated-handoff", dest="elevated_handoff", help=argparse.SUPPRESS)
  159. gateway_uninstall = gateway_subparsers.add_parser("uninstall", help="Uninstall gateway service")
  160. _add_system_flag(gateway_uninstall)
  161. gateway_subparsers.add_parser("list", help="List all profiles and their gateway status")
  162. gateway_subparsers.add_parser("setup", help="Configure messaging platforms")
  163. gateway_migrate_legacy = gateway_subparsers.add_parser(
  164. "migrate-legacy", help="Remove legacy hermes.service units from pre-rename installs",
  165. description="Stop, disable, and remove legacy Hermes gateway unit files "
  166. "(e.g. hermes.service) left over from older installs. Profile "
  167. "units (hermes-gateway-<profile>.service) and unrelated "
  168. "third-party services are never touched.")
  169. _flag(gateway_migrate_legacy, "--dry-run", dest="dry_run",
  170. help="List what would be removed without doing it")
  171. _flag(gateway_migrate_legacy, "-y", "--yes", dest="yes", help="Skip the confirmation prompt")
  172. gateway_migrate = gateway_subparsers.add_parser(
  173. "migrate", help="Converge every per-profile gateway onto the ONE host gateway",
  174. description="Converge this host onto the one-gateway-per-host model: stop and uninstall "
  175. "each secondary profile's gateway and its supervisor unit (systemd, launchd, Windows "
  176. "Scheduled Task), then restart the default profile's gateway so it serves every "
  177. "profile. Runs a preflight first (duplicate bot tokens, port-binding platforms "
  178. "without a /p/<profile>/ ingress) and changes nothing when blocked. Safe to re-run: a "
  179. "half-migrated host converges on the next run. Per-profile gateways are not a "
  180. "supported topology any more, so there is no rollback command.")
  181. _flag(gateway_migrate, "--multiplex", dest="multiplex", help="Converge onto the one host gateway (default)")
  182. _flag(gateway_migrate, "--dry-run", dest="dry_run", help="Print the plan and blockers without changing anything")
  183. _flag(gateway_migrate, "-y", "--yes", dest="yes", help="Apply without confirmation")
  184. # enroll: redeem a single-use connector token for the per-gateway secret + per-tenant
  185. # delivery key, written to .env. See website/docs/developer-guide/relay-connector-contract.md. EXPERIMENTAL.
  186. gateway_enroll = gateway_subparsers.add_parser("enroll",
  187. help="Enroll this gateway with a relay connector (writes relay auth creds to .env)",
  188. description="Redeem a single-use enrollment token with a relay connector. "
  189. "Authenticates as your Nous Portal account (the connector derives the "
  190. "authoritative tenant from it), mints this gateway's per-gateway secret "
  191. "and per-tenant delivery key, and writes GATEWAY_RELAY_ID / "
  192. "GATEWAY_RELAY_SECRET / GATEWAY_RELAY_DELIVERY_KEY into ~/.hermes/.env. "
  193. "Requires being logged in (hermes setup). Not available in managed installs.")
  194. gateway_enroll.add_argument("--token", default=None,
  195. help="The single-use enrollment token from the connector (delivered with "
  196. "your gateway config). Also settable via GATEWAY_RELAY_ENROLL_TOKEN.")
  197. gateway_enroll.add_argument("--connector-url", dest="connector_url", default=None,
  198. help="The connector base/relay URL, e.g. wss://connector.example.com/relay "
  199. "or https://connector.example.com. Also settable via GATEWAY_RELAY_URL "
  200. "/ gateway.relay_url in config.yaml.")
  201. gateway_enroll.add_argument("--gateway-id", dest="gateway_id", default=None,
  202. help="A stable id for this gateway instance (kill-switch granularity). "
  203. "Defaults to gw-<hostname>.")
  204. gateway_enroll.add_argument("--wake-url", dest="wake_url", default=None,
  205. help="Phase 5 §5.2 wake URL: a reachable URL the connector pokes "
  206. "(payload-free GET) to wake this gateway when buffered work arrives "
  207. "while it's idle/suspended, so it reconnects and drains. Persisted as "
  208. "GATEWAY_RELAY_WAKE_URL in ~/.hermes/.env and forwarded at provision. "
  209. "Optional — without it the gateway still drains whenever it next "
  210. "reconnects on its own.")
  211. gateway_enroll.set_defaults(func=cmd_gateway_enroll)
  212. # proxy: local OpenAI-compatible proxy attaching the user's OAuth provider credentials,
  213. # so external apps (Open WebUI, Karakeep, ...) ride a logged-in subscription.
  214. proxy_parser = subparsers.add_parser(
  215. "proxy", help="Local OpenAI-compatible proxy to OAuth providers",
  216. description="Run a local HTTP server that forwards OpenAI-compatible requests "
  217. "to an OAuth-authenticated provider (e.g. Nous Portal). External "
  218. "apps can point at the proxy with any bearer token; the proxy "
  219. "attaches your real credentials.")
  220. proxy_subparsers = proxy_parser.add_subparsers(dest="proxy_command")
  221. proxy_start = proxy_subparsers.add_parser("start", help="Run the proxy in the foreground")
  222. proxy_start.add_argument("--provider", default="nous",
  223. help="Upstream provider: nous or xai (default: nous). See `hermes proxy providers`.")
  224. proxy_start.add_argument("--host", default=None,
  225. help="Bind address (default: 127.0.0.1). Use 0.0.0.0 to expose on LAN.")
  226. proxy_start.add_argument("--port", type=int, default=None, help="Bind port (default: 8645)")
  227. proxy_subparsers.add_parser("status", help="Show which proxy upstreams are ready")
  228. proxy_subparsers.add_parser("providers", help="List available proxy upstream providers")
  229. proxy_parser.set_defaults(func=cmd_proxy)
  230. gateway_parser.set_defaults(func=cmd_gateway)