Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat: integrate Switch Trust guardrails before every message send
Timo Bozsolik-Torresc238a75c1478
diff --git a/console/packages/plugins/src/switch-skill/SKILL.md b/console/packages/plugins/src/switch-skill/SKILL.mdindex e000d5668..9cf4632c3 100644--- a/console/packages/plugins/src/switch-skill/SKILL.md+++ b/console/packages/plugins/src/switch-skill/SKILL.md@@ -251,6 +251,20 @@ you get back from `send_targeted_message` is `not_permitted` in that agent'sthan sending again. Commands are covered too, so `!reset` on a restrictedagent is declined the same way.+## Switch Trust guardrails++A deployment may run every message through **Switch Trust**, a guardrails+service, before it is sent. This is unrelated to the addressing policy above:+addressing refusals always reach the room; a guardrails block does not.++If your content is blocked, `post_message`, `send_targeted_message`,+`update_status` and `finalise_task` fail with an error instead of posting —+and a notice appears in the room in place of what you tried to send, so other+participants see that something was withheld rather than nothing happening.+Rephrase and retry, or drop it. A human's message can be blocked the same way;+when it is, it never reaches the room or you at all, and the sender is told on+their own platform instead.+## Questions and approvalsNative question forms can be answered in the Console or from the room. Thediff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.pyindex 4a5c9f74d..395c52adc 100644--- a/core/switch_core/bridges/agent/api/handlers.py+++ b/core/switch_core/bridges/agent/api/handlers.py@@ -121,6 +121,7 @@ from switch_core.db.stores.api_key_store import ApiKeyStorefrom switch_core.db.stores.feature_flag_store import FeatureFlagStorefrom switch_core.feature_flags import is_known_flagfrom switch_core.gateway.known_agents import KNOWN_AGENTS+from switch_core.trust.client import GuardrailBlockedErrorfrom switch_core.version import switch_core_versionlogger = logging.getLogger(__name__)@@ -481,6 +482,8 @@ async def send_message(event_id = await protocol.send_message(agent.id, req.room_id, req.content)except BudgetExceeded as e:raise HTTPException(status_code=429, detail=str(e)) from e+ except GuardrailBlockedError as e:+ raise HTTPException(status_code=422, detail=str(e)) from eexcept ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from eexcept PermissionError as e:@@ -671,6 +674,8 @@ async def update_status(if req.detail:try:await protocol.update_status(agent.id, req.room_id, req.detail)+ except GuardrailBlockedError as e:+ raise HTTPException(status_code=422, detail=str(e)) from eexcept ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from eexcept PermissionError as e:@@ -1557,6 +1562,8 @@ async def finalise_task(try:await protocol.finalise_task(agent.id, req.task_id, req.outcome)task = await protocol.get_task(agent.id, req.task_id)+ except GuardrailBlockedError as e:+ raise HTTPException(status_code=422, detail=str(e)) from eexcept ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from eexcept PermissionError as e:diff --git a/core/switch_core/bridges/agent/api/operations.py b/core/switch_core/bridges/agent/api/operations.pyindex 6afed7066..952746706 100644--- a/core/switch_core/bridges/agent/api/operations.py+++ b/core/switch_core/bridges/agent/api/operations.py@@ -44,6 +44,7 @@ from switch_core.observability.catalogue import (BRIDGE_EVENTS_IN,)from switch_core.observability.metrics import metrics+from switch_core.trust.client import GuardrailBlockedErrorlogger = logging.getLogger(__name__)@@ -314,6 +315,8 @@ async def post_operation(raise HTTPException(status_code=403, detail=exc.detail) from excexcept BudgetExceeded as exc:raise HTTPException(status_code=429, detail=str(exc)) from exc+ except GuardrailBlockedError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from excexcept PermissionError as exc:raise HTTPException(status_code=403, detail=str(exc)) from excexcept ValueError as exc:diff --git a/core/switch_core/bridges/agent/app.py b/core/switch_core/bridges/agent/app.pyindex 4be9f200e..960e7a9a6 100644--- a/core/switch_core/bridges/agent/app.py+++ b/core/switch_core/bridges/agent/app.py@@ -53,6 +53,7 @@ from switch_core.session_activity.outcomes import ApprovalOutcomesfrom switch_core.sessions.errors import SessionErrorfrom switch_core.sessions.http import session_error_responsefrom switch_core.telemetry import TelemetryService+from switch_core.trust.client import TrustClientlogger = logging.getLogger(__name__)@@ -75,6 +76,7 @@ def create_agent_bridge_app(config: SwitchConfig,approval_outcomes: ApprovalOutcomes,controller_auth: ControllerAuthenticator | None,+ trust_client: TrustClient,connections: AgentConnectionRegistry | None = None,telemetry: TelemetryService | None = None,) -> tuple[FastAPI, AgentCore]:@@ -111,6 +113,7 @@ def create_agent_bridge_app(session_factory=session_factory,config=config,approval_outcomes=approval_outcomes,+ trust_client=trust_client,telemetry=telemetry,)diff --git a/core/switch_core/bridges/agent/dependencies.py b/core/switch_core/bridges/agent/dependencies.pyindex fc47b3d0f..026dd17d0 100644--- a/core/switch_core/bridges/agent/dependencies.py+++ b/core/switch_core/bridges/agent/dependencies.py@@ -28,6 +28,7 @@ from switch_core.telemetry.session_start import (SessionStartLimiter,default_session_start_limiter,)+from switch_core.trust.client import TrustClientif TYPE_CHECKING:from switch_core.session_activity.outcomes import ApprovalOutcomes@@ -54,6 +55,7 @@ def init_dependencies(session_factory: Any,config: Any,approval_outcomes: ApprovalOutcomes,+ trust_client: TrustClient,telemetry: TelemetryService | None = None,) -> None:_state["agent_store"] = agent_store@@ -73,6 +75,7 @@ def init_dependencies(_state["session_factory"] = session_factory_state["config"] = config_state["telemetry"] = telemetry+ _state["trust_client"] = trust_client_state["session_start_limiter"] = default_session_start_limiter()_state["protocol"] = AgentCore(@@ -93,6 +96,7 @@ def init_dependencies(session_factory=session_factory,config=config,approval_outcomes=approval_outcomes,+ trust_client=trust_client,telemetry=telemetry,)diff --git a/core/switch_core/bridges/agent/protocol/agent_core.py b/core/switch_core/bridges/agent/protocol/agent_core.pyindex f642c35cf..80a35595d 100644--- a/core/switch_core/bridges/agent/protocol/agent_core.py+++ b/core/switch_core/bridges/agent/protocol/agent_core.py@@ -60,8 +60,10 @@ from switch_core.bridges.agent.registration_bootstrap import ()from switch_core.bridges.resource.service import ResourceServicefrom switch_core.budgets import BudgetGuard+from switch_core.clients.actor import SystemActorfrom switch_core.clients.admin_messages import PLATFORM_MARKER as _PLATFORM_MARKERfrom switch_core.clients.admin_messages import (+ AdminMessageType,platform_on_behalf_of,platform_replies_in_channel,)@@ -119,6 +121,12 @@ from switch_core.tenant_context import current_tenant_id, tenant_scopefrom switch_core.transport import (TransportError,)+from switch_core.trust.client import (+ GuardrailBlockedError,+ NullTrustClient,+ TrustClient,+ check_message,+)if TYPE_CHECKING:from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker@@ -265,6 +273,9 @@ class AgentCore:# None only for the minimal instances tests assemble; the server always# supplies it, and a stream without it simply carries no approval outcomes.approval_outcomes: ApprovalOutcomes | None = None+ # Same reason: a minimal test instance gets a client that allows everything+ # rather than one that needs real config to construct.+ trust_client: TrustClient = NullTrustClient()# Told (tenant_id, agent_id) just before an agent is deleted, while its row# still exists. Set by the process wiring when something outside Core keeps# state about agents that a cascade alone would drop without telling anyone.@@ -290,9 +301,11 @@ class AgentCore:session_factory: async_sessionmaker[AsyncSession],config: SwitchConfig,approval_outcomes: ApprovalOutcomes,+ trust_client: TrustClient,telemetry: TelemetryService | None = None,) -> None:self.telemetry = telemetry+ self.trust_client = trust_clientself.approval_outcomes = approval_outcomes# Pairs session start with session end. Held here because the handler# that starts a session and the registry listener that ends one must@@ -1212,6 +1225,49 @@ class AgentCore:"Failed to post agent activity notice to %s", transport_room_id)+ async def _enforce_trust(+ self, room: RoomDescriptor, content: str, thread_root_id: str | None+ ) -> None:+ """Check agent-authored content against Switch Trust before it is+ sent. Raises `GuardrailBlockedError` on a BLOCKED verdict, having+ already posted a notice in the room in place of the real content."""+ check = await check_message(+ self.trust_client, role="assistant", content=content+ )+ if check.blocked:+ await self._post_trust_blocked_notice(room, thread_root_id)+ raise GuardrailBlockedError(check)++ async def _post_trust_blocked_notice(+ self, room: RoomDescriptor, thread_root_id: str | None+ ) -> None:+ """Tell the room a response was blocked, in place of sending it."""+ admin = next(+ (+ c+ for c in self.client_lifecycle.get_by_type(+ "admin", require_tenant_id()+ )+ if isinstance(c, SystemActor)+ ),+ None,+ )+ if admin is None:+ return+ try:+ await admin.send_admin(+ room.transport_room_id,+ "🚫 A response was blocked by Switch Trust and was not sent.",+ message_type=AdminMessageType.TRUST_BLOCKED,+ thread_root_id=thread_root_id,+ )+ except Exception:+ logger.warning(+ "Could not post a Switch Trust blocked notice in %s",+ room.id,+ exc_info=True,+ )+async def _post_role_change_notice(self, agent_id: str, transport_room_id: str, action: str) -> None:@@ -1258,6 +1314,8 @@ class AgentCore:agent is not a room member, the client is not running, or thread_iddoes not resolve to an event in the room.Raises PermissionError if auth fails (should not happen in same-process).+ Raises GuardrailBlockedError if Switch Trust blocks the content; a+ notice is posted to the room in place of it."""logger.debug("[AGENT-MSG] agent=%s room=%s content=%s", agent_id, room_id, content[:80]@@ -1271,6 +1329,7 @@ class AgentCore:thread_root_id = await self._resolve_thread_root(client, room.transport_room_id, thread_id)+ await self._enforce_trust(room, content, thread_root_id)event_id = await client.send_message(room.transport_room_id,content,@@ -1731,11 +1790,15 @@ class AgentCore:await collaboration_core.handle_outbound_typing(room.id, agent.name, is_typing)async def update_status(self, agent_id: str, room_id: str, detail: str) -> None:- """Send a status message to a room."""+ """Send a status message to a room.++ Raises GuardrailBlockedError if Switch Trust blocks it.+ """room = await self.require_room_member(agent_id, room_id)client = self.client_lifecycle.get_by_agent_id(agent_id)if client is None:raise ValueError("Agent client not running")+ await self._enforce_trust(room, detail, None)await client.send_message(room.transport_room_id, f"*{detail}*", format="markdown", metered=True)@@ -2474,6 +2537,7 @@ class AgentCore:"outcome": outcome,},)+ await self._enforce_trust(room, outcome, None)await client.send_message(room.transport_room_id, outcome, format="markdown", metered=True)diff --git a/core/switch_core/bridges/collaboration/collaboration_core.py b/core/switch_core/bridges/collaboration/collaboration_core.pyindex 4dd397910..f7a40b0a9 100644--- a/core/switch_core/bridges/collaboration/collaboration_core.py+++ b/core/switch_core/bridges/collaboration/collaboration_core.py@@ -83,6 +83,7 @@ from switch_core.transport import (RoomRef,TransportError,)+from switch_core.trust.client import NullTrustClient, TrustClient, check_messageif TYPE_CHECKING:from switch_core.bridges.agent.protocol.agent_connections import (@@ -183,6 +184,7 @@ class CollaborationCore:session_activity_listener: AgentSessionActivityListener,session_activity_service: AgentSessionActivityService,connections: AgentConnectionRegistry,+ trust_client: TrustClient = NullTrustClient(),gateway_public_url: str | None = None,) -> None:self._bridge_id = bridge_id@@ -211,6 +213,7 @@ class CollaborationCore:workspace_consumer_transport_user_id)self._max_attachment_bytes = max_attachment_bytes+ self._trust_client = trust_clientself._channel_to_room: dict[str, tuple[str, str]] = {}self._room_to_channel: dict[tuple[str, str], str] = {}@@ -945,6 +948,25 @@ class CollaborationCore:content = f"{content}\n{notes}" if content.strip() else notesif not msg.attachments:+ check = await check_message(+ self._trust_client, role="user", content=content+ )+ if check.blocked:+ logger.warning(+ "[BRIDGE-IN] message from %s blocked by Switch Trust "+ "(policy=%s) — not relayed into room %s",+ msg.sender_name,+ check.policy_id,+ transport_room_id,+ )+ await self._adapter.admin_message(+ msg.channel_id,+ "🚫 Your message was blocked by Switch Trust and was not "+ "delivered.",+ msg.root_id or msg.message_ref,+ message_type=AdminMessageType.TRUST_BLOCKED.value,+ )+ returnevent_id = await human_actor.send_message(transport_room_id,content,diff --git a/core/switch_core/bridges/collaboration/lifecycle_service.py b/core/switch_core/bridges/collaboration/lifecycle_service.pyindex e8c4e5256..24ed2cda3 100644--- a/core/switch_core/bridges/collaboration/lifecycle_service.py+++ b/core/switch_core/bridges/collaboration/lifecycle_service.py@@ -49,6 +49,7 @@ from switch_core.telemetry.deployment import ()from switch_core.telemetry.snapshot import PLATFORMS, normalise_platformfrom switch_core.tenant_context import current_tenant_id, no_tenant+from switch_core.trust.client import NullTrustClient, TrustClientif TYPE_CHECKING:from switch_core.bridges.agent.protocol.agent_connections import (@@ -306,6 +307,7 @@ class BridgeStartGuard(Protocol):class CollaborationBridgeLifecycleService:# See RoomService: a test may assemble this without `__init__`._telemetry: TelemetryService | None = None+ _trust_client: TrustClient = NullTrustClient()_connect_failures: dict[str, int] = {}_bridge_facts: dict[str, tuple[str, object]] = {}_preconfigured: set[str] = set()@@ -330,6 +332,7 @@ class CollaborationBridgeLifecycleService:session_activity_service: AgentSessionActivityService,connections: AgentConnectionRegistry,telemetry: TelemetryService | None = None,+ trust_client: TrustClient = NullTrustClient(),) -> None:self._bridge_store = bridge_storeself._external_user_store = external_user_store@@ -339,6 +342,7 @@ class CollaborationBridgeLifecycleService:self._client_store = client_storeself._client_lifecycle = client_lifecycleself._telemetry = telemetry+ self._trust_client = trust_clientself._room_service = room_serviceself._provisioning = provisioningself._session_factory = session_factory@@ -1026,6 +1030,7 @@ class CollaborationBridgeLifecycleService:session_activity_listener=self._session_activity_listener,session_activity_service=self._session_activity_service,connections=self._connections,+ trust_client=self._trust_client,)workspace_consumer = WorkspaceConsumer(diff --git a/core/switch_core/clients/admin_messages.py b/core/switch_core/clients/admin_messages.pyindex 95a7ba49c..9bfe6c880 100644--- a/core/switch_core/clients/admin_messages.py+++ b/core/switch_core/clients/admin_messages.py@@ -106,6 +106,7 @@ class AdminMessageType(StrEnum):SELF_MENTION_UNALIASED = "self_mention_unaliased"NO_AGENTS = "no_agents"RUN_NOTICE = "run_notice"+ TRUST_BLOCKED = "trust_blocked"def admin_extra_content(message_type: AdminMessageType | None) -> dict[str, object]:diff --git a/core/switch_core/config.py b/core/switch_core/config.pyindex 6ea03c4fe..1b5ec01db 100644--- a/core/switch_core/config.py+++ b/core/switch_core/config.py@@ -429,6 +429,27 @@ class SwitchConfig(BaseSettings):# move every deeplink along with it.messaging_public_url: str | None = None+ # Switch Trust: a guardrails service that checks a message against a+ # policy before it is sent, blocking it on a BLOCKED verdict. Base URL,+ # no path — `/guardrails/check` (the check-only route added in+ # https://github.com/sandbox-quantum/hoot/pull/2397) is appended, the same+ # convention `otlp_endpoint`/`telemetry_endpoint` follow. Defaults to the+ # company API; override for a different deployment or a local stack.+ switch_trust_endpoint: str = "https://api.flintai.dev"++ # Authenticates with Switch Trust and names which policy to run. Both+ # unset (the default) is what turns the whole feature off — see+ # `trust_enabled` — and setting one without the other is a startup error,+ # the same all-or-nothing shape as the distributed Slack/Discord app+ # config above.+ switch_trust_api_key: str | None = None+ switch_trust_policy_id: str | None = None++ # How long to wait on a check before giving up and letting the message+ # through unchecked (fail open — see `trust/client.py`). Short, because+ # this gates every message Switch sends.+ switch_trust_timeout_seconds: float = 2.0+# Upper bound on a single attachment an agent may post to a room (and that# a collaboration bridge will relay out). Uploads over this raise instead# of being truncated or silently dropped.@@ -1041,6 +1062,56 @@ class SwitchConfig(BaseSettings):)return self+ @model_validator(mode="after")+ def _validate_switch_trust(self) -> "SwitchConfig":+ required = (self.switch_trust_api_key, self.switch_trust_policy_id)+ set_count = sum(1 for value in required if value)+ if 0 < set_count < len(required):+ raise ValueError(+ "Partial Switch Trust config: set both SWITCH_TRUST_API_KEY "+ "and SWITCH_TRUST_POLICY_ID, or neither."+ )+ if self.switch_trust_endpoint != self.switch_trust_endpoint.strip():+ raise ValueError(+ "SWITCH_TRUST_ENDPOINT has leading or trailing whitespace: "+ f"{self.switch_trust_endpoint!r}."+ )+ endpoint = urlsplit(self.switch_trust_endpoint)+ if endpoint.scheme not in ("http", "https"):+ raise ValueError(+ "SWITCH_TRUST_ENDPOINT must be an http(s) URL, got "+ f"{self.switch_trust_endpoint!r}."+ )+ if not endpoint.netloc:+ raise ValueError(+ "SWITCH_TRUST_ENDPOINT must include a host, got "+ f"{self.switch_trust_endpoint!r}."+ )+ if endpoint.path.strip("/"):+ raise ValueError(+ "SWITCH_TRUST_ENDPOINT is the service's base URL and "+ "/guardrails/check is appended to it, so it must have no path "+ f"of its own. Got {self.switch_trust_endpoint!r} — drop the "+ f"{endpoint.path!r}."+ )+ if endpoint.query or endpoint.fragment:+ raise ValueError(+ "SWITCH_TRUST_ENDPOINT must be a bare base URL: a query or "+ "fragment is dropped when /guardrails/check is appended, so "+ f"it would silently never be sent. Got "+ f"{self.switch_trust_endpoint!r}."+ )+ if self.switch_trust_timeout_seconds <= 0:+ raise ValueError(+ "SWITCH_TRUST_TIMEOUT_SECONDS must be positive, got "+ f"{self.switch_trust_timeout_seconds!r}."+ )+ return self++ @property+ def trust_enabled(self) -> bool:+ return bool(self.switch_trust_api_key and self.switch_trust_policy_id)+@propertydef gateway_oidc_enabled(self) -> bool:return bool(diff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex bc0595b8f..09b67a569 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -169,6 +169,7 @@ from switch_core.telemetry.setup import build_telemetryfrom switch_core.tenant_context import no_tenantfrom switch_core.transport.ephemeral import EphemeralBusfrom switch_core.transport.invites import InviteBus+from switch_core.trust.setup import build_trust_clientfrom switch_core.version import switch_core_versionlogger = logging.getLogger(__name__)@@ -485,6 +486,9 @@ async def run(config: SwitchConfig) -> None:config, session_factory, switch_core_version())+ # ── Switch Trust guardrails ──────────────────────────────────────────────+ trust_client, trust_http = build_trust_client(config)+# ── Resource service ─────────────────────────────────────────────────────resource_service = ResourceService(reference_store=reference_store,@@ -595,6 +599,7 @@ async def run(config: SwitchConfig) -> None:session_activity_service=AgentSessionActivityService(session_factory),connections=connections,telemetry=telemetry,+ trust_client=trust_client,)# ── Room service ─────────────────────────────────────────────────────────@@ -657,6 +662,7 @@ async def run(config: SwitchConfig) -> None:controller_auth=management.authenticator if management is not None else None,connections=connections,telemetry=telemetry,+ trust_client=trust_client,)# Every close reports, whichever of the five paths did it — and only for a# connection the handler saw start.@@ -876,6 +882,8 @@ async def run(config: SwitchConfig) -> None:# product event is the least valuable thing in it.await protocol.sessions.aclose()await _drain_telemetry(telemetry, telemetry_http)+ if trust_http is not None:+ await trust_http.aclose()await observability.aclose()# So a probe during teardown gets a 503 rather than the last# cached answer, which may still say ready.diff --git a/core/switch_core/trust/__init__.py b/core/switch_core/trust/__init__.pynew file mode 100644index 000000000..0884191bc--- /dev/null+++ b/core/switch_core/trust/__init__.py@@ -0,0 +1,21 @@+from switch_core.trust.client import (+ GuardrailBlockedError,+ GuardrailsCheckError,+ HttpTrustClient,+ NullTrustClient,+ TrustCheckResult,+ TrustClient,+ TrustFinding,+ check_message,+)++__all__ = [+ "GuardrailBlockedError",+ "GuardrailsCheckError",+ "HttpTrustClient",+ "NullTrustClient",+ "TrustCheckResult",+ "TrustClient",+ "TrustFinding",+ "check_message",+]diff --git a/core/switch_core/trust/client.py b/core/switch_core/trust/client.pynew file mode 100644index 000000000..7e813b98c--- /dev/null+++ b/core/switch_core/trust/client.py@@ -0,0 +1,154 @@+"""Switch Trust: a guardrails service checked before a message is sent.++Calls the check-only endpoint added in+https://github.com/sandbox-quantum/hoot/pull/2397 — a provider-agnostic+`messages` array in, a block/allow verdict out, no LLM provider in the loop.+`NullTrustClient` is what runs when the feature is off (`SwitchConfig.+trust_enabled` is False): a client that always allows, so no call site has to+ask whether the feature is on — the same shape as `telemetry/sink.py`'s+`NullSink`.+"""++from __future__ import annotations++import logging+from dataclasses import dataclass+from typing import Any, Literal, Protocol++import httpx++logger = logging.getLogger(__name__)++_BLOCKED_OUTCOME = "GUARDRAIL_RESULT_OUTCOME_BLOCKED"++Role = Literal["user", "assistant"]+++class GuardrailsCheckError(RuntimeError):+ """A check did not complete: network error, timeout, or a non-2xx answer."""+++class GuardrailBlockedError(Exception):+ """A message was refused by the guardrails policy.++ Carries the verdict so a caller can tell the room or the agent why,+ without re-deriving it.+ """++ def __init__(self, result: TrustCheckResult) -> None:+ self.result = result+ categories = (+ ", ".join(f.category for f in result.findings) or "policy violation"+ )+ super().__init__(f"blocked by Switch Trust ({categories})")+++@dataclass(frozen=True)+class TrustFinding:+ """One detector hit. Deliberately narrower than the wire shape: no+ `detected_string` — that is often the sensitive text itself (an email, a+ secret), and this travels into log lines and blocked-message notices."""++ category: str+ detector_name: str+ severity: str | None+++@dataclass(frozen=True)+class TrustCheckResult:+ blocked: bool+ policy_id: str | None+ policy_name: str | None+ findings: tuple[TrustFinding, ...] = ()+++class TrustClient(Protocol):+ async def check(self, *, role: Role, content: str) -> TrustCheckResult: ...+++class NullTrustClient:+ """Off: every message is allowed, and no request is made."""++ async def check(self, *, role: Role, content: str) -> TrustCheckResult:+ return TrustCheckResult(blocked=False, policy_id=None, policy_name=None)+++class HttpTrustClient:+ """Posts to `{base_url}/guardrails/check`. One client, reused.++ No history, no tool calls: v1 checks the one message being sent, as a+ `messages` array of length one. Raises `GuardrailsCheckError` on any+ failure — whether that is treated as blocking or fail-open is a decision+ for the caller (`check_message` below), not this client.+ """++ def __init__(+ self,+ *,+ base_url: str,+ api_key: str,+ policy_id: str,+ timeout_seconds: float,+ client: httpx.AsyncClient,+ ) -> None:+ self._url = base_url.rstrip("/") + "/guardrails/check"+ self._headers = {+ "Content-Type": "application/json",+ "x-guardrails-policy-id": policy_id,+ "x-flintai-api-key": api_key,+ }+ self._timeout_seconds = timeout_seconds+ self._client = client++ async def check(self, *, role: Role, content: str) -> TrustCheckResult:+ payload = {"messages": [{"role": role, "content": content}]}+ try:+ response = await self._client.post(+ self._url,+ json=payload,+ headers=self._headers,+ timeout=self._timeout_seconds,+ )+ except httpx.HTTPError as error:+ raise GuardrailsCheckError(f"POST {self._url} failed: {error}") from error+ if response.status_code >= 400:+ raise GuardrailsCheckError(+ f"POST {self._url} answered {response.status_code}: "+ f"{response.text[:200]}"+ )+ try:+ body: dict[str, Any] = response.json()+ except ValueError as error:+ raise GuardrailsCheckError(+ f"POST {self._url} answered a non-JSON body"+ ) from error+ findings = tuple(+ TrustFinding(+ category=finding.get("category", ""),+ detector_name=finding.get("detector_name", ""),+ severity=finding.get("severity"),+ )+ for finding in body.get("findings") or []+ )+ return TrustCheckResult(+ blocked=body.get("outcome") == _BLOCKED_OUTCOME,+ policy_id=body.get("policy_id"),+ policy_name=body.get("policy_name"),+ findings=findings,+ )+++async def check_message(+ client: TrustClient, *, role: Role, content: str+) -> TrustCheckResult:+ """`client.check`, failing open: a Switch Trust outage degrades to+ unchecked messages rather than to no messaging at all. Logged loudly+ either way, since this is the one place that gap is visible."""+ try:+ return await client.check(role=role, content=content)+ except GuardrailsCheckError:+ logger.warning(+ "Switch Trust check failed; message allowed through unchecked",+ exc_info=True,+ )+ return TrustCheckResult(blocked=False, policy_id=None, policy_name=None)diff --git a/core/switch_core/trust/setup.py b/core/switch_core/trust/setup.pynew file mode 100644index 000000000..d37c53fa4--- /dev/null+++ b/core/switch_core/trust/setup.py@@ -0,0 +1,49 @@+"""Building the Switch Trust client at boot.++One function, so `main.py` does not have to know the difference between a+deployment with guardrails configured and one without — it asks for a client+and gets one either way.+"""++from __future__ import annotations++import logging++import httpx++from switch_core.config import SwitchConfig+from switch_core.trust.client import HttpTrustClient, NullTrustClient, TrustClient++logger = logging.getLogger(__name__)+++def build_trust_client(+ config: SwitchConfig,+) -> tuple[TrustClient, httpx.AsyncClient | None]:+ """The trust client, and its HTTP client so `main` can close it.++ Returns a `NullTrustClient` (no request ever made) unless both+ `SWITCH_TRUST_API_KEY` and `SWITCH_TRUST_POLICY_ID` are set.+ """+ api_key = config.switch_trust_api_key+ policy_id = config.switch_trust_policy_id+ if not api_key or not policy_id:+ logger.info(+ "Switch Trust is off; messages are not checked before sending. Set "+ "SWITCH_TRUST_API_KEY and SWITCH_TRUST_POLICY_ID to turn it on."+ )+ return NullTrustClient(), None++ http_client = httpx.AsyncClient()+ client = HttpTrustClient(+ base_url=config.switch_trust_endpoint,+ api_key=api_key,+ policy_id=policy_id,+ timeout_seconds=config.switch_trust_timeout_seconds,+ client=http_client,+ )+ logger.info(+ "Switch Trust is ON: messages are checked against %s before sending.",+ config.switch_trust_endpoint,+ )+ return client, http_clientdiff --git a/core/tests/benchmarks/server.py b/core/tests/benchmarks/server.pyindex a87f3e662..e6e063e50 100644--- a/core/tests/benchmarks/server.py+++ b/core/tests/benchmarks/server.py@@ -73,6 +73,7 @@ from switch_core.sessions.contract import ApprovalResultfrom switch_core.tenant_context import bind_tenant_id, tenant_scopefrom switch_core.transport.ephemeral import EphemeralBusfrom switch_core.transport.invites import InviteBus+from switch_core.trust.client import NullTrustClientfrom tests.benchmarks.instrumentation import (RequestCounter,TracingMiddleware,@@ -543,6 +544,7 @@ async def _serve(config=config,approval_outcomes=ApprovalOutcomes(activity_listener, activity),controller_auth=None,+ trust_client=NullTrustClient(),connections=connections,)diff --git a/core/tests/integration/conftest.py b/core/tests/integration/conftest.pyindex 600b85dc9..b04c49a8f 100644--- a/core/tests/integration/conftest.py+++ b/core/tests/integration/conftest.py@@ -88,6 +88,7 @@ from switch_core.room_service import RoomServicefrom switch_core.tenant_context import tenant_scopefrom switch_core.transport.ephemeral import EphemeralBusfrom switch_core.transport.invites import InviteBus+from switch_core.trust.client import NullTrustClient# ── Mirrors deploy/local/docker-compose.yml — keep in sync ──────────────────────POSTGRES_IMAGE = "postgres:16-alpine"@@ -628,6 +629,7 @@ async def harness(session_env: SessionEnv) -> AsyncIterator[Harness]:config=config,# Required since #543; no integration test answers an approval.approval_outcomes=MagicMock(),+ trust_client=NullTrustClient(),connections=connections,)diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.py b/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.pyindex 3a298b613..a8e68b59d 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.py@@ -9,6 +9,7 @@ from switch_core.bridges.collaboration.models import (AttachmentFailure,InboundMessage,)+from switch_core.trust.client import NullTrustClientclass _FakeHumanActor:@@ -94,6 +95,7 @@ def _fake_bridge() -> SimpleNamespace:_is_registered_agent=_is_registered_agent,_ensure_human_in_room=_ensure_human_in_room,_record_message_map=_record_message_map,+ _trust_client=NullTrustClient(),human_actor=human_actor,recorded=recorded,)diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_unknown_member_first_message.py b/core/tests/switch_core/bridges/collaboration/test_bridge_unknown_member_first_message.pyindex b9a4bc085..05650173f 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_unknown_member_first_message.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_unknown_member_first_message.py@@ -10,6 +10,7 @@ from switch_core.bridges.collaboration import ()from switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.bridges.collaboration.models import InboundMessage+from switch_core.trust.client import NullTrustClient# CHOO-1781: the first message from a channel member not yet known to the room# must not be dropped. Provisioning invites the external user's human actor and@@ -201,6 +202,7 @@ async def test_first_message_from_app_sender_is_relayed() -> None:_handle_text_answer=_no_text_answer,_channel_to_room={"chan-1": ("room-uuid", TRANSPORT_ROOM_ID)},_channel_locks={},+ _trust_client=NullTrustClient(),)await CollaborationCore._handle_inbound_message(@@ -246,6 +248,7 @@ async def test_first_message_from_unknown_member_is_relayed() -> None:_handle_text_answer=_no_text_answer,_channel_to_room={"chan-1": ("room-uuid", TRANSPORT_ROOM_ID)},_channel_locks={},+ _trust_client=NullTrustClient(),)await CollaborationCore._handle_inbound_message(diff --git a/core/tests/switch_core/management/test_middleware.py b/core/tests/switch_core/management/test_middleware.pyindex 47729dac1..84983f546 100644--- a/core/tests/switch_core/management/test_middleware.py+++ b/core/tests/switch_core/management/test_middleware.py@@ -31,6 +31,7 @@ from switch_core.management import tokensfrom switch_core.management.auth import ManagementAuthenticatorfrom switch_core.management.wiring import create_managementfrom switch_core.tenant_context import current_tenant_id+from switch_core.trust.client import NullTrustClientfrom tests.switch_core.management.harness import (TOKEN_SECRET,Harness,@@ -310,6 +311,7 @@ class TestTheFlagOff:config=_Config(), # type: ignore[arg-type]approval_outcomes=object(), # type: ignore[arg-type]controller_auth=None,+ trust_client=NullTrustClient(),)paths = [getattr(route, "path", "") for route in app.routes]assert pathsdiff --git a/core/tests/switch_core/telemetry/test_emitters_are_live.py b/core/tests/switch_core/telemetry/test_emitters_are_live.pyindex 47e5f1312..cec8375af 100644--- a/core/tests/switch_core/telemetry/test_emitters_are_live.py+++ b/core/tests/switch_core/telemetry/test_emitters_are_live.py@@ -29,6 +29,7 @@ from switch_core.bridges.agent.protocol.event_buffer import EventBufferfrom switch_core.keys import Keyringfrom switch_core.telemetry.service import TelemetryServicefrom switch_core.telemetry.sink import NullSink+from switch_core.trust.client import NullTrustClientdef _telemetry() -> TelemetryService:@@ -61,6 +62,7 @@ def _build(telemetry: TelemetryService) -> Any:config=_config(),approval_outcomes=object(), # type: ignore[arg-type]controller_auth=None,+ trust_client=NullTrustClient(),telemetry=telemetry,)return protocoldiff --git a/core/tests/switch_core/test_config_switch_trust.py b/core/tests/switch_core/test_config_switch_trust.pynew file mode 100644index 000000000..2480d0e67--- /dev/null+++ b/core/tests/switch_core/test_config_switch_trust.py@@ -0,0 +1,66 @@+"""Half-configuring Switch Trust has to be a startup error, the same shape as+the distributed Slack/Discord app config: setting the key without the policy+(or the reverse) looks configured and checks nothing.+"""++import pytest++from switch_core.config import SwitchConfig++_BASE_KWARGS = dict(+ db_host="db",+ db_port="5432",+ db_user="postgres",+ db_password="pw",+ db_name="switch",+ id_server_name="switch.local",+ agent_registration_token="token",+ secret_keys="test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",+ gateway_admin_email="[email protected]",+ gateway_admin_password="pw",+)++_TRUST = dict(+ switch_trust_api_key="key",+ switch_trust_policy_id="pol_123",+)+++def _config(**overrides: object) -> SwitchConfig:+ return SwitchConfig(**{**_BASE_KWARGS, **overrides}) # type: ignore[arg-type]+++def test_off_by_default() -> None:+ config = _config()+ assert config.trust_enabled is False+ assert config.switch_trust_endpoint == "https://api.flintai.dev"+++def test_setting_both_enables_it() -> None:+ assert _config(**_TRUST).trust_enabled is True++[email protected]("missing", sorted(_TRUST))+def test_setting_only_one_raises(missing: str) -> None:+ partial = {key: value for key, value in _TRUST.items() if key != missing}+ with pytest.raises(ValueError, match="Partial Switch Trust config"):+ _config(**partial)+++def test_a_path_on_the_endpoint_is_refused() -> None:+ """The check path is appended, so a value already carrying one would be+ posted to e.g. /guardrails/check/guardrails/check."""+ with pytest.raises(ValueError, match="must have no path"):+ _config(+ **_TRUST, switch_trust_endpoint="https://trust.example/guardrails/check"+ )+++def test_an_http_endpoint_is_refused() -> None:+ with pytest.raises(ValueError, match="must be an http"):+ _config(**_TRUST, switch_trust_endpoint="not-a-url")+++def test_a_non_positive_timeout_is_refused() -> None:+ with pytest.raises(ValueError, match="SWITCH_TRUST_TIMEOUT_SECONDS"):+ _config(**_TRUST, switch_trust_timeout_seconds=0)diff --git a/core/tests/switch_core/test_ingress_agent_api_paths.py b/core/tests/switch_core/test_ingress_agent_api_paths.pyindex c190360a1..d361ed0d4 100644--- a/core/tests/switch_core/test_ingress_agent_api_paths.py+++ b/core/tests/switch_core/test_ingress_agent_api_paths.py@@ -18,6 +18,7 @@ from switch_core.bridges.agent.app import create_agent_bridge_appfrom switch_core.bridges.agent.protocol.event_buffer import EventBufferfrom switch_core.keys import Keyringfrom switch_core.management.controller_routes import router as controller_router+from switch_core.trust.client import NullTrustClient_CHART = Path(__file__).resolve().parents[3] / "deploy/remote/helm/switch"@@ -61,6 +62,7 @@ def _served_prefixes() -> set[str]:config=_config(),approval_outcomes=object(), # type: ignore[arg-type]controller_auth=None,+ trust_client=NullTrustClient(),)prefixes = set(_ADDED_IN_MAIN)# The agents controller's routes join the agent bridge app only when agentdiff --git a/core/tests/switch_core/trust/__init__.py b/core/tests/switch_core/trust/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/core/tests/switch_core/trust/test_client.py b/core/tests/switch_core/trust/test_client.pynew file mode 100644index 000000000..c15fc8cba--- /dev/null+++ b/core/tests/switch_core/trust/test_client.py@@ -0,0 +1,156 @@+"""Switch Trust's wire format and fail-open behaviour are ours to keep+correct, so they are tested directly rather than only through the two call+sites that use them.+"""++import json++import httpx+import pytest++from switch_core.trust.client import (+ GuardrailBlockedError,+ GuardrailsCheckError,+ HttpTrustClient,+ NullTrustClient,+ TrustCheckResult,+ TrustFinding,+ check_message,+)+++def _client(handler) -> HttpTrustClient:+ return HttpTrustClient(+ base_url="https://trust.example",+ api_key="k",+ policy_id="pol_123",+ timeout_seconds=1.0,+ client=httpx.AsyncClient(transport=httpx.MockTransport(handler)),+ )+++async def test_posts_the_one_message_with_the_expected_headers():+ seen: dict[str, object] = {}++ def handler(request: httpx.Request) -> httpx.Response:+ seen["url"] = str(request.url)+ seen["policy"] = request.headers.get("x-guardrails-policy-id")+ seen["key"] = request.headers.get("x-flintai-api-key")+ seen["body"] = json.loads(request.content)+ return httpx.Response(200, json={"outcome": "GUARDRAIL_RESULT_OUTCOME_OK"})++ client = _client(handler)+ result = await client.check(role="user", content="hi")++ assert seen["url"] == "https://trust.example/guardrails/check"+ assert seen["policy"] == "pol_123"+ assert seen["key"] == "k"+ assert seen["body"] == {"messages": [{"role": "user", "content": "hi"}]}+ assert result.blocked is False+++async def test_a_trailing_slash_on_the_base_url_does_not_double_up():+ seen: dict[str, object] = {}++ def handler(request: httpx.Request) -> httpx.Response:+ seen["url"] = str(request.url)+ return httpx.Response(200, json={"outcome": "GUARDRAIL_RESULT_OUTCOME_OK"})++ client = HttpTrustClient(+ base_url="https://trust.example/",+ api_key="k",+ policy_id="pol_123",+ timeout_seconds=1.0,+ client=httpx.AsyncClient(transport=httpx.MockTransport(handler)),+ )+ await client.check(role="user", content="hi")+ assert seen["url"] == "https://trust.example/guardrails/check"+++async def test_a_blocked_outcome_carries_its_findings():+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 200,+ json={+ "outcome": "GUARDRAIL_RESULT_OUTCOME_BLOCKED",+ "policy_id": "pol_123",+ "policy_name": "Default Policy",+ "findings": [+ {+ "category": "pii/email",+ "detector_name": "PiiDetector",+ "detected_string": "[email protected]",+ "severity": "high",+ }+ ],+ },+ )++ client = _client(handler)+ result = await client.check(role="user", content="my email is [email protected]")++ assert result.blocked is True+ assert result.policy_name == "Default Policy"+ finding = result.findings[0]+ assert finding.category == "pii/email"+ assert finding.severity == "high"+ # The raw detected text never travels past the wire client.+ assert not hasattr(finding, "detected_string")+++async def test_an_error_response_raises_rather_than_allowing_silently():+ client = _client(lambda request: httpx.Response(503, text="unavailable"))+ with pytest.raises(GuardrailsCheckError, match="503"):+ await client.check(role="user", content="hi")+++async def test_a_network_failure_raises():+ def handler(request: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("refused")++ client = _client(handler)+ with pytest.raises(GuardrailsCheckError, match="failed"):+ await client.check(role="user", content="hi")+++async def test_null_client_always_allows():+ result = await NullTrustClient().check(role="user", content="anything")+ assert result.blocked is False+++async def test_check_message_fails_open_on_error():+ client = _client(lambda request: httpx.Response(500, text="boom"))+ result = await check_message(client, role="user", content="hi")+ assert result == TrustCheckResult(blocked=False, policy_id=None, policy_name=None)+++async def test_check_message_passes_through_a_block():+ client = _client(+ lambda request: httpx.Response(+ 200, json={"outcome": "GUARDRAIL_RESULT_OUTCOME_BLOCKED"}+ )+ )+ result = await check_message(client, role="assistant", content="hi")+ assert result.blocked is True+++def test_guardrail_blocked_error_names_the_categories():+ result = TrustCheckResult(+ blocked=True,+ policy_id="pol_123",+ policy_name="Default",+ findings=(+ TrustFinding(+ category="pii/email", detector_name="PiiDetector", severity="high"+ ),+ ),+ )+ assert "pii/email" in str(GuardrailBlockedError(result))diff --git a/docs/design/switch-trust-guardrails-v1.md b/docs/design/switch-trust-guardrails-v1.mdnew file mode 100644index 000000000..79ae2ed84--- /dev/null+++ b/docs/design/switch-trust-guardrails-v1.md@@ -0,0 +1,196 @@+# Switch Trust guardrails integration, v1++Integrates Switch with **Switch Trust**, a guardrails service that evaluates a+message against a policy and returns a block/allow verdict. The service+exposes a `/guardrails/check` endpoint (see+[hoot#2397](https://github.com/sandbox-quantum/hoot/pull/2397) and its+[README](https://github.com/sandbox-quantum/hoot/blob/300cece9ec3625a5327a06aea66681c444c53139/services/aispm/guardrails/common/externalprocessor/README.md))+that takes a provider-agnostic `messages` array and returns an `outcome` plus+findings. This doc covers v1: a global, env-configured gate in front of every+message Switch sends, blocking on a `BLOCKED` outcome.++## Scope++- One guardrails policy for the whole deployment (no per-tenant override).+- Configured by environment variables only — no gateway or console UI.+- Checks the single outgoing message only — no conversation history sent.+- Only the `BLOCKED` outcome is acted on; `REDACTED`/`ALERTED`/`ERRORED` pass+ through unchanged.+- Text content only — no media/attachments, no tool call/tool result mapping.++These are deliberate v1 cuts, not an assessment that they're unneeded — see+Follow-ups.++## Where it hooks in++The single point every message passes through, regardless of origin, is+`Actor.send_message` (`core/switch_core/clients/actor.py:206`).+`HumanActor`, `AgentActor`, `SystemActor`, and bridge actors all call it before+it reaches `PostgresTransport._send` (`core/switch_core/transport/postgres.py:659`),+which is where the row is actually persisted. The guardrails check runs in+`Actor.send_message`, before the call into the transport — a blocked message+never becomes a row.++`SystemActor`'s own admin/notice sends are excluded from the check: they're+Switch's own control-plane messages (including the blocked-notice this feature+itself posts), not user or agent content.++## Enforcement flow++1. Map the outgoing message to the hoot request shape:+ ```json+ {"messages": [{"role": "<mapped>", "content": "<body>"}]}+ ```+ Role mapping: `agent` → `assistant`, `human`/`bridge` → `user`.+2. `POST {switch_trust_endpoint}/guardrails/check` — the check-only endpoint+ added in [hoot#2397](https://github.com/sandbox-quantum/hoot/pull/2397) —+ with headers `x-guardrails-policy-id` and `x-flintai-api-key`, short+ timeout (2s default).+3. `outcome == "GUARDRAIL_RESULT_OUTCOME_BLOCKED"` → block. Any other outcome+ (`OK`, `REDACTED`, `ALERTED`, `ERRORED`) → allow through unchanged.+4. On block: `Actor.send_message` raises `GuardrailBlockedError` (carrying+ `outcome`, `findings`, `policy_id`) instead of calling the transport. No row+ is created.+5. On network error, timeout, or non-2xx from Switch Trust: **fail open** —+ log a warning and let the message through unchecked. Blocking all of+ Switch's messaging on a guardrails-service outage is a worse failure mode+ than an unchecked message during an outage.++## Differentiated handling by origin++Both call sites catch `GuardrailBlockedError`; each already has the context to+react appropriately for its direction.++- **Agent-originated**, via `AgentProtocolCore.send_message`+ (`core/switch_core/bridges/agent/protocol/agent_core.py:1244`): catch the+ error, and instead of relaying the agent's real content, post a blocked+ notice into the room via `SystemActor.send_admin` with a new+ `AdminMessageType.TRUST_BLOCKED` (`core/switch_core/clients/admin_messages.py`).+ Every collaboration adapter (Slack, Mattermost, Discord, Teams, Telegram)+ already renders `admin_message()` as a platform-native system notice,+ distinct from an ordinary chat bubble — this is "visually stands out" for+ free. The agent's tool/API call gets back an error so it knows its response+ was blocked.+- **Human/bridge-originated**, at the inbound ingestion call site in+ `core/switch_core/bridges/collaboration/collaboration_core.py` where a+ platform event becomes a `human_actor.send_message(...)` call: catch the+ error and call the adapter's `admin_message(...)` back to the **originating+ platform channel** directly. The row is never created, so the message never+ reaches the room or any agent — the notice goes straight back to the+ sender's platform, not into Switch.++## Degraded-mode indicator (Switch Trust unreachable)++v1 ships with a warning log only on fail-open. A lighter-weight in-chat+indicator is worth adding as a fast-follow, reusing the mechanism Switch+already uses for "agent is working" status rather than inventing a new one:+every adapter implements `mark_activity()` (a reaction-emoji badge — 👀+working / ⏳ queued, defined per-adapter, e.g.+`core/switch_core/bridges/collaboration/slack/adapter.py:2049`) and+`post_rich`/`update_rich` (an edited-in-place turn-status card). Teams has no+reaction primitive (`supports_activity_reactions = False`), so it would only+get the card-edit treatment. Deferred out of v1 to avoid coupling the first PR+to the session/turn-rendering system — see Follow-ups.++## Config++New fields on `SwitchConfig` (`core/switch_core/config.py`), mirroring the+existing all-or-nothing settings groups (`_validate_slack_app`,+`core/switch_core/config.py:986`):++```python+switch_trust_endpoint: str = "https://api.flintai.dev"+switch_trust_api_key: str = ""+switch_trust_policy_id: str = ""+switch_trust_timeout_seconds: float = 2.0+```++`switch_trust_endpoint` is a base URL; the client appends+`/guardrails/check` — the check-only route added in+[hoot#2397](https://github.com/sandbox-quantum/hoot/pull/2397) — rather than+treating the configured value as the full check URL. This default will change+once Switch Trust has its own deployment — see Follow-ups.++A `trust_enabled` property returns `bool(switch_trust_api_key and+switch_trust_policy_id)`. A `_validate_switch_trust` model validator checks+the endpoint's URL shape (scheme/host, no path/query — mirroring+`_validate_observability`'s OTLP check) when it's overridden from the default,+and that `switch_trust_api_key`/`switch_trust_policy_id` are both set or both+empty.++When `trust_enabled` is false, a `NullTrustClient` is injected — mirrors+`telemetry/sink.py`'s `NullSink`: off is a client that always allows, so no+call site has to branch on whether the feature is on.++## Execution plan++1. **Config** — add the four `switch_trust_*` fields, `trust_enabled`+ property, and `_validate_switch_trust` validator to `SwitchConfig`. Unit+ tests mirroring the existing Slack/Discord app validator tests.+2. **Trust client** — new `core/switch_core/trust/client.py`: a `TrustClient`+ protocol (`check(role, content) -> TrustCheckResult`), an `HttpTrustClient`+ (httpx, the request/response mapping from §Enforcement flow, fail-open on+ transport errors), and a `NullTrustClient`. Unit tests for request+ building, outcome parsing, and the fail-open path.+3. **Exception + admin message type** — add `GuardrailBlockedError` (new+ module or alongside `transport` exceptions) and+ `AdminMessageType.TRUST_BLOCKED` in `admin_messages.py`.+4. **Wire the client into `Actor`** — inject `TrustClient` into `Actor`+ construction (exact DI point TBD when touching `ClientFactory`/`Actor.__init__`;+ follows the existing store/service injection pattern). Add the check at the+ top of `Actor.send_message`, skipped for `SystemActor`.+5. **Agent-origin handling** — catch `GuardrailBlockedError` in+ `AgentProtocolCore.send_message`, post the `TRUST_BLOCKED` admin message,+ surface an error back to the caller.+6. **Human/bridge-origin handling** — catch `GuardrailBlockedError` at the+ inbound ingestion call site in `collaboration_core.py`, call+ `adapter.admin_message(...)` back to the source channel instead of+ relaying.+7. **Integration tests** (real Postgres, per repo convention) — a blocked+ human message never creates a `messages` row; a blocked agent message+ results in a `TRUST_BLOCKED` admin row instead of the real content; an+ allowed message is unaffected; a Switch Trust timeout/error still delivers+ the message (fail-open).+8. **`docs/old/`**: note the new config block in whichever doc lists+ deployment env vars (none currently fully enumerates `SwitchConfig`, so+ likely just a short mention near the other optional-integration blocks, if+ one exists).++## Resolved decisions++- Prod default for `switch_trust_endpoint`: `https://api.flintai.dev` (base+ URL; the client appends `/guardrails/check`). Expected to change once Switch+ Trust has its own deployment — tracked in Follow-ups.+- 2s timeout default, and `x-guardrails-policy-id` / `x-flintai-api-key`+ headers, confirmed as-is.+- Reaction-badge degraded-mode indicator deferred to a fast-follow rather than+ bundled into this PR.++## Follow-ups (explicitly out of v1 scope)++- **`switch_trust_endpoint` default will change**: `https://api.flintai.dev`+ is a placeholder base URL for now; Switch Trust is expected to get its own+ dedicated endpoint later, at which point the default should move.+- **Conversation history**: send the last N room messages as context so the+ policy can catch things that only make sense across turns (e.g. a PII leak+ split across messages). Needs a role-mapping strategy for Switch's+ multi-party rooms (which don't have a strict two-party turn structure) and a+ decision on including/excluding system/admin notices.+- **Tool calls / tool results**: the hoot endpoint supports `tool_calls` and+ `tool_result` message fields; Switch doesn't yet have an obvious mapping+ from its agent-protocol tool use onto that shape.+- **Redaction / alert handling**: act on `REDACTED` (replace content with the+ engine's sanitized version) and `ALERTED` (log/flag without blocking)+ outcomes instead of only hard-blocking.+- **Per-tenant / per-workspace policy**: today it's one global policy for the+ whole deployment. Multiple tenants wanting different policies needs a DB+ table, migration, and an admin API — a materially bigger lift than the env+ var config in this doc.+- **Settings UI**: a dedicated Switch Trust section, either in the gateway+ operator dashboard or in Console's "server properties" — neither surface has+ an existing settings page to extend today, so this is new UI work in either+ home.+- **Degraded-mode in-chat indicator**: the reaction-badge/turn-status+ treatment sketched above, once the core gate has shipped and proven out.+- **Media/attachment checks**: images and files aren't sent to Switch Trust in+ v1.