Skip to content

The agent that grows with you

refactor(photon): cli.py 400->361, sidecar_paths.py 122->100; fold banner prints, collapse branches, compact module docs

Tekniumb4fbfbed83cc
diff --git a/plugins/platforms/photon/cli.py b/plugins/platforms/photon/cli.py
index 4ed01fa619a..2843b02816f 100644
--- a/plugins/platforms/photon/cli.py
+++ b/plugins/platforms/photon/cli.py
@@ -1,12 +1,7 @@
"""``hermes photon ...`` CLI subcommands (registered via ``ctx.register_cli_command()``):
-
- setup full first-time setup (device login + project + user + sidecar)
- status show login + project + sidecar dep state
- install-sidecar npm install inside plugins/platforms/photon/sidecar/
- telemetry show or toggle Spectrum SDK telemetry (on/off)
-
-Device login is the first step of ``setup`` (no standalone ``login`` verb); inbound is
-the spectrum-ts gRPC stream, so there are no webhook subcommands.
+setup (device login + project + user + sidecar), status, install-sidecar (npm install in
+the sidecar dir), telemetry [on|off]. Device login is the first step of ``setup`` (no
+standalone ``login`` verb); inbound is the gRPC stream, so there are no webhook subcommands.
"""
from __future__ import annotations
@@ -26,9 +21,6 @@ from .sidecar_paths import _NPM_ERROR_LOG_MAX_CHARS, _npm_error_log, _sidecar_di
import contextlib
-# ---------------------------------------------------------------------------
-# argparse wiring
-
def register_cli(parser: argparse.ArgumentParser) -> None:
"""Wire up `hermes photon ...` subcommands."""
subs = parser.add_subparsers(dest="photon_command", required=False)
@@ -51,9 +43,6 @@ def register_cli(parser: argparse.ArgumentParser) -> None:
parser.set_defaults(func=dispatch)
-# ---------------------------------------------------------------------------
-# Dispatch
-
def dispatch(args: argparse.Namespace) -> int:
sub = getattr(args, "photon_command", None)
if sub is None:
@@ -65,20 +54,16 @@ def dispatch(args: argparse.Namespace) -> int:
return handler(args)
-# ---------------------------------------------------------------------------
-# Subcommand handlers
+# -- Subcommand handlers -------------------------------------------------------------
def _run_device_login(args: argparse.Namespace) -> int:
"""Run the RFC 8628 device-code login flow and persist the token (first step of ``setup``)."""
def _print_code(code):
- target = code.verification_uri_complete or code.verification_uri
- print()
- print("┌─ Photon device login ────────────────────────────────────────")
- print(f"│ Open this URL: {target}")
- print(f"│ Enter the code: {code.user_code}")
- print("│ (waiting for approval — Ctrl-C to cancel)")
- print("└──────────────────────────────────────────────────────────────")
- print()
+ print("\n┌─ Photon device login ────────────────────────────────────────\n"
+ f"│ Open this URL: {code.verification_uri_complete or code.verification_uri}\n"
+ f"│ Enter the code: {code.user_code}\n"
+ "│ (waiting for approval — Ctrl-C to cancel)\n"
+ "└──────────────────────────────────────────────────────────────\n")
try:
photon_auth.login_device_flow(open_browser=not args.no_browser, on_user_code=_print_code)
except Exception as e:
@@ -93,8 +78,8 @@ def _setup_token(args: argparse.Namespace) -> Optional[str]:
"""[1/5] Reuse a valid dashboard token or run device login; None on failure."""
token = photon_auth.load_photon_token()
if token:
- # The dashboard token has a short TTL (~3-4 days); a stale one makes every
- # management call 401, so validate upfront and fall back to a fresh login.
+ # The dashboard token has a short TTL (~3-4 days); a stale one makes every management
+ # call 401, so validate upfront and fall back to a fresh login.
print("[1/5] Checking existing Photon token...")
if photon_auth.check_photon_token_valid(token):
print(" ✓ token is valid")
@@ -141,34 +126,29 @@ def _setup_project(token: str, name: str) -> Optional[str]:
def _setup_credentials(token: str, dashboard_id: str, name: str) -> Optional[str]:
- """[3/5] Provision Spectrum credentials (runtime -> .env, ids -> auth.json); the
- dashboard id *is* the Spectrum id. A valid existing secret is reused: regenerating
- breaks a running sidecar's sends until restart. Returns the secret or None."""
+ """[3/5] Provision Spectrum credentials (runtime -> .env, ids -> auth.json); the dashboard
+ id *is* the Spectrum id. A valid existing secret is reused: regenerating breaks a running
+ sidecar's sends until restart. Returns the secret or None."""
try:
print("[3/5] Provisioning Spectrum credentials...")
existing_id, existing_secret = photon_auth.load_project_credentials()
secret: str = ""
- reused = False
if existing_id and existing_secret:
- try:
+ with contextlib.suppress(Exception): # failure => fall through to regeneration
photon_auth.list_users(existing_id, existing_secret) # lightweight validation
secret = existing_secret
- reused = True
- except Exception:
- secret = "" # fall through to regeneration
+ reused = bool(secret)
if not secret:
secret = photon_auth.regenerate_project_secret(token, dashboard_id)
photon_auth.store_project_credentials(
- spectrum_project_id=dashboard_id, project_secret=secret, dashboard_project_id=dashboard_id, name=name,
- )
+ spectrum_project_id=dashboard_id, project_secret=secret, dashboard_project_id=dashboard_id, name=name)
if reused:
print(f" ✓ Spectrum ready (project id {dashboard_id}) — existing credentials valid")
else:
print(f" ✓ Spectrum ready (project id {dashboard_id}) — new secret saved")
- print(
- " ⚠ Project secret was regenerated. If the gateway is running, "
- "restart it so the sidecar picks up the new secret:\n"
- " hermes gateway restart")
+ print(" ⚠ Project secret was regenerated. If the gateway is running, "
+ "restart it so the sidecar picks up the new secret:\n"
+ " hermes gateway restart")
except Exception as e:
print(f"spectrum provisioning failed: {e}", file=sys.stderr)
return None
@@ -187,14 +167,12 @@ def _cmd_setup(args: argparse.Namespace) -> int:
if not secret:
return 1
# 4. Register the operator's phone number as a Spectrum user (idempotent).
- phone = args.phone or _prompt(
- color("[4/5] Your iMessage phone number (E.164, e.g. +15551234567): ", Colors.CYAN))
+ phone = args.phone or _prompt(color("[4/5] Your iMessage phone number (E.164, e.g. +15551234567): ", Colors.CYAN))
agent_number = registered_phone = registered_user_id = None
if not phone:
print(" Skipped user registration (no phone given). Re-run with --phone later.")
else:
- # Name/email are optional and never prompted for (--first-name / --email).
- try:
+ try: # name/email are optional and never prompted for (--first-name / --email)
user, created = photon_auth.register_user_if_absent(
dashboard_id, secret, phone_number=phone, first_name=args.first_name,
last_name=args.last_name, email=args.email)
@@ -207,11 +185,10 @@ def _cmd_setup(args: argparse.Namespace) -> int:
print(" ✓ phone registered" if created else " ✓ phone already registered")
registered_phone = phone
registered_user_id = user.get("id")
- # The number to text the agent is the user's assigned line ("TEXTS ON");
- # shared-number plans have no dedicated /lines entry.
+ # The number to text the agent is the user's assigned line ("TEXTS ON"); shared-number
+ # plans have no dedicated /lines entry.
agent_number = photon_auth.user_assigned_line(user)
- # Otherwise the gateway denies the operator's own inbound ("Unauthorized user")
- # and has no default space for cron delivery.
+ # Otherwise the gateway denies the operator's own inbound and has no cron home space.
_autoconfigure_access(phone)
# 5. Surface the agent's iMessage number.
if not agent_number:
@@ -233,8 +210,7 @@ def _cmd_setup(args: argparse.Namespace) -> int:
try:
photon_auth.store_user_numbers(
phone_number=registered_phone, assigned_phone_number=agent_number,
- user_id=str(registered_user_id) if registered_user_id else None, dashboard_project_id=dashboard_id,
- )
+ user_id=str(registered_user_id) if registered_user_id else None, dashboard_project_id=dashboard_id)
except Exception as e:
print(f" (could not save Photon status metadata: {e})", file=sys.stderr)
# 6. Sidecar deps (spectrum-ts).
@@ -252,22 +228,19 @@ def _cmd_setup(args: argparse.Namespace) -> int:
print(" ✓ photon platform enabled in config.yaml")
except Exception as e:
print(f" (could not enable Photon in config: {e})", file=sys.stderr)
- print()
- print("✓ Photon setup complete.")
- print(" Start the gateway: hermes gateway start")
+ print("\n✓ Photon setup complete.\n Start the gateway: hermes gateway start")
return 0
def _autoconfigure_access(phone: str) -> None:
- """Set PHOTON_ALLOWED_USERS and PHOTON_HOME_CHANNEL to the operator's number,
- each only when unset so a hand-tuned value is never clobbered on re-run."""
+ """Set PHOTON_ALLOWED_USERS and PHOTON_HOME_CHANNEL to the operator's number, each only
+ when unset so a hand-tuned value is never clobbered on re-run."""
try:
from hermes_cli.config import get_env_value, save_env_value
except ImportError:
return
- for key, label in (
- ("PHOTON_ALLOWED_USERS", "allowlisted your number"),
- ("PHOTON_HOME_CHANNEL", "set your DM as the cron home channel")):
+ for key, label in (("PHOTON_ALLOWED_USERS", "allowlisted your number"),
+ ("PHOTON_HOME_CHANNEL", "set your DM as the cron home channel")):
try:
if get_env_value(key):
print(f" {key} already set — leaving it as-is.")
@@ -284,9 +257,8 @@ def _cmd_status(_args: argparse.Namespace) -> int:
# credential-derived strings (keeps cli.py taint-free for CodeQL).
photon_auth.print_credential_summary(print)
node_bin = os.getenv("PHOTON_NODE_BIN") or shutil.which("node")
- sidecar_installed = sidecar_deps_installed()
print(f" node binary : {node_bin or '✗ missing (install Node 18+)'}")
- print(f" sidecar deps : {'✓ installed' if sidecar_installed else '✗ run `hermes photon install-sidecar`'}")
+ print(f" sidecar deps : {'✓ installed' if sidecar_deps_installed() else '✗ run `hermes photon install-sidecar`'}")
print(f" telemetry : {'on' if _telemetry_enabled() else 'off'} (`hermes photon telemetry on|off`)")
return 0
@@ -336,15 +308,14 @@ def _install_sidecar() -> int:
if not shutil.which(npm):
print("npm is not on PATH. Install Node.js 18+ (https://nodejs.org/) and re-run.", file=sys.stderr)
return 1
- # spectrum-ts is pinned exactly (the SDK ships breaking majors); upgrades are
- # deliberate — never `@latest` (see README "Upgrading spectrum-ts"). `npm ci`
- # installs the lockfile verbatim; `npm install` is the fallback for a
- # missing/drifted lockfile.
+ # spectrum-ts is pinned exactly (the SDK ships breaking majors); upgrades are deliberate —
+ # never `@latest` (see README "Upgrading spectrum-ts"). `npm ci` installs the lockfile
+ # verbatim; `npm install` is the fallback for a missing/drifted lockfile.
print(f" $ cd {_sidecar_dir()} && {npm} ci")
def _run(verb: str) -> subprocess.CompletedProcess:
- # stdout streams to the terminal; stderr is captured so the failure reason
- # can be persisted for check_requirements() to surface later.
+ # stdout streams to the terminal; stderr is captured so the failure reason can be
+ # persisted for check_requirements() to surface later.
proc = subprocess.run( # noqa: S603
[npm, verb], cwd=str(_sidecar_dir()), check=False, stderr=subprocess.PIPE, text=True)
if proc.stderr:
@@ -356,8 +327,7 @@ def _install_sidecar() -> int:
proc = _run("install")
if proc.returncode != 0:
print("npm install failed", file=sys.stderr)
- # Bounded to what check_requirements() will ever surface.
- error = (proc.stderr or "").strip()[:_NPM_ERROR_LOG_MAX_CHARS]
+ error = (proc.stderr or "").strip()[:_NPM_ERROR_LOG_MAX_CHARS] # bounded to what check_requirements surfaces
if error:
with contextlib.suppress(OSError):
_npm_error_log().write_text(error, encoding="utf-8")
@@ -368,33 +338,24 @@ def _install_sidecar() -> int:
_COMMANDS = {
- "setup": _cmd_setup,
- "status": _cmd_status,
- "install-sidecar": lambda _args: _install_sidecar(),
- "telemetry": _cmd_telemetry}
+ "setup": _cmd_setup, "status": _cmd_status, "install-sidecar": lambda _args: _install_sidecar(),
+ "telemetry": _cmd_telemetry,
+}
-# ---------------------------------------------------------------------------
-# Gateway-setup entry point
-
def gateway_setup() -> None:
- """Run Photon first-time setup from the unified `hermes gateway setup` wizard
- (same flow as ``hermes photon setup``; phone is prompted when stdin is a TTY)."""
+ """Run Photon first-time setup from the unified `hermes gateway setup` wizard (same flow
+ as ``hermes photon setup``; phone is prompted when stdin is a TTY)."""
_cmd_setup(argparse.Namespace(
photon_command="setup", project_name=None, phone=None, first_name=None, last_name=None,
email=None, no_browser=False, skip_sidecar_install=False))
-# ---------------------------------------------------------------------------
-# Small interactive helpers
-
def _prompt(prompt: str, *, secret: bool = False) -> str:
if not sys.stdin.isatty():
return ""
try:
- if secret:
- return getpass.getpass(prompt).strip()
- return input(prompt).strip()
+ return (getpass.getpass(prompt) if secret else input(prompt)).strip()
except (KeyboardInterrupt, EOFError):
print()
return ""
diff --git a/plugins/platforms/photon/sidecar_paths.py b/plugins/platforms/photon/sidecar_paths.py
index eb7be09c0fa..b87f1cd361b 100644
--- a/plugins/platforms/photon/sidecar_paths.py
+++ b/plugins/platforms/photon/sidecar_paths.py
@@ -1,25 +1,13 @@
+"""Resolve where the Photon sidecar runs from and where its Node deps live.
+
+Hosted images keep the plugin tree read-only (EROFS), so, mirroring
+``resolve_whatsapp_bridge_dir``: (1) ``PHOTON_SIDECAR_DIR`` override as-is; (2) writable
+source dir → run in place; (3) read-only with baked, current ``node_modules`` → in place;
+(4) read-only and deps missing/stale → mirror the source files to
+``$HERMES_HOME/photon/sidecar``. The mirror is refreshed by content compare; ``node_modules``
+is left alone so the lockfile-vs-install-marker check triggers ``npm ci`` inside the mirror.
+Resolution never happens at import time (it probes/copies on disk).
"""
-Resolve where the Photon sidecar runs from and where its Node deps live.
-
-The sidecar source ships inside the installed plugin tree. Hosted/managed
-images keep that tree read-only (``/opt/hermes``, EROFS on every install /
-self-heal path), so resolution mirrors ``resolve_whatsapp_bridge_dir``:
-
-1. ``PHOTON_SIDECAR_DIR`` env override — used as-is.
-2. Source dir writable → run in place (dev installs).
-3. Source dir read-only but ``node_modules`` is baked and current → run in
- place (the Dockerfile bakes deps with ``npm ci`` at build time).
-4. Source dir read-only and deps missing/stale → mirror the sidecar source
- files to ``$HERMES_HOME/photon/sidecar`` (durable, writable) and return it.
-
-The mirror is refreshed on every resolve by content compare (not mtime);
-``node_modules`` is left alone so the adapter's lockfile-vs-install-marker
-staleness check triggers the ``npm ci`` self-heal inside the mirror.
-
-Import-light on purpose: both ``adapter.py`` and ``cli.py`` use it, and
-resolution never happens at import time (it probes/copies on disk).
-"""
-
from __future__ import annotations
import filecmp
@@ -32,30 +20,27 @@ from typing import Optional
logger = logging.getLogger(__name__)
SOURCE_SIDECAR_DIR = Path(__file__).parent / "sidecar"
-
-# Files that define the sidecar; node_modules is deliberately absent (baked
-# on managed images or installed by npm in the mirror).
+# Files that define the sidecar; node_modules is deliberately absent (baked on managed
+# images or installed by npm in the mirror).
_MIRROR_FILES = ("index.mjs", "package.json", "package-lock.json", "patch-spectrum-mixed-attachments.mjs")
-
-# Tests monkeypatch these module globals directly; the accessors honor a
-# non-None value and only resolve/derive when unset.
+# Tests monkeypatch these module globals directly; the accessors honor a non-None value.
_SIDECAR_DIR: Optional[Path] = None
-# Written by `hermes photon install-sidecar` on npm failure so
-# check_requirements() can surface the root cause later; cleared on success.
+# Written by `hermes photon install-sidecar` on npm failure so check_requirements() can
+# surface the root cause later; cleared on success.
_NPM_ERROR_LOG: Optional[Path] = None
_NPM_ERROR_LOG_MAX_CHARS = 300
def dir_writable(path: Path) -> bool:
- """True when we can create files in ``path`` (probe, not stat — stat lies on
- root-squash / read-only bind mounts)."""
+ """True when we can create files in ``path`` (probe, not stat — stat lies on root-squash
+ / read-only bind mounts)."""
probe = path / ".hermes-write-probe"
try:
probe.touch()
probe.unlink()
- return True
except OSError:
return False
+ return True
_dir_writable = dir_writable
@@ -63,8 +48,8 @@ _dir_writable = dir_writable
def _lock_newer_than_install(sidecar_dir: Path) -> bool:
"""True when the committed lockfile postdates npm's install marker
- (``node_modules/.package-lock.json``) — the same signal ``npm ci`` uses.
- False on any stat failure so an odd filesystem never blocks start."""
+ (``node_modules/.package-lock.json``) — the same signal ``npm ci`` uses. False on any
+ stat failure so an odd filesystem never blocks start."""
lockfile = sidecar_dir / "package-lock.json"
marker = sidecar_dir / "node_modules" / ".package-lock.json"
try:
@@ -81,8 +66,7 @@ def resolve_sidecar_dir(source_dir: Optional[Path] = None) -> Path:
return Path(override)
if _dir_writable(source):
return source
- # Read-only tree with baked, current deps: run in place (the sidecar never
- # writes inside its own directory).
+ # Read-only tree with baked, current deps: run in place (the sidecar never writes there).
if (source / "node_modules").exists() and not _lock_newer_than_install(source):
return source
from hermes_constants import get_hermes_home
@@ -90,11 +74,8 @@ def resolve_sidecar_dir(source_dir: Optional[Path] = None) -> Path:
try:
mirror.mkdir(parents=True, exist_ok=True)
for name in _MIRROR_FILES:
- src = source / name
- if not src.exists():
- continue
- dst = mirror / name
- if not dst.exists() or not filecmp.cmp(str(src), str(dst), shallow=False):
+ src, dst = source / name, mirror / name
+ if src.exists() and (not dst.exists() or not filecmp.cmp(str(src), str(dst), shallow=False)):
shutil.copy2(str(src), str(dst))
return mirror
except OSError as exc:
@@ -102,8 +83,7 @@ def resolve_sidecar_dir(source_dir: Optional[Path] = None) -> Path:
"[photon] install tree is read-only and mirroring the sidecar "
"to %s failed (%s) — falling back to the read-only source dir; "
"dependency installs will not be possible",
- mirror,
- exc)
+ mirror, exc)
return source
@@ -117,6 +97,4 @@ def _sidecar_dir() -> Path:
def _npm_error_log() -> Path:
"""Path of the persisted npm-failure log (derived from the sidecar dir)."""
- if _NPM_ERROR_LOG is not None:
- return _NPM_ERROR_LOG
- return _sidecar_dir() / ".photon-npm-error.log"
+ return _NPM_ERROR_LOG if _NPM_ERROR_LOG is not None else _sidecar_dir() / ".photon-npm-error.log"