| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777 |
- """Photon Dashboard API client + device-code login flow (pure Python, no spectrum-ts).
- Management calls hit ``https://app.photon.codes/api/...`` (OAuth 2.0 device flow, Bearer)
- like the official CLI. The dashboard project ``id`` *is* the Spectrum Cloud project id and
- Spectrum is always provisioned at create-time; the sidecar authenticates with
- ``(id, projectSecret)``. Storage: runtime SDK creds -> ``~/.hermes/.env``; management
- metadata -> ``auth.json`` under ``credential_pool.photon`` (device token), ``photon_project``
- (ids + secret for offline status) and ``photon_user`` (numbers).
- """
- from __future__ import annotations
- import json
- import logging
- import os
- import re
- import stat
- import time
- import uuid
- from base64 import b64encode
- from dataclasses import dataclass
- from pathlib import Path
- from typing import Any, Callable, Dict, List, Optional, Tuple
- try:
- import httpx
- except ImportError: # pragma: no cover - httpx is a hermes dependency
- httpx = None # type: ignore[assignment]
- from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret
- from hermes_constants import get_hermes_home
- import contextlib
- logger = logging.getLogger(__name__)
- class PhotonDashboardAuthError(RuntimeError):
- """Raised when Photon rejects a device-flow token for the dashboard API."""
- # Hosted Photon allowlists device clients (unregistered → 400 invalid_client); use Photon's
- # published CLI client until Hermes gets its own client_id.
- DEFAULT_CLIENT_ID = "photon-cli"
- DEFAULT_SCOPE = "openid profile email"
- DEFAULT_DASHBOARD_HOST = "https://app.photon.codes"
- DEFAULT_SPECTRUM_HOST = "https://spectrum.photon.codes"
- DEFAULT_PROJECT_NAME = "Hermes Agent"
- DEFAULT_POLL_INTERVAL = 5 # RFC 8628 polling defaults; Photon's `interval` / `expires_in` win
- DEFAULT_POLL_TIMEOUT = 1800
- E164_RE = re.compile(r"^\+[1-9]\d{6,14}$")
- # -- auth.json helpers (shares the file with the rest of hermes-agent) ------------
- def _auth_json_path() -> Path:
- """The active profile's ``auth.json`` (shared with the rest of hermes-agent)."""
- return get_hermes_home() / "auth.json"
- def _load_auth() -> dict[str, Any]:
- path = _auth_json_path()
- if not path.exists():
- return {}
- try:
- with path.open("r", encoding="utf-8-sig") as fh:
- return json.load(fh) or {}
- except (OSError, json.JSONDecodeError) as e:
- logger.warning("photon: could not read %s: %s", path, e)
- return {}
- def _save_auth(data: dict[str, Any]) -> None:
- path = _auth_json_path()
- path.parent.mkdir(parents=True, exist_ok=True)
- # Random per-process temp name (no collisions / pre-planted symlinks), created 0o600
- # atomically via O_EXCL so the bearer token is never world-readable at umask.
- tmp = path.with_name(f"{path.name}.tmp.{os.getpid()}.{uuid.uuid4().hex}")
- fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_EXCL, stat.S_IRUSR | stat.S_IWUSR)
- try:
- fh = os.fdopen(fd, "w", encoding="utf-8")
- except BaseException: # fdopen failed before owning the descriptor — nothing else will close it
- with contextlib.suppress(OSError):
- os.close(fd)
- with contextlib.suppress(OSError):
- tmp.unlink()
- raise
- try:
- with fh:
- json.dump(data, fh, indent=2, sort_keys=True)
- fh.flush()
- os.fsync(fh.fileno())
- tmp.replace(path)
- except BaseException:
- with contextlib.suppress(OSError):
- tmp.unlink()
- raise
- def _pool_first(auth: dict[str, Any], key: str) -> Any:
- """First entry of ``credential_pool.<key>`` (a list), or None."""
- pool = auth.get("credential_pool", {}).get(key) or []
- return pool[0] if isinstance(pool, list) and pool else None
- def _store_pool_record(key: str, record: dict[str, Any]) -> None:
- """Replace ``credential_pool.<key>`` with ``[record]`` under the cross-process lock."""
- from hermes_cli.auth import _auth_store_lock
- with _auth_store_lock():
- auth = _load_auth()
- auth.setdefault("credential_pool", {})[key] = [record]
- _save_auth(auth)
- def load_photon_token() -> Optional[str]:
- """Return the device-flow bearer token stored by ``login()`` or ``None``."""
- auth = _load_auth()
- entry = _pool_first(auth, "photon") or {}
- legacy = auth.get("providers", {}).get("photon", {}) # backwards-compat shape
- token = entry.get("access_token") or entry.get("token") or legacy.get("access_token")
- return str(token) if token else None
- def store_photon_token(token: str) -> None:
- """Persist a dashboard bearer token under ``credential_pool.photon``."""
- _store_pool_record("photon", {"access_token": token, "issued_at": int(time.time())})
- def clear_photon_token() -> None:
- """Remove any stored Photon dashboard token (before re-authentication)."""
- auth = _load_auth()
- pool = auth.get("credential_pool", {})
- photon = pool.get("photon", [])
- if isinstance(photon, list) and photon:
- pool["photon"] = []
- _save_auth(auth)
- providers = auth.get("providers", {}) # legacy shape
- if "photon" in providers:
- providers["photon"] = {}
- _save_auth(auth)
- def check_photon_token_valid(token: str) -> bool:
- """True if the dashboard API accepts the token; a definitive rejection is stale,
- transient failures (network, 5xx) count as valid so they don't force a re-login."""
- if not token:
- return False
- try:
- validate_photon_token(token)
- except PhotonDashboardAuthError:
- return False
- except Exception:
- pass
- return True
- def load_project_credentials() -> tuple[Optional[str], Optional[str]]:
- """Runtime SDK creds ``(spectrum_project_id, project_secret)``: process env wins
- (``.env`` is loaded at gateway startup), then ``auth.json`` for offline/status."""
- env_id = _get_scoped_secret("PHOTON_PROJECT_ID")
- env_sec = _get_scoped_secret("PHOTON_PROJECT_SECRET")
- if env_id and env_sec:
- return env_id, env_sec
- entry = _pool_first(_load_auth(), "photon_project")
- if entry is None:
- return env_id, env_sec
- # back-compat: old records used "project_id" for the spectrum id
- return env_id or entry.get("spectrum_project_id") or entry.get("project_id"), env_sec or entry.get("project_secret")
- def load_dashboard_project_id() -> Optional[str]:
- """Project id for management API calls — prefers ``spectrum_project_id`` (on
- pre-backfill installs the old ``dashboard_project_id`` is diverged and 404s)."""
- env_id = _get_scoped_secret("PHOTON_DASHBOARD_PROJECT_ID")
- if env_id:
- return env_id
- entry = _pool_first(_load_auth(), "photon_project") or {}
- return entry.get("spectrum_project_id") or entry.get("dashboard_project_id") or entry.get("project_id")
- def store_project_credentials(
- *, spectrum_project_id: str, project_secret: str,
- dashboard_project_id: Optional[str] = None, name: Optional[str] = None) -> None:
- """Persist project credentials to both .env (runtime) and auth.json (mgmt/offline status)."""
- record: dict[str, Any] = {
- "spectrum_project_id": spectrum_project_id, "project_secret": project_secret, "issued_at": int(time.time())}
- record.update({k: v for k, v in (("dashboard_project_id", dashboard_project_id), ("name", name)) if v})
- _store_pool_record("photon_project", record)
- _persist_runtime_env(spectrum_project_id, project_secret)
- def store_user_numbers(
- *, phone_number: Optional[str] = None, assigned_phone_number: Optional[str] = None,
- user_id: Optional[str] = None, dashboard_project_id: Optional[str] = None) -> None:
- """Persist non-secret Photon user numbers for offline ``status`` output."""
- if not phone_number and not assigned_phone_number:
- return
- record: dict[str, Any] = {"issued_at": int(time.time())}
- record.update({k: v for k, v in (
- ("phone_number", phone_number), ("assigned_phone_number", assigned_phone_number),
- ("user_id", user_id), ("dashboard_project_id", dashboard_project_id)) if v})
- _store_pool_record("photon_user", record)
- def _persist_runtime_env(spectrum_project_id: str, project_secret: str) -> None:
- """Write the SDK creds to ``~/.hermes/.env`` (secret never bound to a printable local
- in a caller — CodeQL clean flow)."""
- try:
- from hermes_cli.config import save_env_value
- except ImportError:
- logger.warning("photon: hermes_cli.config unavailable — skipping .env write")
- return
- try:
- save_env_value("PHOTON_PROJECT_ID", spectrum_project_id)
- save_env_value("PHOTON_PROJECT_SECRET", project_secret)
- except Exception as e: # pragma: no cover - defensive
- logger.warning("photon: could not write project creds to .env: %s", e)
- # -- HTTP plumbing ----------------------------------------------------------------
- def _dashboard_host() -> str:
- return (os.getenv("PHOTON_DASHBOARD_HOST") or DEFAULT_DASHBOARD_HOST).rstrip("/")
- def _spectrum_host() -> str:
- return (os.getenv("PHOTON_SPECTRUM_HOST") or DEFAULT_SPECTRUM_HOST).rstrip("/")
- def _bearer(token: str) -> dict[str, str]:
- return {"Authorization": f"Bearer {token}"}
- def _basic(project_id: str, project_secret: str) -> dict[str, str]:
- token = b64encode(f"{project_id}:{project_secret}".encode()).decode("ascii")
- return {"Authorization": f"Basic {token}"}
- def _require_httpx(what: str = "") -> None:
- if httpx is None:
- raise RuntimeError(f"httpx is required for Photon{what}")
- def _dashboard_get(path: str, token: str, *, what: str = " device login") -> Any:
- _require_httpx(what)
- return httpx.get(f"{_dashboard_host()}{path}", headers=_bearer(token), timeout=30.0)
- def _dashboard_post(path: str, body: dict[str, Any], token: str, *, what: str = "") -> Any:
- """POST to the dashboard, raise for HTTP errors, return the decoded body."""
- _require_httpx(what)
- resp = httpx.post(f"{_dashboard_host()}{path}", json=body, headers=_bearer(token), timeout=30.0)
- resp.raise_for_status()
- return resp.json() or {}
- def _response_error_detail(resp: Any) -> str:
- data = None
- with contextlib.suppress(Exception):
- data = resp.json()
- if isinstance(data, dict):
- for key in ("error", "message", "detail"):
- if data.get(key):
- return str(data[key])
- return json.dumps(data, sort_keys=True)[:500]
- text = getattr(resp, "text", "") or ""
- return text[:500] if text else "no response body"
- def _raise_for_status(resp: Any, action: str) -> None:
- status = getattr(resp, "status_code", 200)
- if status >= 400:
- raise RuntimeError(f"Photon {action} failed: HTTP {status}: {_response_error_detail(resp)}")
- def _safe(fn: Callable[[], None]) -> None:
- with contextlib.suppress(Exception):
- fn()
- # -- Device login flow (RFC 8628) ----------------------------------------------------
- @dataclass
- class DeviceCode:
- device_code: str
- user_code: str
- verification_uri: str
- verification_uri_complete: Optional[str]
- expires_in: int
- interval: int
- @dataclass(frozen=True)
- class _DeviceTokenCandidate:
- """A token-like value extracted from the device-token response."""
- source: str
- token: str
- def request_device_code(
- *, client_id: str = DEFAULT_CLIENT_ID, scope: Optional[str] = DEFAULT_SCOPE) -> DeviceCode:
- """POST ``/api/auth/device/code`` and return the device + user codes."""
- _require_httpx(" device login")
- body: dict[str, Any] = {"client_id": client_id}
- if scope:
- body["scope"] = scope
- resp = httpx.post(f"{_dashboard_host()}/api/auth/device/code", json=body, timeout=30.0)
- resp.raise_for_status()
- data = resp.json()
- return DeviceCode(
- device_code=data["device_code"], user_code=data["user_code"],
- verification_uri=data["verification_uri"],
- verification_uri_complete=data.get("verification_uri_complete"),
- expires_in=int(data.get("expires_in") or DEFAULT_POLL_TIMEOUT),
- interval=int(data.get("interval") or DEFAULT_POLL_INTERVAL))
- def poll_for_token(
- code: DeviceCode, *, client_id: str = DEFAULT_CLIENT_ID, timeout: Optional[int] = None,
- interval: Optional[int] = None, on_pending: Optional[Callable[[], None]] = None) -> str:
- """Poll ``/api/auth/device/token`` until approved (official-CLI semantics: sleep first;
- ``authorization_pending`` keeps the interval, ``slow_down`` +5s, HTTP 429 +10s,
- ``access_denied``/``expired_token`` abort)."""
- _require_httpx(" device login")
- url = f"{_dashboard_host()}/api/auth/device/token"
- deadline = time.time() + (timeout or code.expires_in or DEFAULT_POLL_TIMEOUT)
- sleep = interval if interval is not None else (code.interval or DEFAULT_POLL_INTERVAL)
- grant = {"grant_type": "urn:ietf:params:oauth:grant-type:device_code", "device_code": code.device_code,
- "client_id": client_id}
- def _pending() -> None:
- if on_pending:
- _safe(on_pending)
- while time.time() < deadline:
- time.sleep(sleep)
- try:
- resp = httpx.post(url, json=grant, timeout=30.0)
- except httpx.RequestError as e:
- logger.warning("photon: device-token poll failed: %s", e)
- continue
- if resp.status_code == 200:
- body: Any = {}
- with contextlib.suppress(TypeError, ValueError): # json.JSONDecodeError is a ValueError
- body = resp.json() or {}
- body = body if isinstance(body, dict) else {}
- candidates = _device_response_token_candidates(body, headers=getattr(resp, "headers", {}))
- if not candidates:
- raise RuntimeError(
- "Photon returned 200 but no token candidate in the device-token response "
- "(expected access_token, data.access_token, accessToken, or set-auth-token).")
- return candidates[0].token
- if resp.status_code == 429: # RFC 8628 §3.5 — treat as slow_down
- sleep += 10
- _pending()
- continue
- if resp.status_code == 400:
- body = {}
- with contextlib.suppress(json.JSONDecodeError):
- body = resp.json() or {}
- err = body.get("error") or body.get("message") or ""
- if err in ("authorization_pending", "slow_down"):
- if err == "slow_down":
- sleep += 5
- _pending()
- continue
- if err in ("expired_token", "access_denied"):
- raise RuntimeError(f"Photon login failed: {err}")
- raise RuntimeError(f"Photon device token error: {err or resp.text}")
- logger.warning("photon: device-token unexpected status %s: %s", resp.status_code, resp.text[:200])
- raise TimeoutError("Photon device login timed out")
- def _device_response_token_candidates(body: dict[str, Any], *, headers: Optional[Any] = None) -> list:
- """De-duplicated token candidates from a device-token response — Photon has returned
- tokens under several keys across versions plus the ``set-auth-token`` header, so
- collect every shape for validation."""
- session = body.get("session") if isinstance(body.get("session"), dict) else {}
- data = body.get("data") if isinstance(body.get("data"), dict) else {}
- raw = (
- ("access_token", body.get("access_token")), ("accessToken", body.get("accessToken")),
- ("session.access_token", session.get("access_token")),
- ("data.access_token", data.get("access_token")), ("data.accessToken", data.get("accessToken")),
- ("set-auth-token", _header_value(headers, "set-auth-token")))
- candidates: list = []
- seen: set = set()
- for source, value in raw:
- token = _clean_bearer_token(value)
- if token and token not in seen:
- seen.add(token)
- candidates.append(_DeviceTokenCandidate(source=source, token=token))
- return candidates
- def _clean_bearer_token(value: Any) -> Optional[str]:
- if not isinstance(value, str):
- return None
- token = value.strip()
- return (token[7:].strip() if token.lower().startswith("bearer ") else token) or None
- def _header_value(headers: Optional[Any], name: str) -> Optional[str]:
- if not headers:
- return None
- with contextlib.suppress(AttributeError):
- value = headers.get(name)
- if value:
- return str(value)
- with contextlib.suppress(TypeError, ValueError):
- for key, value in dict(headers).items():
- if str(key).lower() == name.lower() and value:
- return str(value)
- return None
- def validate_photon_token(token: str) -> dict[str, Any]:
- """Verify a device-flow token against ``/api/auth/get-session`` AND ``/api/projects/`` —
- the device flow can mint tokens that pass the session lookup but are rejected by the
- project APIs setup depends on."""
- def _get(path: str, rejected: str) -> Any:
- resp = _dashboard_get(path, token)
- if resp.status_code in (401, 403):
- raise PhotonDashboardAuthError(rejected)
- resp.raise_for_status()
- return resp
- data = _get("/api/auth/get-session",
- "Photon issued a device token, but the dashboard session lookup rejected it.").json()
- user = data.get("user") if isinstance(data, dict) else None
- if not isinstance(user, dict) or not user:
- raise PhotonDashboardAuthError(
- "Photon issued a device token, but the dashboard session lookup did not recognize it.")
- _get("/api/projects/", "Photon device token was accepted for the session lookup but rejected by the project API.")
- return user
- def _validated_dashboard_token(candidates: list) -> str:
- """Return the first candidate token that passes dashboard validation."""
- if not candidates:
- raise RuntimeError("Photon returned 200 but no token candidate in the device-token response.")
- dashboard_error: Optional[PhotonDashboardAuthError] = None
- last_error: Optional[BaseException] = None
- for candidate in candidates:
- try:
- validate_photon_token(candidate.token)
- return candidate.token
- except Exception as exc:
- last_error = exc
- if isinstance(exc, PhotonDashboardAuthError):
- dashboard_error = exc
- if dashboard_error is not None:
- sources = ", ".join(c.source for c in candidates) or "none"
- raise PhotonDashboardAuthError(
- f"{dashboard_error} Device login returned no project-valid dashboard token (tried: {sources})."
- ) from dashboard_error
- if last_error is not None:
- raise last_error
- raise RuntimeError("Photon did not return a usable dashboard token")
- def login_device_flow(
- *, client_id: str = DEFAULT_CLIENT_ID, open_browser: bool = True,
- on_user_code: Optional[Callable[[DeviceCode], None]] = None) -> str:
- """Run the full device-code login flow, validate the token against the dashboard API
- before persisting it, and return it. ``on_user_code`` receives the :class:`DeviceCode`."""
- code = request_device_code(client_id=client_id)
- if on_user_code:
- _safe(lambda: on_user_code(code))
- if open_browser:
- with contextlib.suppress(Exception):
- import webbrowser
- webbrowser.open(code.verification_uri_complete or code.verification_uri, new=2)
- first_token = poll_for_token(code, client_id=client_id)
- token = _validated_dashboard_token([_DeviceTokenCandidate(source="poll", token=first_token)])
- store_photon_token(token)
- return token
- # -- Dashboard API: projects --------------------------------------------------------
- def _unwrap_list(data: Any) -> list[dict[str, Any]]:
- if isinstance(data, list):
- return data
- if isinstance(data, dict):
- for key in ("data", "projects", "users", "lines", "items"):
- inner = data.get(key)
- if isinstance(inner, list):
- return inner
- if isinstance(inner, dict):
- nested = next((inner[k] for k in ("projects", "users", "lines", "items")
- if isinstance(inner.get(k), list)), None)
- if nested is not None:
- return nested
- return []
- def _dashboard_list(path: str, token: str) -> list[dict[str, Any]]:
- resp = _dashboard_get(path, token, what="")
- resp.raise_for_status()
- return _unwrap_list(resp.json())
- def _raise_on_error_key(data: dict[str, Any], action: str) -> None:
- if data.get("error"):
- raise RuntimeError(f"Photon {action} failed: {data['error']}")
- def list_projects(token: str) -> list[dict[str, Any]]:
- """GET ``/api/projects`` — return the caller's projects."""
- return _dashboard_list("/api/projects", token)
- def find_project_by_name(token: str, name: str) -> Optional[dict[str, Any]]:
- """First project whose name matches (case-insensitive)."""
- target = (name or "").strip().lower()
- for proj in list_projects(token):
- if (proj.get("name") or "").strip().lower() == target:
- return proj
- return None
- def create_project(
- token: str, *, name: str = DEFAULT_PROJECT_NAME, location: str = "United States") -> dict[str, Any]:
- """POST ``/api/projects`` and return the project (Spectrum is always provisioned;
- the request carries no ``spectrum`` flag)."""
- body: dict[str, Any] = {"name": name, "location": location, "template": False, "observability": False}
- data = _dashboard_post("/api/projects", body, token, what=" project creation")
- if not isinstance(data, dict):
- raise RuntimeError("Photon create-project returned an unexpected response")
- _raise_on_error_key(data, "create-project")
- if data.get("succeed") is False:
- raise RuntimeError(f"Photon create-project failed: {data.get('message') or data}")
- project: dict[str, Any] = data["data"] if isinstance(data.get("data"), dict) else data
- if not project.get("id"):
- raise RuntimeError("Photon create-project did not return a project id")
- return project
- def regenerate_project_secret(token: str, project_id: str) -> str:
- """POST ``/api/projects/{id}/regenerate-secret`` → the new secret (the only way to
- read one — persist it immediately)."""
- data = _dashboard_post(f"/api/projects/{project_id}/regenerate-secret", {}, token)
- _raise_on_error_key(data, "regenerate-secret")
- secret = data.get("projectSecret")
- if not secret:
- raise RuntimeError("Photon regenerate-secret returned no projectSecret")
- return str(secret)
- # -- Spectrum API: users -------------------------------------------------------------
- def _normalize_phone(phone: str) -> str:
- """Reduce a phone string to ``+`` and digits for dedup comparison."""
- return re.sub(r"[^\d+]", "", phone or "")
- def list_users(project_id: str, project_secret: str, *, timeout: float = 30.0) -> list[dict[str, Any]]:
- """GET Spectrum Cloud ``/projects/{id}/users/`` → ``SpectrumUser[]``."""
- _require_httpx()
- url = f"{_spectrum_host()}/projects/{project_id}/users/"
- resp = httpx.get(url, headers=_basic(project_id, project_secret), timeout=timeout)
- _raise_for_status(resp, "list-users")
- return _unwrap_list(resp.json())
- def find_user_by_phone(
- project_id: str, project_secret: str, phone_number: str, *, timeout: float = 30.0,
- ) -> Optional[dict[str, Any]]:
- """Existing Spectrum user with the given phone number (the routable one), or None."""
- return find_routable_user(list_users(project_id, project_secret, timeout=timeout), phone_number)
- def create_user(
- project_id: str, project_secret: str, *, phone_number: str, first_name: Optional[str] = None,
- last_name: Optional[str] = None, email: Optional[str] = None, send_invite: bool = False) -> dict[str, Any]:
- """POST Spectrum Cloud ``/projects/{id}/users/`` and return the user."""
- _require_httpx(" user creation")
- if not E164_RE.match(phone_number):
- raise ValueError(f"phone_number must be E.164 (e.g. +15551234567); got {phone_number!r}")
- url = f"{_spectrum_host()}/projects/{project_id}/users/"
- body: dict[str, Any] = {"type": "shared", "phoneNumber": phone_number}
- if send_invite:
- logger.debug("photon: send_invite is ignored by Spectrum shared-user creation")
- body.update({k: v for k, v in (("firstName", first_name), ("lastName", last_name), ("email", email)) if v})
- resp = httpx.post(url, json=body, headers=_basic(project_id, project_secret), timeout=30.0)
- _raise_for_status(resp, "create-user")
- data = resp.json() or {}
- _raise_on_error_key(data, "create-user")
- user = data.get("user") or data.get("data") or data
- if not isinstance(user, dict):
- raise RuntimeError("Photon create-user returned an unexpected response")
- return user
- def register_user_if_absent(
- project_id: str, project_secret: str, *, phone_number: str, first_name: Optional[str] = None,
- last_name: Optional[str] = None, email: Optional[str] = None) -> tuple[dict[str, Any], bool]:
- """Idempotently register a Spectrum user → ``(user, created)``; the official CLI does
- no dedup, so we add it to keep ``setup`` re-runnable."""
- existing = find_user_by_phone(project_id, project_secret, phone_number)
- if existing is not None:
- return existing, False
- return create_user(project_id, project_secret, phone_number=phone_number, first_name=first_name,
- last_name=last_name, email=email), True
- def user_assigned_line(user: Optional[dict[str, Any]]) -> Optional[str]:
- """The iMessage number a user texts to reach the agent (``assignedPhoneNumber``, the
- dashboard's "TEXTS ON" column). None when unset (freshly created user)."""
- val = user.get("assignedPhoneNumber") if user else None
- return str(val) if val else None
- def user_opted_in(user: Optional[dict[str, Any]]) -> bool:
- """True when the delivery plane routes this user: the row carries ``meta.opt_in``, which
- the service sets only after the human texts the row's ``assignedPhoneNumber`` once from
- ``phoneNumber``. Without it sends fail "Target not allowed for this project", and
- client-supplied meta is ignored on create, so the API cannot produce the flag."""
- meta = user.get("meta") if user else None
- return bool(isinstance(meta, dict) and meta.get("opt_in"))
- def find_routable_user(users: list[dict[str, Any]], phone_number: str) -> Optional[dict[str, Any]]:
- """The row that decides routing for ``phone_number``: an opted-in duplicate wins over list
- order (opt-in is scoped to one number/assigned-line pair), else the first match."""
- target = _normalize_phone(phone_number)
- matches = [u for u in users if _normalize_phone(u.get("phoneNumber") or "") == target]
- return next((u for u in matches if user_opted_in(u)), matches[0] if matches else None)
- def wait_for_opted_in_user(
- project_id: str, project_secret: str, phone_number: str, *, timeout_s: float = 300.0,
- interval_s: float = 5.0, on_waiting: Optional[Callable[[int], None]] = None,
- sleep_fn: Callable[[float], None] = time.sleep,
- clock: Callable[[], float] = time.monotonic) -> Optional[dict[str, Any]]:
- """Poll until ``phone_number``'s row is opted in; the opted-in row, or None at the bound.
- A failed list call is a missed poll (the wait rides out the operator's manual step). Two
- bounds: the attempt cap, and a wall-clock deadline so slow list calls (30 s HTTP timeout
- each) cannot stretch the promised wait far past ``timeout_s``."""
- deadline = clock() + timeout_s
- max_attempts = max(1, int(timeout_s / interval_s))
- for attempt in range(1, max_attempts + 1):
- try:
- user = find_user_by_phone(project_id, project_secret, phone_number)
- if user_opted_in(user):
- return user
- except (httpx.HTTPError, RuntimeError, ValueError) as exc: # transport / HTTP status / bad JSON
- logger.debug("photon: opt-in poll failed (attempt %d): %s", attempt, exc)
- if on_waiting is not None:
- on_waiting(attempt)
- if attempt == max_attempts or clock() + interval_s > deadline:
- break
- sleep_fn(interval_s)
- return None
- def load_user_numbers() -> tuple[Optional[str], Optional[str]]:
- """``(operator_phone_number, assigned_phone_number)`` for status."""
- entry = _pool_first(_load_auth(), "photon_user")
- entry = entry if isinstance(entry, dict) else {}
- phone = entry.get("phone_number") or entry.get("phoneNumber")
- assigned = entry.get("assigned_phone_number") or entry.get("assignedPhoneNumber")
- return (str(phone) if phone else _configured_operator_phone(), str(assigned) if assigned else None)
- def refresh_user_numbers(project_id: str, project_secret: str) -> tuple[Optional[str], Optional[str]]:
- """Refresh cached user numbers from Photon without provisioning anything."""
- phone, assigned = load_user_numbers()
- if phone:
- user = find_user_by_phone(project_id, project_secret, phone)
- else:
- users = list_users(project_id, project_secret)
- user = users[0] if len(users) == 1 else None
- user_id = None
- if user:
- user_id = user.get("id")
- dashboard_phone = _normalize_phone(str(user.get("phoneNumber") or ""))
- if E164_RE.match(dashboard_phone):
- phone = dashboard_phone
- assigned = user_assigned_line(user)
- dashboard_id = load_dashboard_project_id()
- dashboard_token = load_photon_token() if not assigned else None
- if dashboard_token and dashboard_id:
- try:
- line = get_imessage_line(dashboard_token, dashboard_id, create_if_missing=False)
- if line and line.get("phoneNumber"):
- assigned = str(line["phoneNumber"])
- except Exception as e:
- logger.debug("photon: could not refresh iMessage line for status: %s", e)
- store_user_numbers(phone_number=phone, assigned_phone_number=assigned,
- user_id=str(user_id) if user_id else None, dashboard_project_id=dashboard_id)
- return phone, assigned
- def _configured_operator_phone() -> Optional[str]:
- """Infer the operator's E.164 number from existing Photon env settings."""
- home = _normalize_phone(_get_config_env_value("PHOTON_HOME_CHANNEL") or "")
- if home and E164_RE.match(home):
- return home
- allowed = _get_config_env_value("PHOTON_ALLOWED_USERS") or ""
- candidates = [n for n in map(_normalize_phone, re.split(r"[,\s]+", allowed)) if E164_RE.match(n)]
- return candidates[0] if len(candidates) == 1 else None
- def _get_config_env_value(key: str) -> Optional[str]:
- try:
- from hermes_cli.config import get_env_value
- except Exception:
- return os.getenv(key)
- return get_env_value(key)
- # -- Dashboard API: iMessage lines (the assigned number inventory) --------------------
- def list_lines(token: str, project_id: str) -> list[dict[str, Any]]:
- """GET ``/api/projects/{id}/lines`` → ``[{id, platform, phoneNumber, status}]``."""
- return _dashboard_list(f"/api/projects/{project_id}/lines", token)
- def add_line(token: str, project_id: str, *, platform: str = "imessage") -> dict[str, Any]:
- """POST ``/api/projects/{id}/lines`` to provision a new line."""
- data = _dashboard_post(f"/api/projects/{project_id}/lines", {"platform": platform}, token)
- _raise_on_error_key(data, "add-line")
- return data.get("line") or data
- def get_imessage_line(
- token: str, project_id: str, *, create_if_missing: bool = True) -> Optional[dict[str, Any]]:
- """The project's iMessage line, provisioning one if absent and ``create_if_missing``;
- None if there is none and provisioning failed."""
- line = next((ln for ln in list_lines(token, project_id) if (ln.get("platform") or "").lower() == "imessage"), None)
- if line is not None or not create_if_missing:
- return line
- try:
- return add_line(token, project_id, platform="imessage")
- except Exception as e:
- logger.warning("photon: could not auto-provision iMessage line: %s", e)
- return None
- # -- Credential status (display-only — never emits raw secret material) ---------------
- def print_credential_summary(emit: Any = print) -> None:
- """Pretty-print the credential status table via *emit*. Every secret-bearing read is
- reduced to a display literal here; the callback only ever receives the assembled
- banner, so no tainted value escapes to the caller."""
- sid, sec = load_project_credentials()
- phone, assigned = load_user_numbers()
- rows = [
- "Photon iMessage status",
- "──────────────────────",
- " device token : " + (
- "✓ stored" if load_photon_token() else "✗ missing (run `hermes photon setup`)"),
- " project id : " + (sid if sid else "✗ missing"),
- " project secret : " + ("✓ stored" if sec else "✗ missing"),
- " my number : " + (phone if phone else "✗ missing (run `hermes photon setup --phone ...`)"),
- " assigned number : " + (assigned if assigned else "✗ missing (run `hermes photon setup`)")]
- emit("\n".join(rows))
- _STATUS_TIMEOUT_S = 5.0 # `photon status` stays quick when the API is unreachable
- def print_routing_status(emit: Any = print) -> None:
- """Live opt-in row for ``status``: a registered number that never texted its assigned line
- looks configured everywhere but never routes. Verified against the API, not local markers;
- lives here (with the credential reads) so the CLI sink only sees display text."""
- phone, assigned = load_user_numbers()
- sid, sec = load_project_credentials()
- if not (phone and sid and sec):
- return
- try:
- user = find_user_by_phone(sid, sec, phone, timeout=_STATUS_TIMEOUT_S)
- except (httpx.HTTPError, RuntimeError, ValueError) as e:
- emit(f" routing : ? could not verify ({str(e) or type(e).__name__})")
- return
- if user_opted_in(user):
- emit(" routing : ✓ opted in (verified live)")
- else:
- line = user_assigned_line(user) or assigned or "your assigned line"
- emit(f" routing : ✗ not opted in — text {line} once from {phone}, then re-check")
|