"""Global, per-tenant and per-tool kill switches, checked before every tool call.""" from __future__ import annotations import uuid from sqlalchemy import and_, or_, select, update from sqlalchemy.ext.asyncio import AsyncSession from core.gateway.models import KillSwitch async def active_switch(session: AsyncSession, tenant_id: uuid.UUID, tool: str) -> str | None: """Return the reason of the first matching enabled switch, or None.""" row = ( await session.execute( select(KillSwitch.scope, KillSwitch.target, KillSwitch.reason) .where( KillSwitch.enabled.is_(True), or_( and_(KillSwitch.scope == "global"), and_(KillSwitch.scope == "tenant", KillSwitch.target == str(tenant_id)), and_( KillSwitch.scope == "tool", KillSwitch.target == tool, or_(KillSwitch.tenant_id.is_(None), KillSwitch.tenant_id == tenant_id), ), ), ) .limit(1) ) ).first() if row is None: return None return f"kill switch ({row.scope}:{row.target}) {row.reason}".strip() async def set_switch( session: AsyncSession, *, scope: str, target: str, enabled: bool, reason: str = "", tenant_id: uuid.UUID | None = None, ) -> None: if scope not in {"global", "tenant", "tool"}: raise ValueError(f"bad scope {scope}") existing = ( await session.execute( select(KillSwitch.id).where( KillSwitch.scope == scope, KillSwitch.target == target, KillSwitch.tenant_id.is_(None) if tenant_id is None else KillSwitch.tenant_id == tenant_id, ) ) ).scalar_one_or_none() if existing: await session.execute( update(KillSwitch) .where(KillSwitch.id == existing) .values(enabled=enabled, reason=reason) ) else: session.add( KillSwitch( tenant_id=tenant_id, scope=scope, target=target, enabled=enabled, reason=reason ) ) await session.flush()