Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 96 additions & 0 deletions gateway/platform_routing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
"""
Platform routing helpers extracted from ``gateway/run.py``.

These functions answer "which platform is this / where does this go" questions
used by the gateway runner and the ``/sethome`` slash command: normalizing a
platform identity, deciding which surfaces must keep raw text, mapping a
platform to its config key or home-channel env var, and checking whether a
token-authenticated platform actually has a usable credential.

They were extracted verbatim from the gateway god-file so the routing policy
lives in one focused, independently testable module. ``gateway/run.py``
re-exports every name for backward compatibility — external importers
(``gateway/slash_commands.py``, tests) keep working unchanged.
"""

from typing import Any, Dict, Optional

from gateway.config import Platform

# Surfaces that consume gateway text programmatically (CLI/TUI "local"
# diagnostics, API JSON, webhook payloads) and therefore must keep RAW
# status/error text. EVERY other platform is a human-facing chat surface
# where operational lifecycle/provider-error noise (and any secrets in it)
# must be suppressed or sanitized. Widens #28533's Telegram-only filter to
# all chat gateways (#39293). Fail-closed: unknown/empty platform -> chat.
_GATEWAY_RAW_TEXT_PLATFORMS = frozenset(
{"local", "api_server", "webhook", "msgraph_webhook"}
)


def _gateway_platform_value(platform: Any) -> str:
"""Return a normalized gateway platform value for enums or raw strings."""
return str(getattr(platform, "value", platform) or "").strip().lower()


def _gateway_surface_passes_raw_text(platform: Any) -> bool:
"""True only for programmatic/local surfaces that must keep raw text."""
return _gateway_platform_value(platform) in _GATEWAY_RAW_TEXT_PLATFORMS


def _non_conversational_metadata(
metadata: Optional[Dict[str, Any]] = None,
*,
platform: Any = None,
) -> Optional[Dict[str, Any]]:
"""Mark Discord lifecycle/status sends without changing other platforms."""
if _gateway_platform_value(platform) != "discord":
return metadata
merged = dict(metadata or {})
merged["non_conversational"] = True
return merged


def _home_target_env_var(platform_name: str) -> str:
"""Return the configured home-target env var for a platform.

Consults built-in ``_HOME_TARGET_ENV_VARS`` first, then the plugin
registry via ``cron.scheduler._resolve_home_env_var``, then falls back
to ``<PLATFORM>_HOME_CHANNEL`` for unknown names.
"""
from cron.scheduler import _resolve_home_env_var

resolved = _resolve_home_env_var(platform_name)
if resolved:
return resolved
return f"{platform_name.upper()}_HOME_CHANNEL"


def _home_thread_env_var(platform_name: str) -> str:
"""Return the optional thread/topic env var for a platform home target."""
return f"{_home_target_env_var(platform_name)}_THREAD_ID"


def _platform_has_bot_credential(platform: "Platform", platform_config: "PlatformConfig") -> bool:
"""Return True when a token-authenticated platform has a usable bot credential.

Platforms that do not use ``PlatformConfig.token`` always return True so we
never skip them here (Signal session paths, port-binding HTTP adapters, etc.).
"""
from gateway.config import PLATFORM_TOKEN_ENV_NAMES

if platform not in PLATFORM_TOKEN_ENV_NAMES:
return True
token = getattr(platform_config, "token", None) or ""
if isinstance(token, str) and token.strip():
return True
# Some adapters also accept api_key as the primary credential.
api_key = getattr(platform_config, "api_key", None) or ""
if isinstance(api_key, str) and api_key.strip():
return True
return False


def _platform_config_key(platform: "Platform") -> str:
"""Map a Platform enum to its config.yaml key (LOCAL→"cli", rest→enum value)."""
return "cli" if platform == Platform.LOCAL else platform.value
90 changes: 12 additions & 78 deletions gateway/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,21 +205,8 @@ def _gateway_compression_progress_notices_enabled() -> bool:
pass
return False

# Surfaces that consume gateway text programmatically (CLI/TUI "local"
# diagnostics, API JSON, webhook payloads) and therefore must keep RAW
# status/error text. EVERY other platform is a human-facing chat surface
# where operational lifecycle/provider-error noise (and any secrets in it)
# must be suppressed or sanitized. Widens #28533's Telegram-only filter to
# all chat gateways (#39293). Fail-closed: unknown/empty platform -> chat.
_GATEWAY_RAW_TEXT_PLATFORMS = frozenset(
{"local", "api_server", "webhook", "msgraph_webhook"}
)


def _gateway_surface_passes_raw_text(platform: Any) -> bool:
"""True only for programmatic/local surfaces that must keep raw text."""
return _gateway_platform_value(platform) in _GATEWAY_RAW_TEXT_PLATFORMS

# Extracted to gateway/platform_routing.py (re-exported below for backward
# compatibility — external importers use gateway.run._gateway_* names).

