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
Let anyone with write access turn a room's auto-route on or off
agent-runner353ec9492229bac
diff --git a/core/switch_core/bridges/agent/commands.py b/core/switch_core/bridges/agent/commands.pyindex df01bfc8c..0f1b266d2 100644--- a/core/switch_core/bridges/agent/commands.py+++ b/core/switch_core/bridges/agent/commands.py@@ -503,7 +503,7 @@ async def _retry_refusal(if message is None:return "Could not retry: that message is not in this room."if message.sender_id != event.user_id and not await _manages_room(- client, session, room_id, event.user_id+ client, session, room_id, event.user_id, "retry"):return ("Could not retry: only whoever sent that message, or someone who "@@ -521,10 +521,14 @@ async def _retry_refusal(async def _manages_room(- client: AgentRecipient, session: AsyncSession, room_id: str, sender: str+ client: AgentRecipient,+ session: AsyncSession,+ room_id: str,+ sender: str,+ command: str,) -> bool:"""Whether the Switch user behind `sender` owns the room or administers- the tenant."""+ the tenant. `command` names the chat command in the admin audit record."""principal = await client._addressing.resolve_sender(session, sender)if principal is None or principal.kind != "user":return False@@ -541,7 +545,7 @@ async def _manages_room(user,target_type="room",target_id=room_id,- details={"event": "chat_command", "command": "retry"},+ details={"event": "chat_command", "command": command},):return Truereturn False@@ -920,6 +924,11 @@ _AUTO_ROUTE_OFF = ("reaches an agent only as a follow-up or through an assigned agent. Turn it ""on with `!auto-route on`.")+_AUTO_ROUTE_FALLBACK_REFUSED = (+ "Only the room's owner or a workspace admin can name or clear the room's "+ "triage agent. Nothing was changed. Anyone who can post here can still turn "+ "auto-route on or off with `!auto-route on` or `!auto-route off`."+)_AUTO_ROUTE_USAGE = ("Usage: `!auto-route on`, `!auto-route off`, `!auto-route` to see which it ""is, or `!auto-route fallback @agent` / `!auto-route fallback off` to name "@@ -1023,6 +1032,11 @@ async def _auto_route_fallback(if len(args) > 1:await _reply(client, room, event, _AUTO_ROUTE_USAGE)return+ if not await _manages_room(+ client, session, room_id, event.user_id, "auto-route fallback"+ ):+ await _reply(client, room, event, _AUTO_ROUTE_FALLBACK_REFUSED)+ returnhandle = args[0]target: Agent | None = Noneif handle.lower() != "off":diff --git a/core/switch_core/gateway/rooms.py b/core/switch_core/gateway/rooms.pyindex 186fd5917..4bca3d88d 100644--- a/core/switch_core/gateway/rooms.py+++ b/core/switch_core/gateway/rooms.py@@ -17,7 +17,6 @@ from switch_core.authz import (can,can_manage,can_unlink_from_room,- require_manage,)from switch_core.bridges.agent.operations.agent_management import management_portfrom switch_core.bridges.agent.protocol.agent_core import AgentCore@@ -1260,14 +1259,17 @@ async def put_auto_route() -> RoomAutoRoute:"""Turn the room's auto-route on or off, and name or clear its triageagent: the same settings as `!auto-route` and `!auto-route fallback`.- For the room's owner and the workspace's admins. Turning it on where it- cannot act (`available` false) is refused with 409 and the reason."""+ Turning it on or off takes write access to the room, the same as+ follow-ups; naming the triage agent also takes the room's owner or a+ workspace admin (`can_manage`). Turning it on where it cannot act+ (`available` false) is refused with 409 and the reason."""principal = Principal(user.id, is_admin)- room = await authorize_room(session, room_store, room_id, principal, "read")- try:- require_manage(principal, room.owner_id)- except PermissionError as e:- raise HTTPException(status_code=403, detail=str(e)) from e+ room = await authorize_room(session, room_store, room_id, principal, "write")+ if "fallback_agent" in req.model_fields_set and not can(principal, "delete", room):+ raise HTTPException(+ status_code=403,+ detail="Only the room's owner or a workspace admin can name the triage agent.",+ )try:if "fallback_agent" in req.model_fields_set:agent = Nonediff --git a/core/tests/switch_core/bridges/agent/test_commands_auto_route.py b/core/tests/switch_core/bridges/agent/test_commands_auto_route.pyindex c6d6bb460..645f1dbf7 100644--- a/core/tests/switch_core/bridges/agent/test_commands_auto_route.py+++ b/core/tests/switch_core/bridges/agent/test_commands_auto_route.py@@ -17,6 +17,7 @@ from switch_core.db.models import (ApiKey,Client,Room,+ TenantMember,User,room_agents,)@@ -28,15 +29,34 @@ from switch_core.db.stores.room_store import (RoomStore,)from switch_core.decision.settings import DecisionAvailability, ServerDefault+from switch_core.delivery.addressing import SenderPrincipalfrom switch_core.transport import RoomRef+async def _user(+ session_factory: async_sessionmaker[AsyncSession], name: str, role: str+) -> str:+ async with session_factory() as session:+ user = User(+ name=name,+ email=f"{name}-{uuid.uuid4().hex[:6]}@example.invalid",+ role="user",+ )+ session.add(user)+ await session.flush()+ session.add(TenantMember(tenant_id=TENANT_ZERO_ID, user_id=user.id, role=role))+ await session.commit()+ return user.id++async def _room(session_factory: async_sessionmaker[AsyncSession]) -> str:+ owner_id = await _user(session_factory, "room-owner", "member")async with session_factory() as session:room = Room(transport_room_id=f"!r-{uuid.uuid4().hex[:8]}:test",name="room",description="d",+ owner_id=owner_id,metadata_={"created_by_kind": "user"},)session.add(room)@@ -50,9 +70,22 @@ def _host(*,flag: bool = True,endpoint: bool = True,+ sender: str | None = None,) -> tuple[SimpleNamespace, list[str]]:+ """A command host for `room_id`. The command's sender is the Switch user+ `sender`, or the room's owner when it is None."""posted: list[str] = []+ async def _resolve_sender(+ session: AsyncSession, _transport_user_id: str+ ) -> SenderPrincipal:+ user_id = sender+ if user_id is None:+ room = await session.get(Room, room_id)+ assert room is not None and room.owner_id is not None+ user_id = room.owner_id+ return SenderPrincipal("user", "ext-sender", [user_id], None)+async def _resolve_room_meta(_transport_room_id: str) -> SimpleNamespace:return SimpleNamespace(room_id=room_id, name="room")@@ -65,6 +98,7 @@ def _host(reply_command=_reply_command,_room_store=RoomStore(),_agent_store=AgentStore(),+ _addressing=SimpleNamespace(resolve_sender=_resolve_sender),_decision_availability=DecisionAvailability(enabled=flag,server=ServerDefault(@@ -79,7 +113,9 @@ def _host(async def _run(host: SimpleNamespace, args: str) -> None:- event = SimpleNamespace(command="auto-route", args=args, thread_id=None)+ event = SimpleNamespace(+ command="auto-route", args=args, thread_id=None, user_id="@sender:test"+ )await _cmd_auto_route(host, RoomRef(room_id="!t:test"), event, False) # type: ignore[arg-type]@@ -294,6 +330,58 @@ class TestTheTriageAgent:assert "no longer has a triage agent" in posted[-1]assert await _fallback(session_factory, room_id) is None+ async def test_a_member_turns_it_on_and_off(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ room_id = await _room(session_factory)+ member = await _user(session_factory, "member", "member")+ host, posted = _host(session_factory, room_id, sender=member)++ await _run(host, "on")+ assert "Automatic routing is **on**" in posted[-1]+ assert await _on(session_factory, room_id)++ await _run(host, "off")+ assert "Automatic routing is **off**" in posted[-1]+ assert not await _on(session_factory, room_id)++ async def test_a_member_cannot_name_or_clear_it_but_may_see_it(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ room_id = await _room(session_factory)+ agents = await _agents(session_factory, room_id)+ member = await _user(session_factory, "member", "member")+ host, posted = _host(session_factory, room_id, sender=member)++ await _run(host, "fallback @triage")+ assert posted[-1].startswith(+ "Only the room's owner or a workspace admin can name or clear"+ )+ assert "Nothing was changed" in posted[-1]+ assert await _fallback(session_factory, room_id) is None++ owner, _ = _host(session_factory, room_id)+ await _run(owner, "fallback @triage")+ await _run(host, "fallback off")+ assert posted[-1].startswith("Only the room's owner or a workspace admin")+ assert await _fallback(session_factory, room_id) == agents["triage"].id++ await _run(host, "fallback")+ assert "go to **triage**" in posted[-1]++ async def test_a_workspace_admin_may_name_it(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ room_id = await _room(session_factory)+ agents = await _agents(session_factory, room_id)+ admin = await _user(session_factory, "admin", "admin")+ host, posted = _host(session_factory, room_id, sender=admin)++ await _run(host, "fallback @triage")++ assert "is now this room's triage agent" in posted[-1]+ assert await _fallback(session_factory, room_id) == agents["triage"].id+async def test_an_agent_not_in_the_room_is_refused(self, session_factory: async_sessionmaker[AsyncSession]) -> None:diff --git a/core/tests/switch_core/delivery/test_conversation_journeys.py b/core/tests/switch_core/delivery/test_conversation_journeys.pyindex 9b7556bab..b4af850bf 100644--- a/core/tests/switch_core/delivery/test_conversation_journeys.py+++ b/core/tests/switch_core/delivery/test_conversation_journeys.py@@ -53,6 +53,7 @@ from switch_core.db.stores.room_store import RoomStorefrom switch_core.decision.client import DynamicDecisionClientfrom switch_core.decision.settings import DecisionAvailability, ServerDefaultfrom switch_core.delivery import router as router_module+from switch_core.delivery.addressing import AddressingResolverfrom switch_core.delivery.conversation import ConversationSettingsfrom switch_core.delivery.recipient import AgentRecipientfrom switch_core.transport import RoomRef@@ -258,6 +259,14 @@ class Journey:_external_user_store=ExternalUserStore(),client_store=ClientStore(),_connections=SimpleNamespace(live_connection_ids=lambda: set()),+ _addressing=AddressingResolver(+ room_store=RoomStore(),+ room_role_store=RoomRoleStore(),+ client_store=ClientStore(),+ agent_store=AgentStore(),+ external_user_store=ExternalUserStore(),+ live_connection_ids=lambda: set(),+ ),_follow_the_conversation_enabled=True,_decision_availability=(self.decisions.availabilitydiff --git a/core/tests/switch_core/delivery/test_decision_routing.py b/core/tests/switch_core/delivery/test_decision_routing.pyindex a6fb0aaff..1b3e82feb 100644--- a/core/tests/switch_core/delivery/test_decision_routing.py+++ b/core/tests/switch_core/delivery/test_decision_routing.py@@ -905,6 +905,28 @@ class TestTheRoomIsTold:class TestTheTriageAgent:+ """Naming the triage agent takes the room's owner or a workspace admin;+ alice is claimed by the room's owner here."""++ @pytest.fixture(autouse=True)+ async def _alice_owns_the_room(self, world: World) -> None:+ async with world.session_factory() as session:+ await session.execute(+ update(Room)+ .where(Room.id == world.room_id)+ .values(owner_id=world.owner_id)+ )+ await session.commit()++ async def test_bob_who_does_not_may_not_name_it(+ self, world: World, room: Journey+ ) -> None:+ reply = await room.command("bob", "auto-route", "fallback @reviewer", at=5)++ assert reply.startswith("Only the room's owner or a workspace admin")+ async with world.session_factory() as session:+ assert await RoomStore().auto_route_fallback(session, world.room_id) is None+async def test_it_gets_the_message_while_the_service_fails(self, world: World, room: Journey, service: DecisionService) -> None:diff --git a/core/tests/switch_core/gateway/test_room_auto_route.py b/core/tests/switch_core/gateway/test_room_auto_route.pyindex a4545ac04..ab7161ad6 100644--- a/core/tests/switch_core/gateway/test_room_auto_route.py+++ b/core/tests/switch_core/gateway/test_room_auto_route.py@@ -14,7 +14,6 @@ from types import SimpleNamespacefrom typing import Anyimport httpx-import pytestfrom fastapi import FastAPIfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker@@ -147,7 +146,9 @@ async def _agent(session: AsyncSession, owner: User, name: str) -> Agent:async def _room(- session_factory: async_sessionmaker[AsyncSession], owner: User+ session_factory: async_sessionmaker[AsyncSession],+ owner: User,+ visibility: str = "public",) -> tuple[Room, Agent, Agent]:async with session_factory() as session:room = Room(@@ -155,8 +156,8 @@ async def _room(name="ops",description="d",owner_id=owner.id,- read_visibility="public",- write_visibility="public",+ read_visibility=visibility,+ write_visibility=visibility,)session.add(room)await session.flush()@@ -334,29 +335,80 @@ class TestTheToggle:assert "assigned agent" in assigned.json()["detail"]assert stranger.status_code == 422- @pytest.mark.parametrize("role", ["member"])- async def test_someone_who_does_not_own_the_room_is_refused(- self, session_factory: async_sessionmaker[AsyncSession], role: str+ async def test_a_writer_who_does_not_own_the_room_turns_it_on_and_off(+ self, session_factory: async_sessionmaker[AsyncSession]) -> None:owner = await _user(session_factory, "owner", "member")- other = await _user(session_factory, "other", role)+ writer = await _user(session_factory, "writer", "member")room, _, _ = await _room(session_factory, owner)- async with _as(_app(session_factory), other) as client:+ async with _as(_app(session_factory), writer) as client:+ on = await client.put(f"/rooms/{room.id}/auto-route", json={"on": True})+ assert (await _metadata(session_factory, room.id))[AUTO_ROUTE_ON_KEY]+ off = await client.put(f"/rooms/{room.id}/auto-route", json={"on": False})++ assert on.status_code == 200+ assert on.json()["on"] is True+ assert off.status_code == 200+ assert off.json()["on"] is False++ async def test_a_read_only_viewer_of_a_private_room_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ owner = await _user(session_factory, "owner", "member")+ viewer = await _user(session_factory, "viewer", "member")+ room, _, _ = await _room(session_factory, owner, visibility="private")+ async with session_factory() as session:+ # Owning an agent in the room lets the viewer read it, not write.+ theirs = await _agent(session, viewer, "theirs")+ await session.execute(+ room_agents.insert().values(room_id=room.id, agent_id=theirs.id)+ )+ await session.commit()+ async with _as(_app(session_factory), viewer) as client:+ detail = await client.get(f"/rooms/{room.id}")refused = await client.put(f"/rooms/{room.id}/auto-route", json={"on": True})+ assert detail.status_code == 200+ assert detail.json()["can_write"] is Falseassert refused.status_code == 403assert AUTO_ROUTE_ON_KEY not in await _metadata(session_factory, room.id)- async def test_a_workspace_admin_may(+ async def test_a_writer_cannot_name_the_triage_agent(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ owner = await _user(session_factory, "owner", "member")+ writer = await _user(session_factory, "writer", "member")+ room, triage, _ = await _room(session_factory, owner)+ async with _as(_app(session_factory), writer) as client:+ named = await client.put(+ f"/rooms/{room.id}/auto-route",+ json={"on": True, "fallback_agent": triage.id},+ )+ cleared = await client.put(+ f"/rooms/{room.id}/auto-route", json={"fallback_agent": None}+ )++ assert named.status_code == 403+ assert "owner or a workspace admin" in named.json()["detail"]+ assert cleared.status_code == 403+ metadata = await _metadata(session_factory, room.id)+ assert AUTO_ROUTE_FALLBACK_KEY not in metadata+ assert AUTO_ROUTE_ON_KEY not in metadata++ async def test_a_workspace_admin_may_name_the_triage_agent(self, session_factory: async_sessionmaker[AsyncSession]) -> None:owner = await _user(session_factory, "owner", "member")admin = await _user(session_factory, "admin", "admin")- room, _, _ = await _room(session_factory, owner)+ room, triage, _ = await _room(session_factory, owner, visibility="private")async with _as(_app(session_factory), admin) as client:- put = await client.put(f"/rooms/{room.id}/auto-route", json={"on": True})+ put = await client.put(+ f"/rooms/{room.id}/auto-route",+ json={"on": True, "fallback_agent": triage.id},+ )assert put.status_code == 200assert put.json()["on"] is True+ assert put.json()["fallback_agent"] == triage.id