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
"""The owner's management routes, mounted on the gateway at `/management`.
Cookie-authenticated through `get_current_user`, which binds the caller's
tenant; every route then acts only on the caller's own controllers and
agents. Someone else's is answered exactly like one that does not exist, so
nothing about another person's machines is disclosed.
Failures use the same error envelope as the controller routes.
"""
from __future__ import annotations
from typing import Annotated, Any
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from switch_core.bridges.agent.protocol.agent_core import AgentCore
from switch_core.connections.broker import ServiceBroker, get_service_broker
from switch_core.db.models import ServiceTokenIssuance, User, require_tenant_id
from switch_core.gateway.auth import get_current_user
from switch_core.gateway.dependencies import get_protocol, get_session
from switch_core.management.dependencies import get_management
from switch_core.management.errors import ManagementRoute
from switch_core.management.schemas import (
ConsoleControllerRequest,
ControllerDescription,
CreateManagedAgentRequest,
CreateOperationRequest,
PatchManagedAgentRequest,
PutManagedAgentRequest,
UpdateControllerRequest,
wire_time,
)
from switch_core.management.sealed_logins import PutSealedLoginRequest
from switch_core.management.service import ManagementService, placement_from
router = APIRouter(route_class=ManagementRoute, tags=["agent management"])
Management = Annotated[ManagementService, Depends(get_management)]
Session = Annotated[AsyncSession, Depends(get_session)]
CurrentUser = Annotated[User, Depends(get_current_user)]
Protocol = Annotated[AgentCore, Depends(get_protocol)]
Broker = Annotated[ServiceBroker, Depends(get_service_broker)]
def _controller(view: dict[str, Any]) -> dict[str, Any]:
"""`view` with what the caller may do with the machine. Every machine
these routes return is the caller's own, to rename and remove; removing a
revoked one again changes nothing, which `revoked_at` says."""
return {**view, "can_edit": True, "can_remove": True}
def _managed_agent(view: dict[str, Any]) -> dict[str, Any]:
"""`view` with what the caller may do with the managed agent: every one
these routes return is the caller's own, to change or stop managing."""
return {**view, "can_edit": True, "can_delete": True}
async def _revoke_controller_tokens(
session: AsyncSession, broker: ServiceBroker, *conditions: Any
) -> None:
"""Revoke, now, the service tokens a controller change left orphaned.
The periodic pass would find them too; this saves the wait. A failure is
logged by the broker and left queued for that pass.
"""
await session.commit()
await broker.revoke_pending(
session, (ServiceTokenIssuance.principal == "controller", *conditions)
)
@router.post("/enrollment-codes", status_code=201)
async def create_enrollment_code(
session: Session, user: CurrentUser, management: Management
) -> dict[str, str | None]:
"""A one-time code, and the agent bridge's public origin a controller
enrolls against with it (`server_url`, null when `GATEWAY_PUBLIC_URL` is
not set: the page the owner is on is the gateway, which need not serve the
agent bridge, so it is no stand-in)."""
code, expires_at = await management.issue_enrollment_code(session, owner_id=user.id)
return {
"code": code,
"expires_at": wire_time(expires_at),
"server_url": management.settings.server_url,
}
@router.post("/controllers", status_code=201)
async def enroll_console(
body: ConsoleControllerRequest,
session: Session,
user: CurrentUser,
management: Management,
) -> dict[str, str]:
controller, credential = await management.create_controller(
session,
owner_id=user.id,
description=ControllerDescription(
kind=body.kind,
name=body.name,
description=body.description,
platform=body.platform,
version=body.version,
),
public_key=body.public_key,
)
return {"controller_id": controller.id, "credential": credential}
@router.get("/controllers")
async def list_controllers(
session: Session, user: CurrentUser, management: Management
) -> list[dict[str, Any]]:
return [
_controller(view)
for view in await management.list_controllers(
session, require_tenant_id(), user.id
)
]
@router.patch("/controllers/{controller_id}")
async def update_controller(
controller_id: str,
body: UpdateControllerRequest,
session: Session,
user: CurrentUser,
management: Management,
) -> dict[str, Any]:
"""Rename the machine and/or change its description."""
return _controller(
await management.update_controller(
session,
require_tenant_id(),
user.id,
controller_id,
{key: getattr(body, key) for key in body.model_fields_set},
)
)
@router.delete("/controllers/{controller_id}")
async def revoke_controller(
controller_id: str,
session: Session,
user: CurrentUser,
management: Management,
broker: Broker,
) -> dict[str, bool]:
await management.revoke_controller(
session, require_tenant_id(), user.id, controller_id
)
await _revoke_controller_tokens(
session, broker, ServiceTokenIssuance.controller_id == controller_id
)
return {"ok": True}
@router.get("/controllers/{controller_id}/provider-logins")
async def list_sealed_logins(
controller_id: str, session: Session, user: CurrentUser, management: Management
) -> list[dict[str, Any]]:
"""The provider logins given to this machine: which, and which revision;
never what they hold."""
return await management.list_sealed_logins(
session, require_tenant_id(), user.id, controller_id
)
@router.put("/controllers/{controller_id}/provider-logins/{provider}")
async def give_sealed_login(
controller_id: str,
provider: str,
body: PutSealedLoginRequest,
session: Session,
user: CurrentUser,
management: Management,
) -> dict[str, Any]:
"""Give this machine a provider login, sealed to its `public_key` by the
caller's client. Returns the login and the `provider.login` operation
whose result says whether the provider signs in with it."""
return await management.give_sealed_login(
session, require_tenant_id(), user.id, controller_id, provider, body.sealed
)
@router.delete("/controllers/{controller_id}/provider-logins/{provider}")
async def withdraw_sealed_login(
controller_id: str,
provider: str,
session: Session,
user: CurrentUser,
management: Management,
) -> dict[str, bool]:
await management.withdraw_sealed_login(
session, require_tenant_id(), user.id, controller_id, provider
)
return {"ok": True}
@router.get("/agents")
async def list_managed_agents(
session: Session, user: CurrentUser, management: Management
) -> list[dict[str, Any]]:
return [
_managed_agent(view)
for view in await management.list_managed_agents(
session, require_tenant_id(), user.id
)
]
@router.get("/agents/{agent_id}")
async def get_managed_agent(
agent_id: str, session: Session, user: CurrentUser, management: Management
) -> dict[str, Any]:
return _managed_agent(
await management.get_managed_agent(
session, require_tenant_id(), user.id, agent_id
)
)
@router.post("/agents", status_code=201)
async def create_managed_agent(
body: CreateManagedAgentRequest,
session: Session,
user: CurrentUser,
management: Management,
protocol: Protocol,
) -> dict[str, Any]:
return _managed_agent(
await management.create_managed_agent(
session, require_tenant_id(), user.id, body, protocol
)
)
@router.put("/agents/{agent_id}")
async def put_managed_agent(
agent_id: str,
body: PutManagedAgentRequest,
session: Session,
user: CurrentUser,
management: Management,
protocol: Protocol,
broker: Broker,
) -> dict[str, Any]:
view = await management.put_managed_agent(
session,
require_tenant_id(),
user.id,
agent_id,
placement_from(body.controller_id, body.desired_state, body.definition),
protocol,
)
await _revoke_controller_tokens(
session, broker, ServiceTokenIssuance.agent_id == agent_id
)
return _managed_agent(view)
@router.patch("/agents/{agent_id}")
async def patch_managed_agent(
agent_id: str,
body: PatchManagedAgentRequest,
session: Session,
user: CurrentUser,
management: Management,
protocol: Protocol,
broker: Broker,
) -> dict[str, Any]:
view = await management.patch_managed_agent(
session,
require_tenant_id(),
user.id,
agent_id,
definition=body.definition,
desired_state=body.desired_state,
controller_id=body.controller_id,
controller_id_given="controller_id" in body.model_fields_set,
protocol=protocol,
expected_revision=None,
)
await _revoke_controller_tokens(
session, broker, ServiceTokenIssuance.agent_id == agent_id
)
return _managed_agent(view)
@router.delete("/agents/{agent_id}")
async def delete_managed_agent(
agent_id: str,
session: Session,
user: CurrentUser,
management: Management,
broker: Broker,
) -> dict[str, bool]:
await management.delete_managed_agent(
session, require_tenant_id(), user.id, agent_id
)
await _revoke_controller_tokens(
session, broker, ServiceTokenIssuance.agent_id == agent_id
)
return {"ok": True}
@router.post("/operations", status_code=201)
async def create_operation(
body: CreateOperationRequest,
session: Session,
user: CurrentUser,
management: Management,
) -> dict[str, Any]:
return await management.create_operation(
session,
require_tenant_id(),
user.id,
controller_id=body.controller_id,
agent_id=body.agent_id,
kind=body.kind,
params=body.params,
)
@router.get("/operations")
async def list_operations(
session: Session,
user: CurrentUser,
management: Management,
controller_id: str | None = None,
) -> list[dict[str, Any]]:
return await management.list_operations(
session, require_tenant_id(), user.id, controller_id
)