_GATEWAY_PROVIDER_ERROR_RE = re.compile(
r"(" # infrastructure/provider error preambles, not ordinary assistant prose
Expand Down Expand Up @@ -325,24 +312,6 @@ def _ensure_windows_gateway_venv_imports() -> None:
return


def _gateway_platform_value(platform: Any) -> str:
"""Return a normalized gateway platform value for enums or raw strings."""
return str(getattr(platform, "value", platform) or "").strip().lower()


def _non_conversational_metadata(
metadata: Optional[Dict[str, Any]] = None,
*,
platform: Any = None,
) -> Optional[Dict[str, Any]]:
"""Mark Discord lifecycle/status sends without changing other platforms."""
if _gateway_platform_value(platform) != "discord":
return metadata
merged = dict(metadata or {})
merged["non_conversational"] = True
return merged


def _seed_hygiene_system_prompt(
agent: Any,
session_row: Optional[Dict[str, Any]],
Expand Down Expand Up @@ -1650,26 +1619,6 @@ def _ensure_ssl_certs() -> None:
os.environ["SSL_CERT_FILE"] = candidate
return

def _home_target_env_var(platform_name: str) -> str:
"""Return the configured home-target env var for a platform.

Consults built-in ``_HOME_TARGET_ENV_VARS`` first, then the plugin
registry via ``cron.scheduler._resolve_home_env_var``, then falls back
to ``<PLATFORM>_HOME_CHANNEL`` for unknown names.
"""
from cron.scheduler import _resolve_home_env_var

resolved = _resolve_home_env_var(platform_name)
if resolved:
return resolved
return f"{platform_name.upper()}_HOME_CHANNEL"


def _home_thread_env_var(platform_name: str) -> str:
"""Return the optional thread/topic env var for a platform home target."""
return f"{_home_target_env_var(platform_name)}_THREAD_ID"


def _restart_notification_pending() -> bool:
"""Return True when a /restart completion marker is waiting to be delivered."""
return (_hermes_home / ".restart_notify.json").exists()
Expand Down Expand Up @@ -1887,26 +1836,6 @@ def load_gateway_config_for_runner() -> "GatewayConfig":
return cfg


def _platform_has_bot_credential(platform: "Platform", platform_config: "PlatformConfig") -> bool:
"""Return True when a token-authenticated platform has a usable bot credential.

Platforms that do not use ``PlatformConfig.token`` always return True so we
never skip them here (Signal session paths, port-binding HTTP adapters, etc.).
"""
from gateway.config import PLATFORM_TOKEN_ENV_NAMES

if platform not in PLATFORM_TOKEN_ENV_NAMES:
return True
token = getattr(platform_config, "token", None) or ""
if isinstance(token, str) and token.strip():
return True
# Some adapters also accept api_key as the primary credential.
api_key = getattr(platform_config, "api_key", None) or ""
if isinstance(api_key, str) and api_key.strip():
return True
return False


_DOCKER_VOLUME_SPEC_RE = re.compile(r"^(?P<host>.+):(?P<container>/[^:]+?)(?::(?P<options>[^:]+))?$")
_DOCKER_MEDIA_OUTPUT_CONTAINER_PATHS = {"/output", "/outputs"}

Expand Down Expand Up @@ -2256,6 +2185,16 @@ def _platform_has_bot_credential(platform: "Platform", platform_config: "Platfor
)
from gateway.authz_mixin import GatewayAuthorizationMixin
from gateway.kanban_watchers import GatewayKanbanWatchersMixin
from gateway.platform_routing import (
_GATEWAY_RAW_TEXT_PLATFORMS,
_gateway_platform_value,
_gateway_surface_passes_raw_text,
_home_target_env_var,
_home_thread_env_var,
_non_conversational_metadata,
_platform_config_key,
_platform_has_bot_credential,
)
from gateway.slash_commands import GatewaySlashCommandsMixin
from gateway.turn_context import TurnContext
from gateway.platforms.base import (
Expand Down Expand Up @@ -3001,11 +2940,6 @@ def _check_unavailable_skill(command_name: str) -> str | None:
return None


def _platform_config_key(platform: "Platform") -> str:
"""Map a Platform enum to its config.yaml key (LOCAL→"cli", rest→enum value)."""
return "cli" if platform == Platform.LOCAL else platform.value


def _teams_pipeline_plugin_enabled() -> bool:
"""Return True when the standalone Teams pipeline plugin is enabled."""
config = _load_gateway_config()
Expand Down
144 changes: 144 additions & 0 deletions tests/gateway/test_platform_routing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
"""Tests for gateway/platform_routing.py — the platform routing helper cluster
extracted from gateway/run.py (see issue #54962 / #55138).

The helpers are pure policy functions, so these tests exercise the real
imports and real call paths (no mocks). A second block asserts that
gateway/run.py still re-exports every name, because external importers
(gateway/slash_commands.py, the /sethome tests, multiplex tests) import these
helpers from ``gateway.run`` and must keep working unchanged.
"""

from gateway.config import Platform, PlatformConfig
from gateway import platform_routing as pr


# --- _gateway_platform_value ----------------------------------------------

def test_platform_value_normalizes_enum():
assert pr._gateway_platform_value(Platform.TELEGRAM) == "telegram"
assert pr._gateway_platform_value(Platform.WHATSAPP_CLOUD) == "whatsapp_cloud"


def test_platform_value_normalizes_raw_strings():
assert pr._gateway_platform_value("Telegram") == "telegram"
assert pr._gateway_platform_value(" DISCORD ") == "discord"


def test_platform_value_fail_closed_on_empty():
# Unknown/empty platform must not match any surface.
assert pr._gateway_platform_value(None) == ""
assert pr._gateway_platform_value("") == ""


# --- _gateway_surface_passes_raw_text -------------------------------------

def test_raw_text_surfaces_pass_through():
for surface in ("local", "api_server", "webhook", "msgraph_webhook"):
assert pr._gateway_surface_passes_raw_text(surface)


def test_chat_surfaces_do_not_pass_raw_text():
for chat in ("telegram", "discord", "slack", "whatsapp"):
assert not pr._gateway_surface_passes_raw_text(chat)


def test_raw_text_check_fail_closed_on_unknown():
assert not pr._gateway_surface_passes_raw_text(None)
assert not pr._gateway_surface_passes_raw_text("")


# --- _non_conversational_metadata -----------------------------------------

def test_non_conversational_marker_applies_only_to_discord():
metadata = {"thread_id": "t1"}
marked = pr._non_conversational_metadata(metadata, platform=Platform.DISCORD)
assert marked["non_conversational"] is True
assert marked["thread_id"] == "t1"
# Original dict is not mutated.
assert "non_conversational" not in metadata


def test_non_conversational_marker_skips_other_platforms():
metadata = {"thread_id": "t1"}
for platform in (Platform.TELEGRAM, "slack", None):
assert pr._non_conversational_metadata(metadata, platform=platform) is metadata


def test_non_conversational_marker_creates_dict_when_absent():
marked = pr._non_conversational_metadata(None, platform="discord")
assert marked == {"non_conversational": True}


# --- _home_target_env_var / _home_thread_env_var --------------------------

def test_home_target_env_var_known_conventions():
# Matrix and Email deviate from the {PLATFORM}_HOME_CHANNEL convention
# (see tests/gateway/test_home_target_env_var.py and PR #12698).
assert pr._home_target_env_var("matrix") == "MATRIX_HOME_ROOM"
assert pr._home_target_env_var("email") == "EMAIL_HOME_ADDRESS"


def test_home_target_env_var_fallback_suffix():
assert pr._home_target_env_var("signal") == "SIGNAL_HOME_CHANNEL"


def test_home_thread_env_var_suffix():
assert pr._home_thread_env_var("matrix") == "MATRIX_HOME_ROOM_THREAD_ID"
assert pr._home_thread_env_var("signal") == "SIGNAL_HOME_CHANNEL_THREAD_ID"


# --- _platform_has_bot_credential -----------------------------------------

def test_token_platform_without_credential_fails():
assert not pr._platform_has_bot_credential(Platform.TELEGRAM, PlatformConfig())


def test_token_platform_with_token_or_api_key_passes():
assert pr._platform_has_bot_credential(
Platform.TELEGRAM, PlatformConfig(token="123:ABC")
)
assert pr._platform_has_bot_credential(
Platform.DISCORD, PlatformConfig(api_key="abc")
)


def test_non_token_platform_always_passes():
# Signal session paths / port-binding HTTP adapters don't use token.
assert pr._platform_has_bot_credential(Platform.SIGNAL, PlatformConfig())


# --- _platform_config_key -------------------------------------------------

def test_platform_config_key_maps_local_to_cli():
assert pr._platform_config_key(Platform.LOCAL) == "cli"


def test_platform_config_key_uses_enum_value_otherwise():
assert pr._platform_config_key(Platform.TELEGRAM) == "telegram"
assert pr._platform_config_key(Platform.API_SERVER) == "api_server"


# --- gateway/run.py re-exports (backward compatibility) -------------------

def test_run_py_reexports_routing_helpers():
from gateway.run import (
_GATEWAY_RAW_TEXT_PLATFORMS,
_gateway_platform_value,
_gateway_surface_passes_raw_text,
_home_target_env_var,
_home_thread_env_var,
_non_conversational_metadata,
_platform_config_key,
_platform_has_bot_credential,
)

assert _GATEWAY_RAW_TEXT_PLATFORMS == pr._GATEWAY_RAW_TEXT_PLATFORMS
assert _gateway_platform_value("Telegram") == "telegram"
assert _gateway_surface_passes_raw_text("local") is True
assert _home_target_env_var("matrix") == "MATRIX_HOME_ROOM"
assert _home_thread_env_var("signal") == "SIGNAL_HOME_CHANNEL_THREAD_ID"
assert _non_conversational_metadata(None, platform="discord") == {
"non_conversational": True
}
assert _platform_config_key(Platform.LOCAL) == "cli"
assert _platform_has_bot_credential(Platform.TELEGRAM, PlatformConfig()) is False
Loading