2026-02-09 16:23:41 +05:30
|
|
|
"""Gateway CRUD and template synchronization endpoints."""
|
|
|
|
|
|
2026-02-04 23:07:22 +05:30
|
|
|
from __future__ import annotations
|
|
|
|
|
|
2026-02-09 16:23:41 +05:30
|
|
|
from dataclasses import dataclass
|
|
|
|
|
from typing import TYPE_CHECKING
|
2026-02-10 00:45:15 +05:30
|
|
|
from uuid import UUID, uuid4
|
2026-02-04 23:07:22 +05:30
|
|
|
|
2026-02-09 02:04:14 +05:30
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
|
|
|
|
from sqlmodel import col
|
2026-02-04 23:07:22 +05:30
|
|
|
|
2026-02-08 21:16:26 +05:30
|
|
|
from app.api.deps import require_org_admin
|
2026-02-05 15:42:07 +05:30
|
|
|
from app.core.agent_tokens import generate_agent_token, hash_agent_token
|
2026-02-04 23:07:22 +05:30
|
|
|
from app.core.auth import AuthContext, get_auth_context
|
2026-02-06 16:12:04 +05:30
|
|
|
from app.core.time import utcnow
|
2026-02-09 00:51:26 +05:30
|
|
|
from app.db import crud
|
2026-02-06 19:11:11 +05:30
|
|
|
from app.db.pagination import paginate
|
2026-02-04 23:07:22 +05:30
|
|
|
from app.db.session import get_session
|
2026-02-05 00:21:33 +05:30
|
|
|
from app.integrations.openclaw_gateway import GatewayConfig as GatewayClientConfig
|
2026-02-09 20:44:05 +05:30
|
|
|
from app.integrations.openclaw_gateway import OpenClawGatewayError, ensure_session, send_message
|
2026-02-05 15:42:07 +05:30
|
|
|
from app.models.agents import Agent
|
2026-02-04 23:07:22 +05:30
|
|
|
from app.models.gateways import Gateway
|
2026-02-06 16:12:04 +05:30
|
|
|
from app.schemas.common import OkResponse
|
2026-02-07 04:24:06 +05:30
|
|
|
from app.schemas.gateways import (
|
|
|
|
|
GatewayCreate,
|
|
|
|
|
GatewayRead,
|
|
|
|
|
GatewayTemplatesSyncResult,
|
|
|
|
|
GatewayUpdate,
|
|
|
|
|
)
|
2026-02-06 19:11:11 +05:30
|
|
|
from app.schemas.pagination import DefaultLimitOffsetPage
|
2026-02-09 16:23:41 +05:30
|
|
|
from app.services.agent_provisioning import (
|
|
|
|
|
DEFAULT_HEARTBEAT_CONFIG,
|
2026-02-09 17:24:21 +05:30
|
|
|
MainAgentProvisionRequest,
|
|
|
|
|
ProvisionOptions,
|
2026-02-09 16:23:41 +05:30
|
|
|
provision_main_agent,
|
|
|
|
|
)
|
2026-02-10 00:45:15 +05:30
|
|
|
from app.services.gateway_agents import gateway_agent_session_key, gateway_agent_session_key_for_id
|
2026-02-09 20:44:05 +05:30
|
|
|
from app.services.template_sync import GatewayTemplateSyncOptions
|
|
|
|
|
from app.services.template_sync import sync_gateway_templates as sync_gateway_templates_service
|
2026-02-09 16:23:41 +05:30
|
|
|
|
|
|
|
|
if TYPE_CHECKING:
|
2026-02-09 20:40:17 +05:30
|
|
|
from fastapi_pagination.limit_offset import LimitOffsetPage
|
2026-02-09 16:23:41 +05:30
|
|
|
from sqlmodel.ext.asyncio.session import AsyncSession
|
|
|
|
|
|
|
|
|
|
from app.services.organizations import OrganizationContext
|
2026-02-04 23:07:22 +05:30
|
|
|
|
|
|
|
|
router = APIRouter(prefix="/gateways", tags=["gateways"])
|
2026-02-09 16:23:41 +05:30
|
|
|
SESSION_DEP = Depends(get_session)
|
|
|
|
|
AUTH_DEP = Depends(get_auth_context)
|
|
|
|
|
ORG_ADMIN_DEP = Depends(require_org_admin)
|
|
|
|
|
INCLUDE_MAIN_QUERY = Query(default=True)
|
|
|
|
|
RESET_SESSIONS_QUERY = Query(default=False)
|
|
|
|
|
ROTATE_TOKENS_QUERY = Query(default=False)
|
|
|
|
|
FORCE_BOOTSTRAP_QUERY = Query(default=False)
|
|
|
|
|
BOARD_ID_QUERY = Query(default=None)
|
|
|
|
|
_RUNTIME_TYPE_REFERENCES = (UUID,)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
|
|
|
class _TemplateSyncQuery:
|
|
|
|
|
include_main: bool
|
|
|
|
|
reset_sessions: bool
|
|
|
|
|
rotate_tokens: bool
|
|
|
|
|
force_bootstrap: bool
|
|
|
|
|
board_id: UUID | None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _template_sync_query(
|
|
|
|
|
*,
|
|
|
|
|
include_main: bool = INCLUDE_MAIN_QUERY,
|
|
|
|
|
reset_sessions: bool = RESET_SESSIONS_QUERY,
|
|
|
|
|
rotate_tokens: bool = ROTATE_TOKENS_QUERY,
|
|
|
|
|
force_bootstrap: bool = FORCE_BOOTSTRAP_QUERY,
|
|
|
|
|
board_id: UUID | None = BOARD_ID_QUERY,
|
|
|
|
|
) -> _TemplateSyncQuery:
|
|
|
|
|
return _TemplateSyncQuery(
|
|
|
|
|
include_main=include_main,
|
|
|
|
|
reset_sessions=reset_sessions,
|
|
|
|
|
rotate_tokens=rotate_tokens,
|
|
|
|
|
force_bootstrap=force_bootstrap,
|
|
|
|
|
board_id=board_id,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
SYNC_QUERY_DEP = Depends(_template_sync_query)
|
2026-02-04 23:07:22 +05:30
|
|
|
|
|
|
|
|
|
2026-02-05 15:42:07 +05:30
|
|
|
def _main_agent_name(gateway: Gateway) -> str:
|
2026-02-10 00:45:15 +05:30
|
|
|
return f"{gateway.name} Gateway Agent"
|
2026-02-05 15:42:07 +05:30
|
|
|
|
|
|
|
|
|
2026-02-09 00:51:26 +05:30
|
|
|
async def _require_gateway(
|
|
|
|
|
session: AsyncSession,
|
|
|
|
|
*,
|
|
|
|
|
gateway_id: UUID,
|
|
|
|
|
organization_id: UUID,
|
|
|
|
|
) -> Gateway:
|
2026-02-09 02:04:14 +05:30
|
|
|
gateway = (
|
|
|
|
|
await Gateway.objects.by_id(gateway_id)
|
|
|
|
|
.filter(col(Gateway.organization_id) == organization_id)
|
|
|
|
|
.first(session)
|
2026-02-09 00:51:26 +05:30
|
|
|
)
|
2026-02-09 02:04:14 +05:30
|
|
|
if gateway is None:
|
2026-02-09 16:23:41 +05:30
|
|
|
raise HTTPException(
|
2026-02-09 20:44:05 +05:30
|
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
|
|
|
detail="Gateway not found",
|
2026-02-09 16:23:41 +05:30
|
|
|
)
|
2026-02-09 02:04:14 +05:30
|
|
|
return gateway
|
2026-02-09 00:51:26 +05:30
|
|
|
|
|
|
|
|
|
2026-02-06 16:12:04 +05:30
|
|
|
async def _find_main_agent(
|
|
|
|
|
session: AsyncSession,
|
2026-02-05 15:42:07 +05:30
|
|
|
gateway: Gateway,
|
|
|
|
|
previous_name: str | None = None,
|
|
|
|
|
previous_session_key: str | None = None,
|
|
|
|
|
) -> Agent | None:
|
2026-02-10 00:45:15 +05:30
|
|
|
preferred_session_key = gateway_agent_session_key(gateway)
|
|
|
|
|
if preferred_session_key:
|
|
|
|
|
agent = await Agent.objects.filter_by(
|
|
|
|
|
openclaw_session_id=preferred_session_key,
|
|
|
|
|
).first(
|
|
|
|
|
session,
|
|
|
|
|
)
|
|
|
|
|
if agent:
|
|
|
|
|
return agent
|
2026-02-05 15:42:07 +05:30
|
|
|
if gateway.main_session_key:
|
2026-02-09 16:23:41 +05:30
|
|
|
agent = await Agent.objects.filter_by(
|
|
|
|
|
openclaw_session_id=gateway.main_session_key,
|
|
|
|
|
).first(
|
|
|
|
|
session,
|
2026-02-09 02:04:14 +05:30
|
|
|
)
|
2026-02-05 15:42:07 +05:30
|
|
|
if agent:
|
|
|
|
|
return agent
|
|
|
|
|
if previous_session_key:
|
2026-02-09 16:23:41 +05:30
|
|
|
agent = await Agent.objects.filter_by(
|
|
|
|
|
openclaw_session_id=previous_session_key,
|
|
|
|
|
).first(
|
|
|
|
|
session,
|
2026-02-09 02:04:14 +05:30
|
|
|
)
|
2026-02-05 15:42:07 +05:30
|
|
|
if agent:
|
|
|
|
|
return agent
|
|
|
|
|
names = {_main_agent_name(gateway)}
|
|
|
|
|
if previous_name:
|
|
|
|
|
names.add(f"{previous_name} Main")
|
|
|
|
|
for name in names:
|
2026-02-09 02:04:14 +05:30
|
|
|
agent = await Agent.objects.filter_by(name=name).first(session)
|
2026-02-05 15:42:07 +05:30
|
|
|
if agent:
|
|
|
|
|
return agent
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def _ensure_main_agent(
|
2026-02-06 16:12:04 +05:30
|
|
|
session: AsyncSession,
|
2026-02-05 15:42:07 +05:30
|
|
|
gateway: Gateway,
|
|
|
|
|
auth: AuthContext,
|
|
|
|
|
*,
|
2026-02-09 16:23:41 +05:30
|
|
|
previous: tuple[str | None, str | None] | None = None,
|
2026-02-05 15:42:07 +05:30
|
|
|
action: str = "provision",
|
|
|
|
|
) -> Agent | None:
|
2026-02-10 00:45:15 +05:30
|
|
|
if not gateway.url:
|
2026-02-05 15:42:07 +05:30
|
|
|
return None
|
2026-02-10 00:45:15 +05:30
|
|
|
session_key = gateway_agent_session_key(gateway)
|
|
|
|
|
if gateway.main_session_key != session_key:
|
|
|
|
|
gateway.main_session_key = session_key
|
|
|
|
|
gateway.updated_at = utcnow()
|
|
|
|
|
session.add(gateway)
|
2026-02-09 16:23:41 +05:30
|
|
|
agent = await _find_main_agent(
|
|
|
|
|
session,
|
|
|
|
|
gateway,
|
|
|
|
|
previous_name=previous[0] if previous else None,
|
|
|
|
|
previous_session_key=previous[1] if previous else None,
|
|
|
|
|
)
|
2026-02-05 15:42:07 +05:30
|
|
|
if agent is None:
|
|
|
|
|
agent = Agent(
|
|
|
|
|
name=_main_agent_name(gateway),
|
|
|
|
|
status="provisioning",
|
|
|
|
|
board_id=None,
|
|
|
|
|
is_board_lead=False,
|
2026-02-10 00:45:15 +05:30
|
|
|
openclaw_session_id=session_key,
|
2026-02-05 15:42:07 +05:30
|
|
|
heartbeat_config=DEFAULT_HEARTBEAT_CONFIG.copy(),
|
|
|
|
|
identity_profile={
|
2026-02-10 00:45:15 +05:30
|
|
|
"role": "Gateway Agent",
|
2026-02-05 15:42:07 +05:30
|
|
|
"communication_style": "direct, concise, practical",
|
|
|
|
|
"emoji": ":compass:",
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
session.add(agent)
|
|
|
|
|
agent.name = _main_agent_name(gateway)
|
2026-02-10 00:45:15 +05:30
|
|
|
agent.openclaw_session_id = session_key
|
2026-02-05 15:42:07 +05:30
|
|
|
raw_token = generate_agent_token()
|
|
|
|
|
agent.agent_token_hash = hash_agent_token(raw_token)
|
2026-02-06 16:12:04 +05:30
|
|
|
agent.provision_requested_at = utcnow()
|
2026-02-05 15:42:07 +05:30
|
|
|
agent.provision_action = action
|
2026-02-06 16:12:04 +05:30
|
|
|
agent.updated_at = utcnow()
|
2026-02-05 15:42:07 +05:30
|
|
|
if agent.heartbeat_config is None:
|
|
|
|
|
agent.heartbeat_config = DEFAULT_HEARTBEAT_CONFIG.copy()
|
|
|
|
|
session.add(agent)
|
2026-02-06 16:12:04 +05:30
|
|
|
await session.commit()
|
|
|
|
|
await session.refresh(agent)
|
2026-02-05 15:42:07 +05:30
|
|
|
try:
|
2026-02-09 17:24:21 +05:30
|
|
|
await provision_main_agent(
|
|
|
|
|
agent,
|
|
|
|
|
MainAgentProvisionRequest(
|
|
|
|
|
gateway=gateway,
|
|
|
|
|
auth_token=raw_token,
|
|
|
|
|
user=auth.user,
|
2026-02-10 00:45:15 +05:30
|
|
|
session_key=session_key,
|
2026-02-09 17:24:21 +05:30
|
|
|
options=ProvisionOptions(action=action),
|
|
|
|
|
),
|
|
|
|
|
)
|
2026-02-05 15:48:54 +05:30
|
|
|
await ensure_session(
|
2026-02-10 00:45:15 +05:30
|
|
|
session_key,
|
2026-02-06 02:43:08 +05:30
|
|
|
config=GatewayClientConfig(url=gateway.url, token=gateway.token),
|
|
|
|
|
label=agent.name,
|
2026-02-05 15:48:54 +05:30
|
|
|
)
|
|
|
|
|
await send_message(
|
|
|
|
|
(
|
|
|
|
|
f"Hello {agent.name}. Your gateway provisioning was updated.\n\n"
|
2026-02-05 19:06:32 +05:30
|
|
|
"Please re-read AGENTS.md, USER.md, HEARTBEAT.md, and TOOLS.md. "
|
2026-02-09 16:23:41 +05:30
|
|
|
"If BOOTSTRAP.md exists, run it once then delete it. "
|
|
|
|
|
"Begin heartbeats after startup."
|
2026-02-05 15:48:54 +05:30
|
|
|
),
|
2026-02-10 00:45:15 +05:30
|
|
|
session_key=session_key,
|
2026-02-05 15:48:54 +05:30
|
|
|
config=GatewayClientConfig(url=gateway.url, token=gateway.token),
|
|
|
|
|
deliver=True,
|
|
|
|
|
)
|
2026-02-05 15:42:07 +05:30
|
|
|
except OpenClawGatewayError:
|
|
|
|
|
# Best-effort provisioning.
|
|
|
|
|
pass
|
|
|
|
|
return agent
|
|
|
|
|
|
|
|
|
|
|
2026-02-06 19:11:11 +05:30
|
|
|
@router.get("", response_model=DefaultLimitOffsetPage[GatewayRead])
|
2026-02-06 16:12:04 +05:30
|
|
|
async def list_gateways(
|
2026-02-09 16:23:41 +05:30
|
|
|
session: AsyncSession = SESSION_DEP,
|
|
|
|
|
ctx: OrganizationContext = ORG_ADMIN_DEP,
|
2026-02-09 20:40:17 +05:30
|
|
|
) -> LimitOffsetPage[GatewayRead]:
|
2026-02-09 16:23:41 +05:30
|
|
|
"""List gateways for the caller's organization."""
|
2026-02-08 21:16:26 +05:30
|
|
|
statement = (
|
2026-02-09 02:04:14 +05:30
|
|
|
Gateway.objects.filter_by(organization_id=ctx.organization.id)
|
2026-02-08 21:16:26 +05:30
|
|
|
.order_by(col(Gateway.created_at).desc())
|
2026-02-09 00:51:26 +05:30
|
|
|
.statement
|
2026-02-08 21:16:26 +05:30
|
|
|
)
|
2026-02-06 19:11:11 +05:30
|
|
|
return await paginate(session, statement)
|
2026-02-04 23:07:22 +05:30
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.post("", response_model=GatewayRead)
|
|
|
|
|
async def create_gateway(
|
|
|
|
|
payload: GatewayCreate,
|
2026-02-09 16:23:41 +05:30
|
|
|
session: AsyncSession = SESSION_DEP,
|
|
|
|
|
auth: AuthContext = AUTH_DEP,
|
|
|
|
|
ctx: OrganizationContext = ORG_ADMIN_DEP,
|
2026-02-04 23:07:22 +05:30
|
|
|
) -> Gateway:
|
2026-02-09 16:23:41 +05:30
|
|
|
"""Create a gateway and provision or refresh its main agent."""
|
2026-02-04 23:07:22 +05:30
|
|
|
data = payload.model_dump()
|
2026-02-10 00:45:15 +05:30
|
|
|
gateway_id = uuid4()
|
|
|
|
|
data["id"] = gateway_id
|
2026-02-08 21:16:26 +05:30
|
|
|
data["organization_id"] = ctx.organization.id
|
2026-02-10 00:45:15 +05:30
|
|
|
data["main_session_key"] = gateway_agent_session_key_for_id(gateway_id)
|
2026-02-09 00:51:26 +05:30
|
|
|
gateway = await crud.create(session, Gateway, **data)
|
2026-02-05 15:42:07 +05:30
|
|
|
await _ensure_main_agent(session, gateway, auth, action="provision")
|
2026-02-04 23:07:22 +05:30
|
|
|
return gateway
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.get("/{gateway_id}", response_model=GatewayRead)
|
2026-02-06 16:12:04 +05:30
|
|
|
async def get_gateway(
|
2026-02-04 23:07:22 +05:30
|
|
|
gateway_id: UUID,
|
2026-02-09 16:23:41 +05:30
|
|
|
session: AsyncSession = SESSION_DEP,
|
|
|
|
|
ctx: OrganizationContext = ORG_ADMIN_DEP,
|
2026-02-04 23:07:22 +05:30
|
|
|
) -> Gateway:
|
2026-02-09 16:23:41 +05:30
|
|
|
"""Return one gateway by id for the caller's organization."""
|
2026-02-09 00:51:26 +05:30
|
|
|
return await _require_gateway(
|
|
|
|
|
session,
|
|
|
|
|
gateway_id=gateway_id,
|
|
|
|
|
organization_id=ctx.organization.id,
|
|
|
|
|
)
|
2026-02-04 23:07:22 +05:30
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.patch("/{gateway_id}", response_model=GatewayRead)
|
|
|
|
|
async def update_gateway(
|
|
|
|
|
gateway_id: UUID,
|
|
|
|
|
payload: GatewayUpdate,
|
2026-02-09 16:23:41 +05:30
|
|
|
session: AsyncSession = SESSION_DEP,
|
|
|
|
|
auth: AuthContext = AUTH_DEP,
|
|
|
|
|
ctx: OrganizationContext = ORG_ADMIN_DEP,
|
2026-02-04 23:07:22 +05:30
|
|
|
) -> Gateway:
|
2026-02-09 16:23:41 +05:30
|
|
|
"""Patch a gateway and refresh the main-agent provisioning state."""
|
2026-02-09 00:51:26 +05:30
|
|
|
gateway = await _require_gateway(
|
|
|
|
|
session,
|
|
|
|
|
gateway_id=gateway_id,
|
|
|
|
|
organization_id=ctx.organization.id,
|
|
|
|
|
)
|
2026-02-05 15:42:07 +05:30
|
|
|
previous_name = gateway.name
|
|
|
|
|
previous_session_key = gateway.main_session_key
|
2026-02-04 23:07:22 +05:30
|
|
|
updates = payload.model_dump(exclude_unset=True)
|
2026-02-09 00:51:26 +05:30
|
|
|
await crud.patch(session, gateway, updates)
|
2026-02-05 15:42:07 +05:30
|
|
|
await _ensure_main_agent(
|
|
|
|
|
session,
|
|
|
|
|
gateway,
|
|
|
|
|
auth,
|
2026-02-09 16:23:41 +05:30
|
|
|
previous=(previous_name, previous_session_key),
|
2026-02-05 15:42:07 +05:30
|
|
|
action="update",
|
|
|
|
|
)
|
2026-02-04 23:07:22 +05:30
|
|
|
return gateway
|
|
|
|
|
|
|
|
|
|
|
2026-02-07 04:24:06 +05:30
|
|
|
@router.post("/{gateway_id}/templates/sync", response_model=GatewayTemplatesSyncResult)
|
|
|
|
|
async def sync_gateway_templates(
|
|
|
|
|
gateway_id: UUID,
|
2026-02-09 16:23:41 +05:30
|
|
|
sync_query: _TemplateSyncQuery = SYNC_QUERY_DEP,
|
|
|
|
|
session: AsyncSession = SESSION_DEP,
|
|
|
|
|
auth: AuthContext = AUTH_DEP,
|
|
|
|
|
ctx: OrganizationContext = ORG_ADMIN_DEP,
|
2026-02-07 04:24:06 +05:30
|
|
|
) -> GatewayTemplatesSyncResult:
|
2026-02-09 16:23:41 +05:30
|
|
|
"""Sync templates for a gateway and optionally rotate runtime settings."""
|
2026-02-09 00:51:26 +05:30
|
|
|
gateway = await _require_gateway(
|
|
|
|
|
session,
|
|
|
|
|
gateway_id=gateway_id,
|
|
|
|
|
organization_id=ctx.organization.id,
|
|
|
|
|
)
|
2026-02-07 04:24:06 +05:30
|
|
|
return await sync_gateway_templates_service(
|
|
|
|
|
session,
|
|
|
|
|
gateway,
|
2026-02-09 16:23:41 +05:30
|
|
|
GatewayTemplateSyncOptions(
|
|
|
|
|
user=auth.user,
|
|
|
|
|
include_main=sync_query.include_main,
|
|
|
|
|
reset_sessions=sync_query.reset_sessions,
|
|
|
|
|
rotate_tokens=sync_query.rotate_tokens,
|
|
|
|
|
force_bootstrap=sync_query.force_bootstrap,
|
|
|
|
|
board_id=sync_query.board_id,
|
|
|
|
|
),
|
2026-02-07 04:24:06 +05:30
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
2026-02-06 16:12:04 +05:30
|
|
|
@router.delete("/{gateway_id}", response_model=OkResponse)
|
|
|
|
|
async def delete_gateway(
|
2026-02-04 23:07:22 +05:30
|
|
|
gateway_id: UUID,
|
2026-02-09 16:23:41 +05:30
|
|
|
session: AsyncSession = SESSION_DEP,
|
|
|
|
|
ctx: OrganizationContext = ORG_ADMIN_DEP,
|
2026-02-06 16:12:04 +05:30
|
|
|
) -> OkResponse:
|
2026-02-09 16:23:41 +05:30
|
|
|
"""Delete a gateway in the caller's organization."""
|
2026-02-09 00:51:26 +05:30
|
|
|
gateway = await _require_gateway(
|
|
|
|
|
session,
|
|
|
|
|
gateway_id=gateway_id,
|
|
|
|
|
organization_id=ctx.organization.id,
|
|
|
|
|
)
|
|
|
|
|
await crud.delete(session, gateway)
|
2026-02-06 16:12:04 +05:30
|
|
|
return OkResponse()
|