Skip to content

The agent that grows with you

feat(photon): gate setup success on iMessage opt-in via first message

Teknium5d9b27cd2333
diff --git a/plugins/platforms/photon/auth.py b/plugins/platforms/photon/auth.py
index b2fca6840ca..2f82c05a684 100644
--- a/plugins/platforms/photon/auth.py
+++ b/plugins/platforms/photon/auth.py
@@ -560,12 +560,8 @@ def list_users(project_id: str, project_secret: str) -> list[dict[str, Any]]:
def find_user_by_phone(project_id: str, project_secret: str, phone_number: str) -> Optional[dict[str, Any]]:
- """Existing Spectrum user with the given phone number, or None."""
- target = _normalize_phone(phone_number)
- for user in list_users(project_id, project_secret):
- if _normalize_phone(user.get("phoneNumber") or "") == target:
- return user
- return None
+ """Existing Spectrum user with the given phone number (the routable one), or None."""
+ return find_routable_user(list_users(project_id, project_secret), phone_number)
def create_user(
@@ -609,6 +605,45 @@ def user_assigned_line(user: Optional[dict[str, Any]]) -> Optional[str]:
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) -> 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); the
+ attempt cap keeps instant-``sleep_fn`` tests deterministic."""
+ 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:
+ 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")
@@ -711,3 +746,23 @@ def print_credential_summary(emit: Any = print) -> None:
" 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))
+
+
+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)
+ except (httpx.HTTPError, RuntimeError, ValueError) as e:
+ emit(f" routing : ? could not verify ({e})")
+ 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")
diff --git a/plugins/platforms/photon/cli.py b/plugins/platforms/photon/cli.py
index 1d25e8ed0db..910d088bab1 100644
--- a/plugins/platforms/photon/cli.py
+++ b/plugins/platforms/photon/cli.py
@@ -180,6 +180,13 @@ def _cmd_setup(args: argparse.Namespace) -> int:
# 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)
+ # Opt-in gate: Photon only routes a number whose user row carries meta.opt_in, which the
+ # service sets once the human texts the assigned line from their phone (the API cannot
+ # set it). Name the line and wait for the opt-in; a re-run on an opted-in row passes.
+ if photon_auth.user_opted_in(user):
+ print(" ✓ number is opted in — routing is live")
+ else:
+ agent_number = _wait_for_opt_in(dashboard_id, secret, phone, agent_number)
# 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.
@@ -224,6 +231,36 @@ def _cmd_setup(args: argparse.Namespace) -> int:
return 0
+def _wait_for_opt_in(dashboard_id: str, secret: str, phone: str, agent_number: Optional[str]) -> Optional[str]:
+ """Print the opt-in step and, on a TTY, wait for it to land. Returns the agent number
+ (the assignment can materialize with the opt-in)."""
+ line_hint = agent_number or "the line Photon assigns to your number"
+ print("\n" + color(" One manual step: opt in by texting your agent", Colors.CYAN, Colors.BOLD))
+ print(" Your number only enters iMessage routing after it has messaged the line\n"
+ f" Photon assigned to it:\n 1. Open Messages on {phone}.\n"
+ f" 2. Text {line_hint} — one message of any content is enough.")
+ if not sys.stdin.isatty(): # scripted setup / CI: nobody can answer the poll
+ print(" Non-interactive run — skipping the opt-in wait. Verify later with `hermes photon status`.")
+ return agent_number
+ print(" Setup waits here (up to 5 minutes) and continues once the opt-in lands.\n"
+ " (Ctrl-C to skip — re-running setup resumes where it left off.)")
+
+ def _on_waiting(attempt: int) -> None:
+ if attempt % 6 == 0:
+ print(" ... still waiting for your message to land")
+ try:
+ opted = photon_auth.wait_for_opted_in_user(dashboard_id, secret, phone, on_waiting=_on_waiting)
+ except KeyboardInterrupt:
+ opted = None
+ print()
+ if opted is None:
+ print(f" ⚠ {phone} is not opted in yet. Send one message from {phone} to {line_hint}, "
+ "then re-run `hermes photon setup` — it resumes where it left off.")
+ return agent_number
+ print(" ✓ opt-in landed — routing is live")
+ return photon_auth.user_assigned_line(opted) or agent_number
+
+
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."""
@@ -259,6 +296,7 @@ def _cmd_status(_args: argparse.Namespace) -> int:
print(f" node binary : {node_bin or '✗ missing (install Node 18+)'}")
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`)")
+ photon_auth.print_routing_status(print)
return 0
diff --git a/tests/plugins/platforms/photon/test_auth.py b/tests/plugins/platforms/photon/test_auth.py
index ab6d1cf30b6..249d36c759e 100644
--- a/tests/plugins/platforms/photon/test_auth.py
+++ b/tests/plugins/platforms/photon/test_auth.py
@@ -310,6 +310,59 @@ def test_user_assigned_line() -> None:
assert photon_auth.user_assigned_line(None) is None
+# ---------------------------------------------------------------------------
+# Opt-in routing: only a row carrying meta.opt_in routes.
+
+def _users_body(*rows: dict[str, Any]) -> _FakeResponse:
+ return _FakeResponse(json_body={"succeed": True, "data": {"users": list(rows)}})
+
+
+def test_wait_for_opted_in_user_polls_until_flag_lands(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Poll 1 fails transiently, poll 2 sees no flag, poll 3 sees it land."""
+ calls = {"n": 0}
+
+ def fake_get(url: str, **kwargs: Any) -> _FakeResponse:
+ calls["n"] += 1
+ if calls["n"] == 1:
+ raise RuntimeError("transient")
+ meta = {"opt_in": True} if calls["n"] >= 3 else {}
+ return _users_body({"id": "u1", "phoneNumber": "+15551234567",
+ "assignedPhoneNumber": "+16282679185", "meta": meta})
+
+ monkeypatch.setattr(photon_auth.httpx, "get", fake_get)
+ waits: list = []
+ user = photon_auth.wait_for_opted_in_user(
+ "proj", "secret", "+15551234567", timeout_s=50, interval_s=5,
+ on_waiting=waits.append, sleep_fn=lambda _s: None,
+ )
+ assert user is not None and photon_auth.user_opted_in(user)
+ assert calls["n"] == 3 and waits == [1, 2]
+ # Never opted in -> None at the bound, not an endless poll.
+ monkeypatch.setattr(photon_auth.httpx, "get", lambda url, **kw: _users_body(
+ {"id": "u1", "phoneNumber": "+15551234567", "meta": {}}))
+ assert photon_auth.wait_for_opted_in_user(
+ "proj", "secret", "+15551234567", timeout_s=15, interval_s=5,
+ sleep_fn=lambda _s: None,
+ ) is None
+
+
+def test_register_user_if_absent_reuses_opted_in_duplicate(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A re-run must reuse the OPTED-IN duplicate, not list order, or a landed opt-in is lost."""
+ monkeypatch.setattr(photon_auth.httpx, "get", lambda url, **kw: _users_body(
+ {"id": "stale", "phoneNumber": "+15551234567", "meta": {}},
+ {"id": "live", "phoneNumber": "+1 (555) 123-4567", "meta": {"opt_in": True}},
+ ))
+ monkeypatch.setattr(photon_auth.httpx, "post", lambda url, **kw: pytest.fail("created a duplicate"))
+ user, created = photon_auth.register_user_if_absent(
+ "proj", "secret", phone_number="+15551234567",
+ )
+ assert created is False and user["id"] == "live"
+
+
# ---------------------------------------------------------------------------
# Lines (assigned number)