The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(photon): collapse defensive layers + fold branches across adapter/auth/cli (2813->2749 LOC)
Teknium229f530d3462
diff --git a/plugins/platforms/photon/adapter.py b/plugins/platforms/photon/adapter.pyindex b5fd83d4d62..baa5f0d65d4 100644--- a/plugins/platforms/photon/adapter.py+++ b/plugins/platforms/photon/adapter.py@@ -131,15 +131,14 @@ def _sidecar_pid_alive(pid: Any) -> bool:return bool(_pid_exists(pid_int))except Exception:pass- if os.name == "posix":- try:- os.kill(pid_int, 0) # windows-footgun: ok — inside os.name == "posix" guard- except PermissionError:- return True- except OSError: # incl. ProcessLookupError- return False+ if os.name != "posix": # os.kill(pid, 0) is destructive on Windows — assume alive; the HTTP send arbitratesreturn True- # Windows without psutil: os.kill(pid, 0) is destructive — assume alive; the HTTP send arbitrates.+ try:+ os.kill(pid_int, 0) # windows-footgun: ok — inside os.name == "posix" guard+ except PermissionError:+ return True+ except OSError: # incl. ProcessLookupError+ return Falsereturn True@@ -173,11 +172,9 @@ class PhotonSidecarError(RuntimeError):def _sidecar_error_from_response(path: str, status_code: int, text: str,data: Optional[Dict[str, Any]] = None) -> PhotonSidecarError:if data is None:- try:- parsed = json.loads(text)- except Exception:- parsed = {}- data = parsed if isinstance(parsed, dict) else {}+ with contextlib.suppress(Exception):+ data = json.loads(text)+ data = data if isinstance(data, dict) else {}error = str(data.get("error") or text[:200] or "sidecar error")error_class = str(data.get("error_class") or "sidecar_error")retryable = bool(data.get("retryable"))@@ -201,8 +198,7 @@ def _is_timeout_error(exc: BaseException) -> bool:"""True when *exc* indicates the request timed out (call hung)."""if isinstance(exc, (asyncio.TimeoutError, TimeoutError)):return True- timeout_exc = getattr(httpx, "TimeoutException", None) if HTTPX_AVAILABLE else None- if timeout_exc is not None and isinstance(exc, timeout_exc):+ if HTTPX_AVAILABLE and isinstance(exc, httpx.TimeoutException):return Truereturn "timeout" in type(exc).__name__.lower()@@ -259,21 +255,19 @@ def _reinstall_sidecar_deps() -> None:except subprocess.TimeoutExpired: # retried on the next reconnect ticklogger.error("[photon] sidecar dependency reinstall timed out after %ss", _NPM_REINSTALL_TIMEOUT)return- if result.returncode != 0:- logger.error("[photon] sidecar dependency reinstall failed: %s",- (result.stderr or result.stdout or "").strip())- else:+ if result.returncode == 0:logger.info("[photon] sidecar dependencies reinstalled from lockfile")+ else:+ logger.error("[photon] sidecar dependency reinstall failed: %s", (result.stderr or result.stdout or "").strip())def validate_config(cfg: PlatformConfig) -> bool:extra = cfg.extra or {}- project_id = extra.get("project_id") or _get_scoped_secret("PHOTON_PROJECT_ID")- project_secret = extra.get("project_secret") or _get_scoped_secret("PHOTON_PROJECT_SECRET")- if not project_id or not project_secret:- stored_id, stored_sec = load_project_credentials() # auth.json fallback- return bool(stored_id and stored_sec)- return True+ if (extra.get("project_id") or _get_scoped_secret("PHOTON_PROJECT_ID")) and (+ extra.get("project_secret") or _get_scoped_secret("PHOTON_PROJECT_SECRET")):+ return True+ stored_id, stored_sec = load_project_credentials() # auth.json fallback+ return bool(stored_id and stored_sec)def is_connected(cfg: PlatformConfig) -> bool:@@ -306,9 +300,7 @@ def _url_only_candidate(text: str) -> Optional[str]:parsed = urlparse(candidate)except ValueError:return None- if parsed.scheme.lower() not in {"http", "https"} or not parsed.netloc:- return None- return candidate+ return candidate if parsed.scheme.lower() in {"http", "https"} and parsed.netloc else Nonedef _richlink_candidate(text: str) -> Optional[str]:@@ -331,15 +323,10 @@ def _group_item_contents(content: Dict[str, Any]) -> List[Dict[str, Any]]:def _richlink_url_from_content(content: Dict[str, Any]) -> Optional[str]:ctype = content.get("type")- if ctype == "text":- return _url_only_candidate(content.get("text") or "")- if ctype == "richlink":- return _url_only_candidate(content.get("url") or "")+ if ctype in ("text", "richlink"):+ return _url_only_candidate(content.get("text" if ctype == "text" else "url") or "")if ctype == "group":- for item_content in _group_item_contents(content):- url = _richlink_url_from_content(item_content)- if url:- return url+ return next((u for u in map(_richlink_url_from_content, _group_item_contents(content)) if u), None)return None@@ -351,11 +338,12 @@ def _is_richlink_preview_attachment(payload: Dict[str, Any]) -> bool:def _richlink_preview_label(content: Dict[str, Any]) -> str:+ def _label(c: Dict[str, Any]) -> str:+ return str(c.get("name") or c.get("id") or "(unnamed)")if content.get("type") == "attachment":- return str(content.get("name") or content.get("id") or "(unnamed)")+ return _label(content)if content.get("type") == "group":- labels = [str(c.get("name") or c.get("id") or "(unnamed)") for c in _group_item_contents(content)]- return ", ".join(labels) or "(group)"+ return ", ".join(_label(c) for c in _group_item_contents(content)) or "(group)"return "(unknown)"@@ -405,12 +393,7 @@ def _normalize_group_content(content: Dict[str, Any]) -> _Normalized:media_types: List[str] = []for item_content in _group_item_contents(content):item_type = item_content.get("type")- if item_type == "text":- if item_content.get("text"):- text_parts.append(item_content["text"])- elif item_type == "richlink":- text_parts.append(_format_richlink_content(item_content))- elif item_type in {"attachment", "voice"}:+ if item_type in {"attachment", "voice"}:marker, item_mtype, item_urls, item_types = _normalize_binary_payload(item_content)if mtype == MessageType.TEXT:mtype = item_mtype@@ -418,14 +401,16 @@ def _normalize_group_content(content: Dict[str, Any]) -> _Normalized:media_types.extend(item_types)if not item_urls:text_parts.append(marker)+ elif item_type == "text":+ text_parts.append(item_content.get("text") or "")+ elif item_type == "richlink":+ text_parts.append(_format_richlink_content(item_content))elif item_type:text_parts.append(f"[Photon content type not handled: {item_type}]")if media_urls and mtype == MessageType.TEXT:mtype = MessageType.DOCUMENTtext = "\n".join(part for part in text_parts if part).strip()- if not text:- text = "(attachment)" if media_urls else "[Photon empty group received]"- return text, mtype, media_urls, media_types+ return text or ("(attachment)" if media_urls else "[Photon empty group received]"), mtype, media_urls, media_types_CONTENT_NORMALIZERS: Dict[Any, Callable[[Dict[str, Any]], _Normalized]] = {@@ -449,7 +434,8 @@ def _attachment_body(space_id: str, safe_path: str, *, kind: str, name: Optionalmime_type: Optional[str] = None, caption: Optional[str] = None) -> Dict[str, Any]:"""``/send-attachment`` body; spectrum-ts infers name/mimeType from the extension,so optional keys are only sent when Hermes supplied them."""- body: Dict[str, Any] = {"spaceId": space_id, "path": safe_path, "kind": kind}+ body: Dict[str, Any] = {+ "spaceId": space_id, "path": safe_path, "kind": "voice" if kind == "voice" else "attachment"}body.update({k: v for k, v in (("name", name), ("mimeType", mime_type), ("caption", caption)) if v})return body@@ -534,10 +520,10 @@ class PhotonAdapter(BasePlatformAdapter):self._typing_last_sent: Dict[str, float] = {}self._pending_fffc: Dict[str, tuple[float, Any]] = {} # chat_key → (timestamp, asyncio.Task)# Group-chat mention gating (parity with BlueBubbles); DMs are never gated.- _require_mention = extra.get("require_mention")- if _require_mention is None:- _require_mention = _get_scoped_secret("PHOTON_REQUIRE_MENTION")- self.require_mention = str(_require_mention).strip().lower() in {"true", "1", "yes", "on"}+ require_mention = extra.get("require_mention")+ if require_mention is None:+ require_mention = _get_scoped_secret("PHOTON_REQUIRE_MENTION")+ self.require_mention = str(require_mention).strip().lower() in {"true", "1", "yes", "on"}self._mention_patterns = self._compile_mention_patterns(extra["mention_patterns"] if "mention_patterns" in extraelse _get_scoped_secret("PHOTON_MENTION_PATTERNS"))@@ -555,13 +541,9 @@ class PhotonAdapter(BasePlatformAdapter):def _clean_mention_text(self, text: str) -> str:"""Strip a leading wake word only (patterns are regexes; never touch later words)."""- if not text:- return text- for pattern in self._mention_patterns:- match = pattern.match(text.lstrip())- if match:- cleaned = text.lstrip()[match.end():].lstrip(" ,:-")- return cleaned or text+ stripped = text.lstrip() if text else ""+ for match in filter(None, (pattern.match(stripped) for pattern in self._mention_patterns)):+ return stripped[match.end():].lstrip(" ,:-") or textreturn text# -- Sidecar HTTP plumbing ------------------------------------------------------@@ -747,10 +729,10 @@ class PhotonAdapter(BasePlatformAdapter):def _cancel_pending_fffc(self, chat_key: str) -> bool:"""Pop and cancel a pending U+FFFC timeout; True when a live task was cancelled."""prev = self._pending_fffc.pop(chat_key, None)- if prev and prev[1] and not prev[1].done():+ live = bool(prev and prev[1] and not prev[1].done())+ if live:prev[1].cancel()- return True- return False+ return liveasync def _dispatch_inbound(self, event: Dict[str, Any]) -> None:"""Normalize a sidecar inbound event ``{messageId, space: {id, type: dm|group, phone},@@ -838,11 +820,11 @@ class PhotonAdapter(BasePlatformAdapter):def _quick_stdout(cmd: List[str]) -> Optional[str]:"""stdout of a short shell-out, or None if it failed to run."""try:- out = subprocess.run( # noqa: S603, S607- cmd, capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=5.0, check=False)+ return subprocess.run( # noqa: S603, S607+ cmd, capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=5.0,+ check=False).stdoutexcept (OSError, subprocess.TimeoutExpired):return None- return out.stdout@classmethoddef _find_listener_pids(cls, port: int) -> List[int]:@@ -860,9 +842,9 @@ class PhotonAdapter(BasePlatformAdapter):def _pid_alive(pid: int) -> bool:try:os.kill(pid, 0) # windows-footgun: ok — only called from _reap_stale_sidecar which win32-guards early- return Trueexcept OSError:return False+ return Trueasync def _reap_stale_sidecar(self) -> None:"""Kill an orphaned sidecar squatting our port (a SIGKILLed gateway leaves one whose@@ -1306,10 +1288,8 @@ class PhotonAdapter(BasePlatformAdapter):def _is_retryable_error(error: Optional[str]) -> bool:if BasePlatformAdapter._is_retryable_error(error):return True- if not error:- return False- lowered = error.lower()- if "retryable=false" in lowered or "auth_or_config" in lowered:+ lowered = (error or "").lower()+ if not lowered or "retryable=false" in lowered or "auth_or_config" in lowered:return Falsereturn any(pat in lowered for pat in _PHOTON_RETRYABLE_PATTERNS)@@ -1371,10 +1351,10 @@ class PhotonAdapter(BasePlatformAdapter):try:data = await self._sidecar_call(path, body)except PhotonSidecarError as e:- if not structured:- return SendResult(success=False, error=str(e))- return SendResult(success=False, error=str(e), retryable=e.retryable,- raw_response={"error_class": e.error_class, "retryable": e.retryable})+ if structured:+ return SendResult(success=False, error=str(e), retryable=e.retryable,+ raw_response={"error_class": e.error_class, "retryable": e.retryable})+ return SendResult(success=False, error=str(e))except Exception as e:return SendResult(success=False, error=str(e))self._record_sent_message(data.get("messageId"))@@ -1416,8 +1396,7 @@ class PhotonAdapter(BasePlatformAdapter):if not safe_path:return SendResult(success=False, error=f"unsafe or missing attachment path: {path}")body = _attachment_body(- space_id, safe_path, kind="voice" if kind == "voice" else "attachment",- name=name, mime_type=mime_type or _guess_mime(safe_path), caption=caption)+ space_id, safe_path, kind=kind, name=name, mime_type=mime_type or _guess_mime(safe_path), caption=caption)return await self._post_send("/send-attachment", body, structured=True)async def _sidecar_call(self, path: str, body: Dict[str, Any]) -> Dict[str, Any]:@@ -1490,12 +1469,10 @@ def _cache_inbound_attachment(content: Dict[str, Any], name: str, mime: str, *,def _standalone_error(resp: Any) -> Dict[str, Any]:"""Structured error dict for a failed standalone call (mirrors``_sidecar_error_from_response``, incl. the canonical target_not_allowed text)."""- try:+ data: Any = {}+ with contextlib.suppress(Exception):data = resp.json() or {}- except Exception:- data = {}- if not isinstance(data, dict):- data = {}+ data = data if isinstance(data, dict) else {}error_class = str(data.get("error_class") or "sidecar_error")retryable = bool(data.get("retryable"))if error_class == "target_not_allowed":@@ -1553,20 +1530,17 @@ async def _standalone_send(return resp, (data if data.get("ok") else None)if message: # 1. text body first, so it leads the conversationrich_url = _richlink_candidate(message)+ data = Noneif rich_url:_resp, data = await _post("/send-richlink", {"spaceId": chat_id, "url": rich_url})- if data:- last_message_id = data.get("messageId")- else:- rich_url = None- if not rich_url:+ if not data: # no URL-only message, or the rich-link send failed: plain textsend_body: Dict[str, Any] = {"spaceId": chat_id, "text": message[:_MAX_MESSAGE_LENGTH]}- if _markdown_enabled() and not _richlink_candidate(message):+ if _markdown_enabled() and not rich_url:send_body["format"] = "markdown"resp, data = await _post("/send", send_body)if not data:return _standalone_error(resp)- last_message_id = data.get("messageId")+ last_message_id = data.get("messageId")# 2. Each attachment as a separate /send-attachment call; media_files is# List[Tuple[path, is_voice]] (filter_media_delivery_paths).for media_path, is_voice in media_files or []:diff --git a/plugins/platforms/photon/auth.py b/plugins/platforms/photon/auth.pyindex cc18c0a2dcc..d402048e7ad 100644--- a/plugins/platforms/photon/auth.py+++ b/plugins/platforms/photon/auth.py@@ -64,8 +64,7 @@ def _load_auth() -> Dict[str, Any]:if not path.exists():return {}try:- with path.open("r", encoding="utf-8") as fh:- return json.load(fh) or {}+ return json.loads(path.read_text(encoding="utf-8")) or {}except (OSError, json.JSONDecodeError) as e:logger.warning("photon: could not read %s: %s", path, e)return {}@@ -116,13 +115,10 @@ def _store_pool_record(key: str, record: Dict[str, Any]) -> None: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")- if entry is not None:- token = entry.get("access_token") or entry.get("token")- if token:- return str(token)+ entry = _pool_first(auth, "photon") or {}legacy = auth.get("providers", {}).get("photon", {}) # backwards-compat shape- return str(legacy["access_token"]) if legacy.get("access_token") else None+ token = entry.get("access_token") or entry.get("token") or legacy.get("access_token")+ return str(token) if token else Nonedef store_photon_token(token: str) -> None:@@ -154,7 +150,7 @@ def check_photon_token_valid(token: str) -> bool:except PhotonDashboardAuthError:return Falseexcept Exception:- return True+ passreturn True@@ -166,10 +162,10 @@ def load_project_credentials() -> Tuple[Optional[str], Optional[str]]:if env_id and env_sec:return env_id, env_secentry = _pool_first(_load_auth(), "photon_project")- if entry is not None: # back-compat: old records used "project_id" for the spectrum id- sid = entry.get("spectrum_project_id") or entry.get("project_id")- return (env_id or sid, env_sec or entry.get("project_secret"))- return env_id, env_sec+ 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]:@@ -178,10 +174,8 @@ def load_dashboard_project_id() -> Optional[str]:env_id = _get_scoped_secret("PHOTON_DASHBOARD_PROJECT_ID")if env_id:return env_id- entry = _pool_first(_load_auth(), "photon_project")- if entry is not None:- return entry.get("spectrum_project_id") or entry.get("dashboard_project_id") or entry.get("project_id")- return None+ 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(@@ -261,10 +255,9 @@ def _dashboard_post(path: str, body: Dict[str, Any], token: str, *, what: str =def _response_error_detail(resp: Any) -> str:- try:+ data = None+ with contextlib.suppress(Exception):data = resp.json()- except Exception:- data = Noneif isinstance(data, dict):for key in ("error", "message", "detail"):if data.get(key):@@ -276,9 +269,8 @@ def _response_error_detail(resp: Any) -> str:def _raise_for_status(resp: Any, action: str) -> None:status = getattr(resp, "status_code", 200)- if status < 400:- return- raise RuntimeError(f"Photon {action} failed: HTTP {status}: {_response_error_detail(resp)}")+ if status >= 400:+ raise RuntimeError(f"Photon {action} failed: HTTP {status}: {_response_error_detail(resp)}")def _safe(fn: Callable[[], None]) -> None:@@ -347,12 +339,10 @@ def poll_for_token(logger.warning("photon: device-token poll failed: %s", e)continueif resp.status_code == 200:- body: Dict[str, Any] = {}- try:- decoded = resp.json() or {}- body = decoded if isinstance(decoded, dict) else {}- except (TypeError, ValueError, json.JSONDecodeError):- body = {}+ 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(@@ -369,7 +359,8 @@ def poll_for_token(body = resp.json() or {}err = body.get("error") or body.get("message") or ""if err in ("authorization_pending", "slow_down"):- sleep += 5 if err == "slow_down" else 0+ if err == "slow_down":+ sleep += 5_pending()continueif err in ("expired_token", "access_denied"):@@ -404,9 +395,7 @@ def _clean_bearer_token(value: Any) -> Optional[str]:if not isinstance(value, str):return Nonetoken = value.strip()- if token.lower().startswith("bearer "):- token = token[7:].strip()- return token or None+ return (token[7:].strip() if token.lower().startswith("bearer ") else token) or Nonedef _header_value(headers: Optional[Any], name: str) -> Optional[str]:@@ -427,20 +416,19 @@ 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 theproject APIs setup depends on."""- resp = _dashboard_get("/api/auth/get-session", token)- if resp.status_code in (401, 403):- raise PhotonDashboardAuthError("Photon issued a device token, but the dashboard session lookup rejected it.")- resp.raise_for_status()- data = resp.json()+ 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 Noneif not isinstance(user, dict) or not user:raise PhotonDashboardAuthError("Photon issued a device token, but the dashboard session lookup did not recognize it.")- projects_resp = _dashboard_get("/api/projects/", token)- if projects_resp.status_code in (401, 403):- raise PhotonDashboardAuthError(- "Photon device token was accepted for the session lookup but rejected by the project API.")- projects_resp.raise_for_status()+ _get("/api/projects/", "Photon device token was accepted for the session lookup but rejected by the project API.")return user@@ -454,11 +442,10 @@ def _validated_dashboard_token(candidates: list) -> str:try:validate_photon_token(candidate.token)return candidate.token- except PhotonDashboardAuthError as exc:- dashboard_error = exc- last_error = excexcept Exception as exc:last_error = exc+ if isinstance(exc, PhotonDashboardAuthError):+ dashboard_error = excif dashboard_error is not None:sources = ", ".join(c.source for c in candidates) or "none"raise PhotonDashboardAuthError(@@ -498,10 +485,10 @@ def _unwrap_list(data: Any) -> List[Dict[str, Any]]:if isinstance(inner, list):return innerif isinstance(inner, dict):- for nested_key in ("projects", "users", "lines", "items"):- nested = inner.get(nested_key)- if isinstance(nested, list):- return nested+ nested = next((inner[k] for k in ("projects", "users", "lines", "items")+ if isinstance(inner.get(k), list)), None)+ if nested is not None:+ return nestedreturn []@@ -541,8 +528,7 @@ def create_project(_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_candidate = data.get("data")- project: Dict[str, Any] = project_candidate if isinstance(project_candidate, dict) else data+ project: Dict[str, Any] = data["data"] if isinstance(data.get("data"), dict) else dataif not project.get("id"):raise RuntimeError("Photon create-project did not return a project id")return project@@ -601,9 +587,9 @@ def create_user(data = resp.json() or {}_raise_on_error_key(data, "create-user")user = data.get("user") or data.get("data") or data- if isinstance(user, dict):- return user- raise RuntimeError("Photon create-user returned an unexpected response")+ if not isinstance(user, dict):+ raise RuntimeError("Photon create-user returned an unexpected response")+ return userdef register_user_if_absent(@@ -614,9 +600,8 @@ def register_user_if_absent(existing = find_user_by_phone(project_id, project_secret, phone_number)if existing is not None:return existing, False- user = create_user(project_id, project_secret, phone_number=phone_number, first_name=first_name,- last_name=last_name, email=email)- return user, True+ return create_user(project_id, project_secret, phone_number=phone_number, first_name=first_name,+ last_name=last_name, email=email), Truedef user_assigned_line(user: Optional[Dict[str, Any]]) -> Optional[str]:@@ -629,25 +614,21 @@ def user_assigned_line(user: Optional[Dict[str, Any]]) -> Optional[str]:def load_user_numbers() -> Tuple[Optional[str], Optional[str]]:"""``(operator_phone_number, assigned_phone_number)`` for status."""entry = _pool_first(_load_auth(), "photon_user")- if isinstance(entry, dict):- phone = entry.get("phone_number") or entry.get("phoneNumber")- assigned = entry.get("assigned_phone_number") or entry.get("assignedPhoneNumber")- if phone or assigned:- return (str(phone) if phone else _configured_operator_phone(), str(assigned) if assigned else None)- return _configured_operator_phone(), None+ 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, cached_assigned = load_user_numbers()- user: Optional[Dict[str, Any]] = None+ 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 Noneuser_id = None- assigned: Optional[str] = cached_assignedif user:user_id = user.get("id")dashboard_phone = _normalize_phone(str(user.get("phoneNumber") or ""))@@ -659,11 +640,10 @@ def refresh_user_numbers(project_id: str, project_secret: str) -> Tuple[Optionalif dashboard_token and dashboard_id:try:line = get_imessage_line(dashboard_token, dashboard_id, create_if_missing=False)- except Exception as e:- logger.debug("photon: could not refresh iMessage line for status: %s", e)- else: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@@ -674,10 +654,8 @@ def _configured_operator_phone() -> Optional[str]: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")- if not allowed:- return None- candidates = [n for n in (_normalize_phone(part) for part in re.split(r"[,\s]+", allowed)) if E164_RE.match(n)]+ 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@@ -707,11 +685,9 @@ 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."""- for line in list_lines(token, project_id):- if (line.get("platform") or "").lower() == "imessage":- return line- if not create_if_missing:- return None+ 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 linetry:return add_line(token, project_id, platform="imessage")except Exception as e:diff --git a/plugins/platforms/photon/cli.py b/plugins/platforms/photon/cli.pyindex 2734c186636..f2c52320424 100644--- a/plugins/platforms/photon/cli.py+++ b/plugins/platforms/photon/cli.py@@ -45,9 +45,7 @@ def register_cli(parser: argparse.ArgumentParser) -> None:def dispatch(args: argparse.Namespace) -> int:sub = getattr(args, "photon_command", None)- if sub is None:- return _cmd_status(args) # no subcommand — show status by default- handler = _COMMANDS.get(sub)+ handler = _cmd_status if sub is None else _COMMANDS.get(sub) # no subcommand — status by defaultif handler is None:print(f"unknown subcommand: {sub}", file=sys.stderr)return 2@@ -83,20 +81,16 @@ def _setup_token(args: argparse.Namespace) -> Optional[str]:print("[1/5] Checking existing Photon token...")if photon_auth.check_photon_token_valid(token):print(" ✓ token is valid")- else:- print(" ✗ token is stale (dashboard rejected it) — re-authenticating")- photon_auth.clear_photon_token()- token = None+ print("[1/5] Reusing existing Photon token")+ return token+ print(" ✗ token is stale (dashboard rejected it) — re-authenticating")+ photon_auth.clear_photon_token()+ print("[1/5] No valid Photon token found — running device login...")+ if _run_device_login(args) != 0:+ return None+ token = photon_auth.load_photon_token()if not token:- print("[1/5] No valid Photon token found — running device login...")- if _run_device_login(args) != 0:- return None- token = photon_auth.load_photon_token()- if not token:- print("login completed but token was not stored", file=sys.stderr)- return None- else:- print("[1/5] Reusing existing Photon token")+ print("login completed but token was not stored", file=sys.stderr)return token@@ -106,16 +100,13 @@ def _setup_project(token: str, name: str) -> Optional[str]:try:if dashboard_id:print("[2/5] Reusing configured Photon project")+ elif (existing := photon_auth.find_project_by_name(token, name)) and existing.get("id"):+ dashboard_id = existing["id"]+ print(f"[2/5] Found existing project '{name}'")else:- existing = photon_auth.find_project_by_name(token, name)- if existing and existing.get("id"):- dashboard_id = existing["id"]- print(f"[2/5] Found existing project '{name}'")- else:- print(f"[2/5] Creating Photon project '{name}'...")- created = photon_auth.create_project(token, name=name)- dashboard_id = created.get("id")- print(" ✓ project created")+ print(f"[2/5] Creating Photon project '{name}'...")+ dashboard_id = photon_auth.create_project(token, name=name).get("id")+ print(" ✓ project created")except Exception as e:print(f"project setup failed: {e}", file=sys.stderr)return None@@ -156,14 +147,10 @@ def _setup_credentials(token: str, dashboard_id: str, name: str) -> Optional[strdef _cmd_setup(args: argparse.Namespace) -> int:- token = _setup_token(args)- if not token:- return 1name = args.project_name or photon_auth.DEFAULT_PROJECT_NAME- dashboard_id = _setup_project(token, name)- if not dashboard_id:- return 1- secret = _setup_credentials(token, dashboard_id, name)+ token = _setup_token(args)+ dashboard_id = token and _setup_project(token, name)+ secret = dashboard_id and _setup_credentials(token, dashboard_id, name)if not secret:return 1# 4. Register the operator's phone number as a Spectrum user (idempotent).@@ -199,11 +186,11 @@ def _cmd_setup(args: argparse.Namespace) -> int:except Exception as e:print(f" (could not fetch the assigned line: {e})", file=sys.stderr)if agent_number:- print()- print(color("┌─ Your agent's iMessage number ───────────────────────────────", Colors.GREEN))- print(color("│ 📱 ", Colors.GREEN) + color(str(agent_number), Colors.GREEN, Colors.BOLD))- print(color("│ Text this number from your phone to talk to your agent.", Colors.GREEN))- print(color("└──────────────────────────────────────────────────────────────", Colors.GREEN))+ print("\n" + "\n".join((+ color("┌─ Your agent's iMessage number ───────────────────────────────", Colors.GREEN),+ color("│ 📱 ", Colors.GREEN) + color(str(agent_number), Colors.GREEN, Colors.BOLD),+ color("│ Text this number from your phone to talk to your agent.", Colors.GREEN),+ color("└──────────────────────────────────────────────────────────────", Colors.GREEN))))else:print(" No iMessage line assigned yet — check the Photon dashboard.")if registered_phone:@@ -319,15 +306,14 @@ def _install_sidecar() -> int:if proc.returncode != 0:print(f" npm ci failed — falling back to: {npm} install")proc = _run("install")+ error = (proc.stderr or "").strip()[:_NPM_ERROR_LOG_MAX_CHARS] # bounded to what check_requirements surfacesif proc.returncode != 0:print("npm install failed", file=sys.stderr)- 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")- else:- with contextlib.suppress(OSError):+ with contextlib.suppress(OSError):+ if proc.returncode == 0:_npm_error_log().unlink()+ elif error:+ _npm_error_log().write_text(error, encoding="utf-8")return proc.returncode