cli.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. """``hermes photon ...`` CLI subcommands (registered via ``ctx.register_cli_command()``):
  2. setup (device login + project + user + sidecar), status, install-sidecar (npm install in
  3. the sidecar dir), telemetry [on|off]. Device login is the first step of ``setup`` (no
  4. standalone ``login`` verb); inbound is the gRPC stream, so there are no webhook subcommands.
  5. """
  6. from __future__ import annotations
  7. import argparse
  8. import getpass
  9. import os
  10. import subprocess
  11. import sys
  12. from typing import Optional
  13. from hermes_cli.colors import Colors, color
  14. from . import auth as photon_auth
  15. from .adapter import sidecar_deps_installed
  16. from hermes_constants import find_node_executable, with_hermes_node_path
  17. from .sidecar_paths import _NPM_ERROR_LOG_MAX_CHARS, _npm_error_log, _sidecar_dir
  18. import contextlib
  19. def register_cli(parser: argparse.ArgumentParser) -> None:
  20. """Wire up `hermes photon ...` subcommands."""
  21. subs = parser.add_subparsers(dest="photon_command", required=False)
  22. p_setup = subs.add_parser("setup", help="First-time setup (device login + project + user + sidecar)")
  23. p_setup.add_argument("--project-name", default=None, help="Project name (default: 'Hermes Agent')")
  24. p_setup.add_argument("--phone", default=None, help="Your E.164 phone number (e.g. +15551234567)")
  25. p_setup.add_argument("--first-name", default=None)
  26. p_setup.add_argument("--last-name", default=None)
  27. p_setup.add_argument("--email", default=None)
  28. p_setup.add_argument("--no-browser", action="store_true",
  29. help="Don't try to open a browser for device login; print the URL only")
  30. p_setup.add_argument("--skip-sidecar-install", action="store_true",
  31. help="Skip `npm install` inside the sidecar directory")
  32. subs.add_parser("status", help="Show login + project + sidecar dep state")
  33. subs.add_parser("install-sidecar", help="Run npm install inside the sidecar directory")
  34. p_telemetry = subs.add_parser("telemetry", help="Show or toggle Spectrum SDK telemetry (on/off)")
  35. p_telemetry.add_argument(
  36. "state", nargs="?", choices=("on", "off"),
  37. help="Turn telemetry on or off (omit to show the current state)")
  38. parser.set_defaults(func=dispatch)
  39. def dispatch(args: argparse.Namespace) -> int:
  40. sub = getattr(args, "photon_command", None)
  41. handler = _cmd_status if sub is None else _COMMANDS.get(sub) # no subcommand — status by default
  42. if handler is None:
  43. print(f"unknown subcommand: {sub}", file=sys.stderr)
  44. return 2
  45. return handler(args)
  46. # -- Subcommand handlers -------------------------------------------------------------
  47. def _run_device_login(args: argparse.Namespace) -> int:
  48. """Run the RFC 8628 device-code login flow and persist the token (first step of ``setup``)."""
  49. def _print_code(code):
  50. print("\n┌─ Photon device login ────────────────────────────────────────\n"
  51. f"│ Open this URL: {code.verification_uri_complete or code.verification_uri}\n"
  52. f"│ Enter the code: {code.user_code}\n"
  53. "│ (waiting for approval — Ctrl-C to cancel)\n"
  54. "└──────────────────────────────────────────────────────────────\n")
  55. try:
  56. photon_auth.login_device_flow(open_browser=not args.no_browser, on_user_code=_print_code)
  57. except Exception as e:
  58. print(f"login failed: {e}", file=sys.stderr)
  59. return 1
  60. # Never print any portion of the token (shoulder-surfing / screen recordings).
  61. print(f"✓ logged in — token saved to {photon_auth._auth_json_path()}")
  62. return 0
  63. def _setup_token(args: argparse.Namespace) -> Optional[str]:
  64. """[1/5] Reuse a valid dashboard token or run device login; None on failure."""
  65. token = photon_auth.load_photon_token()
  66. if token:
  67. # The dashboard token has a short TTL (~3-4 days); a stale one makes every management
  68. # call 401, so validate upfront and fall back to a fresh login.
  69. print("[1/5] Checking existing Photon token...")
  70. if photon_auth.check_photon_token_valid(token):
  71. print(" ✓ token is valid")
  72. print("[1/5] Reusing existing Photon token")
  73. return token
  74. print(" ✗ token is stale (dashboard rejected it) — re-authenticating")
  75. photon_auth.clear_photon_token()
  76. print("[1/5] No valid Photon token found — running device login...")
  77. if _run_device_login(args) != 0:
  78. return None
  79. token = photon_auth.load_photon_token()
  80. if not token:
  81. print("login completed but token was not stored", file=sys.stderr)
  82. return token
  83. def _setup_project(token: str, name: str) -> Optional[str]:
  84. """[2/5] Find or create the project; returns its id or None on failure."""
  85. dashboard_id = photon_auth.load_dashboard_project_id()
  86. try:
  87. if dashboard_id:
  88. print("[2/5] Reusing configured Photon project")
  89. elif (existing := photon_auth.find_project_by_name(token, name)) and existing.get("id"):
  90. dashboard_id = existing["id"]
  91. print(f"[2/5] Found existing project '{name}'")
  92. else:
  93. print(f"[2/5] Creating Photon project '{name}'...")
  94. dashboard_id = photon_auth.create_project(token, name=name).get("id")
  95. print(" ✓ project created")
  96. except Exception as e:
  97. print(f"project setup failed: {e}", file=sys.stderr)
  98. return None
  99. if not dashboard_id:
  100. print("could not resolve a Photon project id", file=sys.stderr)
  101. return None
  102. return dashboard_id
  103. def _setup_credentials(token: str, dashboard_id: str, name: str) -> Optional[str]:
  104. """[3/5] Provision Spectrum credentials (runtime -> .env, ids -> auth.json); the dashboard
  105. id *is* the Spectrum id. A valid existing secret is reused: regenerating breaks a running
  106. sidecar's sends until restart. Returns the secret or None."""
  107. try:
  108. # 3. Spectrum is always enabled and provisioned at create-time, and the dashboard project id *is*
  109. # the Spectrum project id (ids unified), so there's nothing to enable — the id we already have is
  110. # the Spectrum id. Regenerating invalidates the credential that a running sidecar holds in its
  111. # process env, causing all outbound sends to fail with AuthenticationError until the gateway is
  112. # restarted (GH #50755).
  113. print("[3/5] Provisioning Spectrum credentials...")
  114. existing_id, existing_secret = photon_auth.load_project_credentials()
  115. secret: str = ""
  116. if existing_id and existing_secret:
  117. with contextlib.suppress(Exception): # failure => fall through to regeneration
  118. photon_auth.list_users(existing_id, existing_secret) # lightweight validation
  119. secret = existing_secret
  120. reused = bool(secret)
  121. if not secret:
  122. secret = photon_auth.regenerate_project_secret(token, dashboard_id)
  123. photon_auth.store_project_credentials(
  124. spectrum_project_id=dashboard_id, project_secret=secret, dashboard_project_id=dashboard_id, name=name)
  125. if reused:
  126. print(f" ✓ Spectrum ready (project id {dashboard_id}) — existing credentials valid")
  127. else:
  128. print(f" ✓ Spectrum ready (project id {dashboard_id}) — new secret saved")
  129. print(" ⚠ Project secret was regenerated. If the gateway is running, "
  130. "restart it so the sidecar picks up the new secret:\n"
  131. " hermes gateway restart")
  132. except Exception as e:
  133. print(f"spectrum provisioning failed: {e}", file=sys.stderr)
  134. return None
  135. return secret
  136. def _cmd_setup(args: argparse.Namespace) -> int:
  137. name = args.project_name or photon_auth.DEFAULT_PROJECT_NAME
  138. token = _setup_token(args)
  139. dashboard_id = token and _setup_project(token, name)
  140. secret = dashboard_id and _setup_credentials(token, dashboard_id, name)
  141. if not secret:
  142. return 1
  143. # 4. Register the operator's phone number as a Spectrum user (idempotent).
  144. phone = args.phone or _prompt(color("[4/5] Your iMessage phone number (E.164, e.g. +15551234567): ", Colors.CYAN))
  145. agent_number = registered_phone = registered_user_id = None
  146. routing_live = False # only an opted-in, registered number makes setup "complete"
  147. if not phone:
  148. print(" Skipped user registration (no phone given). Re-run with --phone later.")
  149. else:
  150. try: # name/email are optional and never prompted for (--first-name / --email)
  151. user, created = photon_auth.register_user_if_absent(
  152. dashboard_id, secret, phone_number=phone, first_name=args.first_name,
  153. last_name=args.last_name, email=args.email)
  154. except ValueError as e:
  155. print(f" invalid phone number: {e}", file=sys.stderr)
  156. return 1
  157. except Exception as e:
  158. print(f" user registration failed: {e}", file=sys.stderr)
  159. return 1
  160. print(" ✓ phone registered" if created else " ✓ phone already registered")
  161. registered_phone = phone
  162. registered_user_id = user.get("id")
  163. # The number to text the agent is the user's assigned line ("TEXTS ON"); shared-number
  164. # plans have no dedicated /lines entry.
  165. agent_number = photon_auth.user_assigned_line(user) or _lookup_imessage_line(token, dashboard_id)
  166. # Opt-in gate: Photon only routes a number whose user row carries meta.opt_in, which the
  167. # service sets once the human texts the assigned line from their phone (the API cannot
  168. # set it). Name the line and wait for the opt-in; a re-run on an opted-in row passes.
  169. if photon_auth.user_opted_in(user):
  170. routing_live = True
  171. print(" ✓ number is opted in — routing is live")
  172. elif not agent_number: # nothing to text yet, so a wait could never end in an opt-in
  173. routing_live = False
  174. print(f" ⚠ No iMessage line is assigned to {phone} yet — skipping the opt-in wait.\n"
  175. f" Once the Photon dashboard shows your line, text it once from {phone},\n"
  176. " then check with `hermes photon status`.")
  177. else:
  178. opted = _wait_for_opt_in(dashboard_id, secret, phone, agent_number)
  179. routing_live = opted is not None
  180. agent_number = photon_auth.user_assigned_line(opted) or agent_number
  181. # Otherwise the gateway denies the operator's own inbound and has no cron home space.
  182. _autoconfigure_access(phone)
  183. # 5. Surface the agent's iMessage number.
  184. if not agent_number and not phone: # the phone path already looked the line up
  185. agent_number = _lookup_imessage_line(token, dashboard_id)
  186. if agent_number:
  187. print("\n" + "\n".join((
  188. color("┌─ Your agent's iMessage number ───────────────────────────────", Colors.GREEN),
  189. color("│ 📱 ", Colors.GREEN) + color(str(agent_number), Colors.GREEN, Colors.BOLD),
  190. color("│ Text this number from your phone to talk to your agent.", Colors.GREEN),
  191. color("└──────────────────────────────────────────────────────────────", Colors.GREEN))))
  192. else:
  193. print(" No iMessage line assigned yet — check the Photon dashboard.")
  194. if registered_phone:
  195. try:
  196. photon_auth.store_user_numbers(
  197. phone_number=registered_phone, assigned_phone_number=agent_number,
  198. user_id=str(registered_user_id) if registered_user_id else None, dashboard_project_id=dashboard_id)
  199. except Exception as e:
  200. print(f" (could not save Photon status metadata: {e})", file=sys.stderr)
  201. # 6. Sidecar deps (spectrum-ts).
  202. if args.skip_sidecar_install:
  203. print("[5/5] Skipping sidecar npm install (--skip-sidecar-install)")
  204. else:
  205. print("[5/5] Installing Node sidecar deps (spectrum-ts)...")
  206. rc = _install_sidecar()
  207. if rc != 0:
  208. return rc
  209. # 7. Enable the platform in config.yaml, or the channel silently stays offline.
  210. try:
  211. from hermes_cli.config import write_platform_config_field
  212. write_platform_config_field("photon", "enabled", True, raw=True)
  213. print(" ✓ photon platform enabled in config.yaml")
  214. except Exception as e:
  215. print(f" (could not enable Photon in config: {e})", file=sys.stderr)
  216. if not phone: # saved, but nothing can route until a number is registered and opted in
  217. print("\n⚠ Photon setup saved, but iMessage routing is NOT live: no phone number is registered.\n"
  218. " Finish with: hermes photon setup --phone +15551234567")
  219. return 0
  220. if not routing_live: # saved, but not "complete": the gateway cannot reach this number yet
  221. print(f"\n⚠ Photon setup saved, but iMessage routing is NOT live: text {agent_number or 'your assigned line'} "
  222. f"once from {phone}.\n Check with `hermes photon status`; start the gateway once it shows opted in.")
  223. return 0
  224. print("\n✓ Photon setup complete.\n Start the gateway: hermes gateway start")
  225. return 0
  226. def _lookup_imessage_line(token: str, dashboard_id: str) -> Optional[str]:
  227. """The project's dedicated iMessage line (fallback when the user row names none)."""
  228. try:
  229. line = photon_auth.get_imessage_line(token, dashboard_id)
  230. except (photon_auth.httpx.HTTPError, RuntimeError, ValueError, AttributeError, TypeError) as e: # transport / status / bad or misshapen JSON
  231. print(f" (could not fetch the assigned line: {e})", file=sys.stderr)
  232. return None
  233. return line.get("phoneNumber") if line else None
  234. _OPT_IN_WAIT_S = 300
  235. def _wait_for_opt_in(dashboard_id: str, secret: str, phone: str, agent_number: Optional[str]) -> Optional[dict]:
  236. """Print the opt-in step and, on a TTY, wait (bounded) for it to land. Returns the
  237. opted-in user row, or None when skipped, timed out or interrupted."""
  238. line_hint = agent_number or "the line Photon assigns to your number"
  239. print("\n" + color(" One manual step: opt in by texting your agent", Colors.CYAN, Colors.BOLD))
  240. print(" Your number only enters iMessage routing after it has messaged the line\n"
  241. f" Photon assigned to it:\n 1. Open Messages on {phone}.\n"
  242. f" 2. Text {line_hint} — one message of any content is enough.")
  243. if not sys.stdin.isatty(): # scripted setup / CI: nobody can answer the poll
  244. print(" Non-interactive run — skipping the opt-in wait. Verify later with `hermes photon status`.")
  245. return None
  246. print(f" Setup waits here (up to {_OPT_IN_WAIT_S // 60} minutes) and continues once the opt-in lands.\n"
  247. " (Ctrl-C to skip — re-running setup resumes where it left off.)")
  248. def _on_waiting(attempt: int) -> None:
  249. if attempt % 6 == 0:
  250. print(" ... still waiting for your message to land")
  251. try:
  252. opted = photon_auth.wait_for_opted_in_user(
  253. dashboard_id, secret, phone, timeout_s=_OPT_IN_WAIT_S, on_waiting=_on_waiting)
  254. why = f"No opt-in seen within {_OPT_IN_WAIT_S // 60} minutes."
  255. except KeyboardInterrupt:
  256. opted, why = None, "Wait skipped (Ctrl-C)."
  257. print()
  258. if opted is None:
  259. print(f" ⚠ {why}\n {phone} is not opted in yet: text {line_hint} once from it, then re-run\n"
  260. " `hermes photon setup` (it resumes where it left off).")
  261. return None
  262. print(" ✓ opt-in landed — routing is live")
  263. return opted
  264. def _autoconfigure_access(phone: str) -> None:
  265. """Set PHOTON_ALLOWED_USERS and PHOTON_HOME_CHANNEL to the operator's number, each only
  266. when unset so a hand-tuned value is never clobbered on re-run."""
  267. try:
  268. from hermes_cli.config import get_env_value, save_env_value
  269. except ImportError:
  270. return
  271. for key, label in (("PHOTON_ALLOWED_USERS", "allowlisted your number"),
  272. ("PHOTON_HOME_CHANNEL", "set your DM as the cron home channel")):
  273. try:
  274. if get_env_value(key):
  275. print(f" {key} already set — leaving it as-is.")
  276. continue
  277. save_env_value(key, phone)
  278. print(f" ✓ {label} ({key})")
  279. except Exception as e:
  280. print(f" could not set {key}: {e}", file=sys.stderr)
  281. def _cmd_status(_args: argparse.Namespace) -> int:
  282. phone, assigned = photon_auth.load_user_numbers()
  283. if not (phone and assigned):
  284. spectrum_id, project_secret = photon_auth.load_project_credentials()
  285. if spectrum_id and project_secret:
  286. try:
  287. photon_auth.refresh_user_numbers(spectrum_id, project_secret)
  288. except Exception as e:
  289. print(f" (could not refresh Photon user numbers: {e})", file=sys.stderr)
  290. # auth.print_credential_summary's emit callback is the only sink that sees
  291. # credential-derived strings (keeps cli.py taint-free for CodeQL).
  292. photon_auth.print_credential_summary(print)
  293. node_bin = find_node_executable("node")
  294. print(f" node binary : {node_bin or '✗ missing (install Node 18+)'}")
  295. print(f" sidecar deps : {'✓ installed' if sidecar_deps_installed() else '✗ run `hermes photon install-sidecar`'}")
  296. print(f" telemetry : {'on' if _telemetry_enabled() else 'off'} (`hermes photon telemetry on|off`)")
  297. photon_auth.print_routing_status(print)
  298. return 0
  299. def _telemetry_enabled() -> bool:
  300. """PHOTON_TELEMETRY from env / ~/.hermes/.env; truthy set mirrors the sidecar's."""
  301. try:
  302. from hermes_cli.config import get_env_value
  303. raw = get_env_value("PHOTON_TELEMETRY")
  304. except ImportError:
  305. raw = os.getenv("PHOTON_TELEMETRY")
  306. return (raw or "").strip().lower() in ("1", "true", "yes", "on")
  307. def _cmd_telemetry(args: argparse.Namespace) -> int:
  308. state = getattr(args, "state", None)
  309. if state is None:
  310. print(f"Photon telemetry: {'on' if _telemetry_enabled() else 'off'}")
  311. print(" Toggle with `hermes photon telemetry on` / `hermes photon telemetry off`.")
  312. return 0
  313. try:
  314. from hermes_cli.config import save_env_value
  315. save_env_value("PHOTON_TELEMETRY", "true" if state == "on" else "false")
  316. except Exception as e:
  317. print(f"could not save PHOTON_TELEMETRY: {e}", file=sys.stderr)
  318. return 1
  319. print(f"✓ Spectrum telemetry turned {state} (PHOTON_TELEMETRY in ~/.hermes/.env)")
  320. print(" Restart the gateway for the sidecar to pick it up: hermes gateway restart")
  321. return 0
  322. def _install_sidecar() -> int:
  323. import pm
  324. try:
  325. npm = find_node_executable("npm")
  326. env = with_hermes_node_path()
  327. if npm is None:
  328. env = pm.ensure("npm", explicit=True).env
  329. installed = pm.installed_package("npm")
  330. if installed is None or installed.binary is None:
  331. raise pm.InstallError("npm", "ensured but no selected binary was recorded")
  332. npm = str(installed.binary)
  333. except pm.InstallError as exc:
  334. print(f"Could not prepare Photon dependencies: {exc}", file=sys.stderr)
  335. return 1
  336. # spectrum-ts is pinned exactly (the SDK ships breaking majors); upgrades are deliberate —
  337. # never `@latest` (see README "Upgrading spectrum-ts"). `npm ci` installs the lockfile
  338. # verbatim; `npm install` is the fallback for a missing/drifted lockfile.
  339. print(f" $ cd {_sidecar_dir()} && {npm} ci")
  340. def _run(verb: str) -> subprocess.CompletedProcess:
  341. # stdout streams to the terminal; stderr is captured so the failure reason can be
  342. # persisted for check_requirements() to surface later.
  343. proc = subprocess.run(
  344. [npm, verb], stdin=subprocess.DEVNULL, cwd=str(_sidecar_dir()), check=False, stderr=subprocess.PIPE, text=True, env=env)
  345. if proc.stderr:
  346. print(proc.stderr, end="", file=sys.stderr)
  347. return proc
  348. proc = _run("ci")
  349. if proc.returncode != 0:
  350. print(f" npm ci failed — falling back to: {npm} install")
  351. proc = _run("install")
  352. error = (proc.stderr or "").strip()[:_NPM_ERROR_LOG_MAX_CHARS] # bounded to what check_requirements surfaces
  353. if proc.returncode != 0:
  354. print("npm install failed", file=sys.stderr)
  355. with contextlib.suppress(OSError):
  356. if proc.returncode == 0:
  357. _npm_error_log().unlink()
  358. elif error:
  359. _npm_error_log().write_text(error, encoding="utf-8")
  360. return proc.returncode
  361. _COMMANDS = {
  362. "setup": _cmd_setup, "status": _cmd_status, "install-sidecar": lambda _args: _install_sidecar(),
  363. "telemetry": _cmd_telemetry}
  364. def gateway_setup() -> None:
  365. """Run Photon first-time setup from the unified `hermes gateway setup` wizard (same flow
  366. as ``hermes photon setup``; phone is prompted when stdin is a TTY)."""
  367. _cmd_setup(argparse.Namespace(
  368. photon_command="setup", project_name=None, phone=None, first_name=None, last_name=None,
  369. email=None, no_browser=False, skip_sidecar_install=False))
  370. def _prompt(prompt: str, *, secret: bool = False) -> str:
  371. if not sys.stdin.isatty():
  372. return ""
  373. try:
  374. return (getpass.getpass(prompt) if secret else input(prompt)).strip()
  375. except (KeyboardInterrupt, EOFError):
  376. print()
  377. return ""