Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

Remove the legacy /moderation HTTP routes, now that the ops door covers them (#993)

Abel Dantas684c2725fbc6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bd1343ab9..030786534 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -274,6 +274,18 @@ version of their own to them without also giving them a release of their own.
uploaded again.
#### Removed
+- **Breaking for HTTP clients: the `/agents/{id}/moderation/…` routes are
+ removed** and answer `404`. They predate the operations door, which runs the
+ same operations as MCP. Call `POST /agents/{id}/ops/<operation>` with the
+ operation's arguments as the JSON body instead:
+ `POST moderation/rooms` is `create_room`,
+ `POST moderation/rooms/{room_id}/invite` is `invite_agent_to_room`,
+ `GET moderation/rooms` is `list_all_rooms`,
+ `GET moderation/rooms/{room_id}` is `get_room_detail`,
+ `GET moderation/agents` is `list_agents`, and
+ `GET moderation/bridges` is `list_bridges`. The reply is
+ `{"result": …}` in the operation's own shape, so `list_all_rooms` gives
+ `room_id` where the old route gave `id`.
- **`!run-cmd`, and the terminal command in offline replies.** A CLI started
with that command got none of the Switch tools, so it never brought the agent
online. The reply for an agent that is offline or not live now says what's
diff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.py
index a4dcaf24f..39faae991 100644
--- a/core/switch_core/bridges/agent/api/handlers.py
+++ b/core/switch_core/bridges/agent/api/handlers.py
@@ -24,22 +24,16 @@ from sqlalchemy.ext.asyncio import AsyncSession
from starlette.responses import Response, StreamingResponse
from switch_core.bridges.agent.api.schemas import (
- AgentInfo,
- AgentListResponse,
BulkRegisterResult,
ConnectionBeatRequest,
ConnectionPlacementsRequest,
ConnectionRenewRequest,
ConnectionSubscribeRequest,
- CreateModerationRoomRequest,
- CreateModerationRoomResponse,
EventResponse,
FeatureFlagInfo,
FeatureFlagListResponse,
HistoryMessage,
HistoryResponse,
- InviteAgentRequest,
- ListBridgesResponse,
ParticipantInfo,
ParticipantsResponse,
PostLlmResponseRequest,
@@ -56,9 +50,6 @@ from switch_core.bridges.agent.api.schemas import (
RegisterKnownAgentBulkResponse,
RegisterKnownAgentRequest,
ReportEventsRequest,
- RoomDetailResponse,
- RoomInfo,
- RoomListResponse,
RuntimeStateRequest,
SendMessageRequest,
StatusRequest,
@@ -1887,157 +1878,6 @@ async def post_llm_response(
return PostLlmResponseResponse(verdict=result["verdict"]) # type: ignore[arg-type]
-# Moderation endpoints
-
-
[email protected]("/{agent_id}/moderation/rooms")
-async def create_room(
- agent_id: str,
- req: CreateModerationRoomRequest,
- agent: Annotated[Agent, Depends(get_agent_from_scope)],
- protocol: Annotated[AgentCore, Depends(get_protocol)],
-) -> CreateModerationRoomResponse:
- if agent.id != agent_id:
- raise HTTPException(status_code=403, detail="Not authorized for this agent")
-
- try:
- result = await protocol.create_moderation_room(
- agent_id=agent.id,
- name=req.name,
- description=req.description,
- agent_names=req.agent_names,
- include_subagents_for=req.include_subagents_for,
- user_names=req.user_names,
- channel_type=req.channel_type,
- bridge_id=req.bridge_id,
- internal_only=req.internal_only,
- admin_mode=req.admin_mode,
- security_config=req.security_config,
- instructions=req.instructions,
- reference_ids=req.reference_ids,
- package_ids=req.package_ids,
- linked_rooms=(
- [lr.model_dump() for lr in req.linked_rooms]
- if req.linked_rooms
- else None
- ),
- )
- except PermissionError as e:
- raise HTTPException(status_code=403, detail=str(e)) from e
- except ValueError as e:
- raise HTTPException(status_code=422, detail=str(e)) from e
- except RuntimeError as e:
- raise HTTPException(status_code=502, detail=str(e)) from e
-
- return CreateModerationRoomResponse(
- id=result.room.id,
- name=result.room.name,
- transport_room_id=result.room.transport_room_id,
- matrix_room_id=result.room.transport_room_id,
- failed_attachments=result.failed_attachments,
- )
-
-
[email protected]("/{agent_id}/moderation/rooms/{room_id}/invite")
-async def invite_agent(
- agent_id: str,
- room_id: str,
- req: InviteAgentRequest,
- agent: Annotated[Agent, Depends(get_agent_from_scope)],
- protocol: Annotated[AgentCore, Depends(get_protocol)],
-) -> dict[str, bool]:
- if agent.id != agent_id:
- raise HTTPException(status_code=403, detail="Not authorized for this agent")
-
- try:
- await protocol.invite_agent_to_room(
- agent.id, room_id, req.agent_name, include_subagents=req.include_subagents
- )
- except ValueError as e:
- raise HTTPException(status_code=422, detail=str(e)) from e
- except PermissionError as e:
- raise HTTPException(status_code=403, detail=str(e)) from e
- return {"ok": True}
-
-
[email protected]("/{agent_id}/moderation/rooms")
-async def list_rooms(
- agent_id: str,
- agent: Annotated[Agent, Depends(get_agent_from_scope)],
- protocol: Annotated[AgentCore, Depends(get_protocol)],
-) -> RoomListResponse:
- if agent.id != agent_id:
- raise HTTPException(status_code=403, detail="Not authorized for this agent")
-
- rooms = await protocol.list_all_rooms(agent.id)
- return RoomListResponse(
- rooms=[RoomInfo(id=r.id, name=r.name, description=r.description) for r in rooms]
- )
-
-
[email protected]("/{agent_id}/moderation/rooms/{room_id}")
-async def get_room(
- agent_id: str,
- room_id: str,
- agent: Annotated[Agent, Depends(get_agent_from_scope)],
- protocol: Annotated[AgentCore, Depends(get_protocol)],
-) -> RoomDetailResponse:
- if agent.id != agent_id:
- raise HTTPException(status_code=403, detail="Not authorized for this agent")
-
- try:
- room_detail = await protocol.get_room_detail(agent.id, room_id)
- except ValueError as e:
- raise HTTPException(status_code=404, detail=str(e)) from e
- except PermissionError as e:
- raise HTTPException(status_code=403, detail=str(e)) from e
-
- return RoomDetailResponse(
- id=room_detail.id,
- name=room_detail.name,
- description=room_detail.description,
- channel_type=room_detail.channel_type,
- admin_mode=room_detail.admin_mode,
- agent_names=room_detail.agent_names,
- )
-
-
[email protected]("/{agent_id}/moderation/agents")
-async def list_agents(
- agent_id: str,
- agent: Annotated[Agent, Depends(get_agent_from_scope)],
- protocol: Annotated[AgentCore, Depends(get_protocol)],
-) -> AgentListResponse:
- if agent.id != agent_id:
- raise HTTPException(status_code=403, detail="Not authorized for this agent")
-
- agents = await protocol.list_all_agents(agent.id)
- return AgentListResponse(
- agents=[
- AgentInfo(
- id=a.id,
- name=a.name,
- description=a.description,
- display_name=a.display_name,
- )
- for a in agents
- ]
- )
-
-
[email protected]("/{agent_id}/moderation/bridges")
-async def list_bridges(
- agent_id: str,
- agent: Annotated[Agent, Depends(get_agent_from_scope)],
- protocol: Annotated[AgentCore, Depends(get_protocol)],
-) -> ListBridgesResponse:
- if agent.id != agent_id:
- raise HTTPException(status_code=403, detail="Not authorized for this agent")
-
- bridges = await protocol.list_bridges()
- return ListBridgesResponse(bridges=bridges)
-
-
# Feature flag endpoints
diff --git a/core/switch_core/bridges/agent/api/schemas.py b/core/switch_core/bridges/agent/api/schemas.py
index 730bc1fed..7ef01c5d9 100644
--- a/core/switch_core/bridges/agent/api/schemas.py
+++ b/core/switch_core/bridges/agent/api/schemas.py
@@ -321,96 +321,6 @@ class ReportEventsRequest(BaseModel):
events: list[ToolCallReport | LlmCallReport]
-# ── Agents ───────────────────────────────────────────────────────────────────
-
-
-class AgentInfo(BaseModel):
- id: str
- name: str
- description: str
- display_name: str | None
-
-
-# ── Moderation ───────────────────────────────────────────────────────────────
-
-
-class LinkedRoomCreateSpec(BaseModel):
- target_room_id: str
- label: str
-
-
-class CreateModerationRoomRequest(BaseModel):
- name: str
- description: str
- agent_names: list[str]
- # Per-agent opt-in: names (subset of agent_names) whose subagents to also add.
- include_subagents_for: list[str] | None = None
- user_names: list[str] | None = None
- channel_type: Literal["channel_public", "channel_private"] | None = None
- # Bridge is optional — omit to use the instance's default bridge.
- bridge_id: str | None = None
- # Opt out of the instance default bridge: create a room with no external
- # channel. Ignored when bridge_id is set.
- internal_only: bool = False
- admin_mode: bool = False
- security_config: dict[str, Any] | None = None
- instructions: str | None = None
- reference_ids: list[str] | None = None
- package_ids: list[str] | None = None
- linked_rooms: list[LinkedRoomCreateSpec] | None = None
-
-
-class CreateModerationRoomResponse(BaseModel):
- id: str
- name: str
- transport_room_id: str
- # Deprecated alias of `transport_room_id`, sent for the compatibility
- # window. Connectors are installed copies and only update when someone
- # clicks Update, so both names are carried until the shipped ones have
- # moved. Same value in both; nothing dereferences either.
- matrix_room_id: str
- # Attachments that failed at attach-time (after the room was created).
- # Empty on full success.
- failed_attachments: list[dict[str, Any]] = []
-
-
-class ListBridgesResponse(BaseModel):
- bridges: list[dict[str, Any]]
-
-
-class InviteAgentRequest(BaseModel):
- agent_name: str
- # When true, also add the invited agent's subagents (child agents).
- include_subagents: bool = False
-
-
-class UpdateSecurityRequest(BaseModel):
- checks: list[dict[str, Any]]
-
-
-class RoomInfo(BaseModel):
- id: str
- name: str
- description: str
-
-
-class RoomDetailResponse(BaseModel):
- id: str
- name: str
- description: str
- channel_type: str | None
- admin_mode: bool
- agent_names: list[str]
-
-
-class RoomListResponse(BaseModel):
- rooms: list[RoomInfo]
-
-
-class AgentListResponse(BaseModel):
- agents: list[AgentInfo]
-
-
class FeatureFlagInfo(BaseModel):
key: str
enabled: bool
diff --git a/core/switch_core/bridges/agent/protocol/agent_core.py b/core/switch_core/bridges/agent/protocol/agent_core.py
index b7faf1d8e..691240bcb 100644
--- a/core/switch_core/bridges/agent/protocol/agent_core.py
+++ b/core/switch_core/bridges/agent/protocol/agent_core.py
@@ -4175,12 +4175,6 @@ class AgentCore:
await self.room_service.set_room_archived(room_id, archived)
return await self.get_room_detail(agent_id, room_id)
- async def list_all_agents(self, agent_id: str) -> list[Agent]:
- """List all agents (moderation only)."""
- async with self.session_factory() as session:
- agents = await self.agent_store.get_all(session)
- return agents
-
async def pre_tool_call(
self,
agent_id: str,
diff --git a/core/tests/switch_core/bridges/agent/api/test_moderation_routes_removed.py b/core/tests/switch_core/bridges/agent/api/test_moderation_routes_removed.py
new file mode 100644
index 000000000..e79d44c13
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/api/test_moderation_routes_removed.py
@@ -0,0 +1,63 @@
+"""The moderation routes are gone from the HTTP surface: they answer 404, and
+agents reach the same operations through the operations door."""
+
+from __future__ import annotations
+
+from collections.abc import Iterator
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from starlette.types import ASGIApp, Receive, Scope, Send
+
+from switch_core.bridges.agent.api import handlers, operations
+from switch_core.bridges.agent.dependencies import (
+ get_protocol,
+ get_session_factory,
+)
+from switch_core.db.models import TENANT_ZERO_ID, Agent
+from switch_core.tenant_context import tenant_scope
+
+AGENT_ID = "agent-1"
+
+
+class _AuthenticatedAs:
+ def __init__(self, app: ASGIApp, agent: Agent) -> None:
+ self.app = app
+ self.agent = agent
+
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
+ scope["agent"] = self.agent
+ with tenant_scope(self.agent.tenant_id):
+ await self.app(scope, receive, send)
+
+
+def client() -> Iterator[TestClient]:
+ app = FastAPI()
+ app.include_router(handlers.router, prefix="/agents")
+ app.include_router(operations.router)
+ app.dependency_overrides[get_protocol] = lambda: object()
+ app.dependency_overrides[get_session_factory] = lambda: object()
+ agent = Agent(id=AGENT_ID, name="agent", tenant_id=TENANT_ZERO_ID)
+ with TestClient(_AuthenticatedAs(app, agent)) as client: # type: ignore[arg-type]
+ yield client
+
+
+ ("method", "path"),
+ [
+ ("POST", "moderation/rooms"),
+ ("POST", "moderation/rooms/r-1/invite"),
+ ("GET", "moderation/rooms"),
+ ("GET", "moderation/rooms/r-1"),
+ ("GET", "moderation/agents"),
+ ("GET", "moderation/bridges"),
+ ("PATCH", "moderation/rooms/r-1/security"),
+ ],
+)
+def test_former_moderation_routes_are_not_found(
+ client: TestClient, method: str, path: str
+) -> None:
+ response = client.request(method, f"/agents/{AGENT_ID}/{path}", json={})
+ assert response.status_code == 404
diff --git a/core/tests/switch_core/bridges/agent/api/test_refusal_status_codes.py b/core/tests/switch_core/bridges/agent/api/test_refusal_status_codes.py
index 0a0c2594c..ba0ee3502 100644
--- a/core/tests/switch_core/bridges/agent/api/test_refusal_status_codes.py
+++ b/core/tests/switch_core/bridges/agent/api/test_refusal_status_codes.py
@@ -20,8 +20,9 @@ from fastapi.exceptions import RequestValidationError
from httpx import ASGITransport, AsyncClient, Response
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
-from switch_core.bridges.agent.api import handlers
+from switch_core.bridges.agent.api import handlers, operations
from switch_core.bridges.agent.app import log_http_exceptions, log_validation_errors
+from switch_core.bridges.agent.operations import context as op_context
from switch_core.bridges.agent.protocol.agent_core import AgentCore
from switch_core.db.stores.message_store import MessageStore
from tests.switch_core.bridges.agent.protocol.test_room_roster_authz import (
@@ -39,10 +40,14 @@ async def _request(
app.add_exception_handler(HTTPException, log_http_exceptions) # type: ignore[arg-type]
app.add_exception_handler(RequestValidationError, log_validation_errors) # type: ignore[arg-type]
app.include_router(handlers.router, prefix="/agents")
+ app.include_router(operations.router)
app.dependency_overrides[handlers.get_agent_from_scope] = lambda: SimpleNamespace(
id=caller_id
)
app.dependency_overrides[handlers.get_protocol] = lambda: svc
+ # The ops door runs operations against the process-wide protocol.
+ app.dependency_overrides[operations.get_session_factory] = lambda: None
+ op_context.init_operations_protocol(svc)
transport = ASGITransport(app=app, raise_app_exceptions=False)
async with AsyncClient(transport=transport, base_url="http://test") as client:
@@ -81,8 +86,8 @@ async def test_a_refused_invite_is_403(
r.svc,
r.outsider_id,
"POST",
- f"/agents/{r.outsider_id}/moderation/rooms/{r.room_id}/invite",
- json={"agent_name": "outsider-agent"},
+ f"/agents/{r.outsider_id}/ops/invite_agent_to_room",
+ json={"room_id": r.room_id, "agent_name": "outsider-agent"},
)
assert resp.status_code == 403
@@ -97,8 +102,9 @@ async def test_a_non_member_looking_up_a_room_is_403(
resp = await _request(
r.svc,
r.outsider_id,
- "GET",
- f"/agents/{r.outsider_id}/moderation/rooms/{r.room_id}",
+ "POST",
+ f"/agents/{r.outsider_id}/ops/get_room_detail",
+ json={"room_id": r.room_id},
)
assert resp.status_code == 403