2026-02-04 02:28:51 +05:30
|
|
|
from __future__ import annotations
|
|
|
|
|
|
2026-02-05 22:51:46 +05:30
|
|
|
import asyncio
|
|
|
|
|
import json
|
2026-02-06 02:43:08 +05:30
|
|
|
import re
|
|
|
|
|
from datetime import datetime, timedelta, timezone
|
2026-02-04 16:04:52 +05:30
|
|
|
from uuid import UUID, uuid4
|
2026-02-04 02:28:51 +05:30
|
|
|
|
2026-02-05 22:51:46 +05:30
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
|
|
|
|
|
from sqlalchemy import asc, or_, update
|
2026-02-05 00:21:33 +05:30
|
|
|
from sqlmodel import Session, col, select
|
2026-02-05 22:51:46 +05:30
|
|
|
from sse_starlette.sse import EventSourceResponse
|
|
|
|
|
from starlette.concurrency import run_in_threadpool
|
2026-02-04 02:28:51 +05:30
|
|
|
|
2026-02-04 14:58:14 +05:30
|
|
|
from app.api.deps import ActorContext, require_admin_auth, require_admin_or_agent
|
2026-02-05 01:40:28 +05:30
|
|
|
from app.core.agent_tokens import generate_agent_token, hash_agent_token
|
2026-02-04 03:57:19 +05:30
|
|
|
from app.core.auth import AuthContext
|
2026-02-05 22:51:46 +05:30
|
|
|
from app.db.session import engine, get_session
|
2026-02-05 00:21:33 +05:30
|
|
|
from app.integrations.openclaw_gateway import GatewayConfig as GatewayClientConfig
|
|
|
|
|
from app.integrations.openclaw_gateway import OpenClawGatewayError, ensure_session, send_message
|
2026-02-04 14:58:14 +05:30
|
|
|
from app.models.activity_events import ActivityEvent
|
2026-02-05 00:21:33 +05:30
|
|
|
from app.models.agents import Agent
|
2026-02-04 16:04:52 +05:30
|
|
|
from app.models.boards import Board
|
2026-02-04 23:07:22 +05:30
|
|
|
from app.models.gateways import Gateway
|
2026-02-05 03:08:47 +05:30
|
|
|
from app.models.tasks import Task
|
2026-02-06 02:43:08 +05:30
|
|
|
from app.schemas.agents import (
|
|
|
|
|
AgentCreate,
|
|
|
|
|
AgentHeartbeat,
|
|
|
|
|
AgentHeartbeatCreate,
|
|
|
|
|
AgentRead,
|
|
|
|
|
AgentUpdate,
|
|
|
|
|
)
|
2026-02-04 03:57:19 +05:30
|
|
|
from app.services.activity_log import record_activity
|
2026-02-04 17:05:58 +05:30
|
|
|
from app.services.agent_provisioning import (
|
|
|
|
|
DEFAULT_HEARTBEAT_CONFIG,
|
2026-02-05 01:40:28 +05:30
|
|
|
cleanup_agent,
|
2026-02-05 01:27:48 +05:30
|
|
|
provision_agent,
|
2026-02-05 19:29:17 +05:30
|
|
|
provision_main_agent,
|
2026-02-04 17:05:58 +05:30
|
|
|
)
|
2026-02-04 02:28:51 +05:30
|
|
|
|
|
|
|
|
router = APIRouter(prefix="/agents", tags=["agents"])
|
|
|
|
|
|
|
|
|
|
OFFLINE_AFTER = timedelta(minutes=10)
|
2026-02-04 03:46:46 +05:30
|
|
|
AGENT_SESSION_PREFIX = "agent"
|
2026-02-04 02:28:51 +05:30
|
|
|
|
|
|
|
|
|
2026-02-05 22:51:46 +05:30
|
|
|
def _parse_since(value: str | None) -> datetime | None:
|
|
|
|
|
if not value:
|
|
|
|
|
return None
|
|
|
|
|
normalized = value.strip()
|
|
|
|
|
if not normalized:
|
|
|
|
|
return None
|
|
|
|
|
normalized = normalized.replace("Z", "+00:00")
|
|
|
|
|
try:
|
|
|
|
|
parsed = datetime.fromisoformat(normalized)
|
|
|
|
|
except ValueError:
|
|
|
|
|
return None
|
|
|
|
|
if parsed.tzinfo is not None:
|
|
|
|
|
return parsed.astimezone(timezone.utc).replace(tzinfo=None)
|
|
|
|
|
return parsed
|
|
|
|
|
|
|
|
|
|
|
2026-02-05 02:21:38 +05:30
|
|
|
def _normalize_identity_profile(
|
|
|
|
|
profile: dict[str, object] | None,
|
|
|
|
|
) -> dict[str, str] | None:
|
|
|
|
|
if not profile:
|
|
|
|
|
return None
|
|
|
|
|
normalized: dict[str, str] = {}
|
|
|
|
|
for key, raw in profile.items():
|
|
|
|
|
if raw is None:
|
|
|
|
|
continue
|
|
|
|
|
if isinstance(raw, list):
|
|
|
|
|
parts = [str(item).strip() for item in raw if str(item).strip()]
|
|
|
|
|
if not parts:
|
|
|
|
|
continue
|
|
|
|
|
normalized[key] = ", ".join(parts)
|
|
|
|
|
continue
|
|
|
|
|
value = str(raw).strip()
|
|
|
|
|
if value:
|
|
|
|
|
normalized[key] = value
|
|
|
|
|
return normalized or None
|
|
|
|
|
|
|
|
|
|
|
2026-02-04 02:28:51 +05:30
|
|
|
def _slugify(value: str) -> str:
|
|
|
|
|
slug = re.sub(r"[^a-z0-9]+", "-", value.lower()).strip("-")
|
|
|
|
|
return slug or uuid4().hex
|
|
|
|
|
|
|
|
|
|
|
2026-02-04 03:46:46 +05:30
|
|
|
def _build_session_key(agent_name: str) -> str:
|
|
|
|
|
return f"{AGENT_SESSION_PREFIX}:{_slugify(agent_name)}:main"
|
2026-02-04 02:28:51 +05:30
|
|
|
|
|
|
|
|
|
2026-02-04 17:14:47 +05:30
|
|
|
def _workspace_path(agent_name: str, workspace_root: str | None) -> str:
|
|
|
|
|
if not workspace_root:
|
|
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
2026-02-04 23:07:22 +05:30
|
|
|
detail="Gateway workspace_root is required",
|
2026-02-04 17:14:47 +05:30
|
|
|
)
|
|
|
|
|
root = workspace_root.rstrip("/")
|
|
|
|
|
return f"{root}/workspace-{_slugify(agent_name)}"
|
|
|
|
|
|
|
|
|
|
|
2026-02-04 16:04:52 +05:30
|
|
|
def _require_board(session: Session, board_id: UUID | str | None) -> Board:
|
|
|
|
|
if not board_id:
|
|
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
|
|
|
detail="board_id is required",
|
|
|
|
|
)
|
|
|
|
|
board = session.get(Board, board_id)
|
|
|
|
|
if board is None:
|
|
|
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Board not found")
|
|
|
|
|
return board
|
|
|
|
|
|
|
|
|
|
|
2026-02-05 00:21:33 +05:30
|
|
|
def _require_gateway(session: Session, board: Board) -> tuple[Gateway, GatewayClientConfig]:
|
2026-02-04 23:07:22 +05:30
|
|
|
if not board.gateway_id:
|
2026-02-04 16:04:52 +05:30
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
2026-02-04 23:07:22 +05:30
|
|
|
detail="Board gateway_id is required",
|
2026-02-04 16:04:52 +05:30
|
|
|
)
|
2026-02-04 23:07:22 +05:30
|
|
|
gateway = session.get(Gateway, board.gateway_id)
|
|
|
|
|
if gateway is None:
|
2026-02-04 17:14:47 +05:30
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
2026-02-04 23:07:22 +05:30
|
|
|
detail="Board gateway_id is invalid",
|
2026-02-04 17:14:47 +05:30
|
|
|
)
|
2026-02-04 23:07:22 +05:30
|
|
|
if not gateway.main_session_key:
|
2026-02-04 17:14:47 +05:30
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
2026-02-04 23:07:22 +05:30
|
|
|
detail="Gateway main_session_key is required",
|
2026-02-04 17:14:47 +05:30
|
|
|
)
|
2026-02-04 23:07:22 +05:30
|
|
|
if not gateway.url:
|
|
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
|
|
|
detail="Gateway url is required",
|
|
|
|
|
)
|
|
|
|
|
if not gateway.workspace_root:
|
|
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
|
|
|
detail="Gateway workspace_root is required",
|
|
|
|
|
)
|
|
|
|
|
return gateway, GatewayClientConfig(url=gateway.url, token=gateway.token)
|
2026-02-04 16:04:52 +05:30
|
|
|
|
|
|
|
|
|
2026-02-05 19:29:17 +05:30
|
|
|
def _gateway_client_config(gateway: Gateway) -> GatewayClientConfig:
|
|
|
|
|
if not gateway.url:
|
|
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
|
|
|
detail="Gateway url is required",
|
|
|
|
|
)
|
|
|
|
|
return GatewayClientConfig(url=gateway.url, token=gateway.token)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _get_gateway_main_session_keys(session: Session) -> set[str]:
|
|
|
|
|
keys = session.exec(select(Gateway.main_session_key)).all()
|
|
|
|
|
return {key for key in keys if key}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _is_gateway_main(agent: Agent, main_session_keys: set[str]) -> bool:
|
|
|
|
|
return bool(agent.openclaw_session_id and agent.openclaw_session_id in main_session_keys)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _to_agent_read(agent: Agent, main_session_keys: set[str]) -> AgentRead:
|
|
|
|
|
model = AgentRead.model_validate(agent, from_attributes=True)
|
|
|
|
|
return model.model_copy(update={"is_gateway_main": _is_gateway_main(agent, main_session_keys)})
|
|
|
|
|
|
|
|
|
|
|
2026-02-06 02:43:08 +05:30
|
|
|
def _find_gateway_for_main_session(session: Session, session_key: str | None) -> Gateway | None:
|
2026-02-05 19:29:17 +05:30
|
|
|
if not session_key:
|
|
|
|
|
return None
|
2026-02-06 02:43:08 +05:30
|
|
|
return session.exec(select(Gateway).where(Gateway.main_session_key == session_key)).first()
|
2026-02-05 19:29:17 +05:30
|
|
|
|
|
|
|
|
|
2026-02-04 16:04:52 +05:30
|
|
|
async def _ensure_gateway_session(
|
|
|
|
|
agent_name: str,
|
2026-02-04 23:07:22 +05:30
|
|
|
config: GatewayClientConfig,
|
2026-02-04 16:04:52 +05:30
|
|
|
) -> tuple[str, str | None]:
|
2026-02-04 03:46:46 +05:30
|
|
|
session_key = _build_session_key(agent_name)
|
2026-02-04 02:28:51 +05:30
|
|
|
try:
|
2026-02-04 16:04:52 +05:30
|
|
|
await ensure_session(session_key, config=config, label=agent_name)
|
2026-02-04 03:46:46 +05:30
|
|
|
return session_key, None
|
2026-02-04 02:28:51 +05:30
|
|
|
except OpenClawGatewayError as exc:
|
2026-02-04 03:46:46 +05:30
|
|
|
return session_key, str(exc)
|
2026-02-04 02:28:51 +05:30
|
|
|
|
|
|
|
|
|
|
|
|
|
def _with_computed_status(agent: Agent) -> Agent:
|
|
|
|
|
now = datetime.utcnow()
|
2026-02-04 18:25:13 +05:30
|
|
|
if agent.status in {"deleting", "updating"}:
|
2026-02-04 17:05:58 +05:30
|
|
|
return agent
|
2026-02-04 15:16:28 +05:30
|
|
|
if agent.last_seen_at is None:
|
|
|
|
|
agent.status = "provisioning"
|
|
|
|
|
elif now - agent.last_seen_at > OFFLINE_AFTER:
|
2026-02-04 02:28:51 +05:30
|
|
|
agent.status = "offline"
|
|
|
|
|
return agent
|
|
|
|
|
|
|
|
|
|
|
2026-02-05 22:51:46 +05:30
|
|
|
def _serialize_agent(agent: Agent, main_session_keys: set[str]) -> dict[str, object]:
|
2026-02-06 02:43:08 +05:30
|
|
|
return _to_agent_read(_with_computed_status(agent), main_session_keys).model_dump(mode="json")
|
2026-02-05 22:51:46 +05:30
|
|
|
|
|
|
|
|
|
|
|
|
|
def _fetch_agent_events(
|
|
|
|
|
board_id: UUID | None,
|
|
|
|
|
since: datetime,
|
|
|
|
|
) -> list[Agent]:
|
|
|
|
|
with Session(engine) as session:
|
|
|
|
|
statement = select(Agent)
|
|
|
|
|
if board_id:
|
|
|
|
|
statement = statement.where(col(Agent.board_id) == board_id)
|
2026-02-06 02:43:08 +05:30
|
|
|
statement = statement.where(
|
|
|
|
|
or_(
|
|
|
|
|
col(Agent.updated_at) >= since,
|
|
|
|
|
col(Agent.last_seen_at) >= since,
|
2026-02-05 22:51:46 +05:30
|
|
|
)
|
2026-02-06 02:43:08 +05:30
|
|
|
).order_by(asc(col(Agent.updated_at)))
|
2026-02-05 22:51:46 +05:30
|
|
|
return list(session.exec(statement))
|
|
|
|
|
|
|
|
|
|
|
2026-02-04 02:28:51 +05:30
|
|
|
def _record_heartbeat(session: Session, agent: Agent) -> None:
|
2026-02-04 03:57:19 +05:30
|
|
|
record_activity(
|
|
|
|
|
session,
|
2026-02-04 02:28:51 +05:30
|
|
|
event_type="agent.heartbeat",
|
|
|
|
|
message=f"Heartbeat received from {agent.name}.",
|
|
|
|
|
agent_id=agent.id,
|
|
|
|
|
)
|
2026-02-04 03:57:19 +05:30
|
|
|
|
|
|
|
|
|
2026-02-05 00:21:33 +05:30
|
|
|
def _record_instruction_failure(session: Session, agent: Agent, error: str, action: str) -> None:
|
2026-02-04 17:05:58 +05:30
|
|
|
action_label = action.replace("_", " ").capitalize()
|
2026-02-04 03:57:19 +05:30
|
|
|
record_activity(
|
|
|
|
|
session,
|
2026-02-04 17:05:58 +05:30
|
|
|
event_type=f"agent.{action}.failed",
|
|
|
|
|
message=f"{action_label} message failed: {error}",
|
2026-02-04 03:57:19 +05:30
|
|
|
agent_id=agent.id,
|
|
|
|
|
)
|
2026-02-04 02:28:51 +05:30
|
|
|
|
|
|
|
|
|
2026-02-04 17:05:58 +05:30
|
|
|
async def _send_wakeup_message(
|
2026-02-04 23:07:22 +05:30
|
|
|
agent: Agent, config: GatewayClientConfig, verb: str = "provisioned"
|
2026-02-04 17:05:58 +05:30
|
|
|
) -> None:
|
2026-02-04 16:08:28 +05:30
|
|
|
session_key = agent.openclaw_session_id or _build_session_key(agent.name)
|
2026-02-04 17:24:52 +05:30
|
|
|
await ensure_session(session_key, config=config, label=agent.name)
|
2026-02-04 16:08:28 +05:30
|
|
|
message = (
|
2026-02-04 17:05:58 +05:30
|
|
|
f"Hello {agent.name}. Your workspace has been {verb}.\n\n"
|
2026-02-04 16:08:28 +05:30
|
|
|
"Start the agent, run BOOT.md, and if BOOTSTRAP.md exists run it once "
|
|
|
|
|
"then delete it. Begin heartbeats after startup."
|
|
|
|
|
)
|
|
|
|
|
await send_message(message, session_key=session_key, config=config, deliver=True)
|
|
|
|
|
|
|
|
|
|
|
2026-02-04 02:28:51 +05:30
|
|
|
@router.get("", response_model=list[AgentRead])
|
|
|
|
|
def list_agents(
|
|
|
|
|
session: Session = Depends(get_session),
|
2026-02-04 03:57:19 +05:30
|
|
|
auth: AuthContext = Depends(require_admin_auth),
|
2026-02-04 02:28:51 +05:30
|
|
|
) -> list[Agent]:
|
|
|
|
|
agents = list(session.exec(select(Agent)))
|
2026-02-05 19:29:17 +05:30
|
|
|
main_session_keys = _get_gateway_main_session_keys(session)
|
2026-02-06 02:43:08 +05:30
|
|
|
return [_to_agent_read(_with_computed_status(agent), main_session_keys) for agent in agents]
|
2026-02-04 02:28:51 +05:30
|
|
|
|
|
|
|
|
|
2026-02-05 22:51:46 +05:30
|
|
|
@router.get("/stream")
|
|
|
|
|
async def stream_agents(
|
|
|
|
|
request: Request,
|
|
|
|
|
board_id: UUID | None = Query(default=None),
|
|
|
|
|
since: str | None = Query(default=None),
|
|
|
|
|
auth: AuthContext = Depends(require_admin_auth),
|
|
|
|
|
) -> EventSourceResponse:
|
|
|
|
|
since_dt = _parse_since(since) or datetime.utcnow()
|
|
|
|
|
last_seen = since_dt
|
|
|
|
|
|
|
|
|
|
async def event_generator():
|
|
|
|
|
nonlocal last_seen
|
|
|
|
|
while True:
|
|
|
|
|
if await request.is_disconnected():
|
|
|
|
|
break
|
|
|
|
|
agents = await run_in_threadpool(_fetch_agent_events, board_id, last_seen)
|
|
|
|
|
if agents:
|
|
|
|
|
with Session(engine) as session:
|
|
|
|
|
main_session_keys = _get_gateway_main_session_keys(session)
|
|
|
|
|
for agent in agents:
|
|
|
|
|
updated_at = agent.updated_at or agent.last_seen_at or datetime.utcnow()
|
|
|
|
|
if updated_at > last_seen:
|
|
|
|
|
last_seen = updated_at
|
|
|
|
|
payload = {"agent": _serialize_agent(agent, main_session_keys)}
|
|
|
|
|
yield {"event": "agent", "data": json.dumps(payload)}
|
|
|
|
|
await asyncio.sleep(2)
|
|
|
|
|
|
|
|
|
|
return EventSourceResponse(event_generator(), ping=15)
|
|
|
|
|
|
|
|
|
|
|
2026-02-04 02:28:51 +05:30
|
|
|
@router.post("", response_model=AgentRead)
|
|
|
|
|
async def create_agent(
|
|
|
|
|
payload: AgentCreate,
|
|
|
|
|
session: Session = Depends(get_session),
|
2026-02-05 15:11:27 +05:30
|
|
|
actor: ActorContext = Depends(require_admin_or_agent),
|
2026-02-04 02:28:51 +05:30
|
|
|
) -> Agent:
|
2026-02-05 15:11:27 +05:30
|
|
|
if actor.actor_type == "agent":
|
|
|
|
|
if not actor.agent or not actor.agent.is_board_lead:
|
|
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
|
|
|
detail="Only board leads can create agents",
|
|
|
|
|
)
|
|
|
|
|
if not actor.agent.board_id:
|
|
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
|
|
|
detail="Board lead must be assigned to a board",
|
|
|
|
|
)
|
|
|
|
|
if payload.board_id and payload.board_id != actor.agent.board_id:
|
|
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
|
|
|
detail="Board leads can only create agents in their own board",
|
|
|
|
|
)
|
|
|
|
|
payload = AgentCreate(**{**payload.model_dump(), "board_id": actor.agent.board_id})
|
|
|
|
|
|
2026-02-04 16:04:52 +05:30
|
|
|
board = _require_board(session, payload.board_id)
|
2026-02-04 23:07:22 +05:30
|
|
|
gateway, client_config = _require_gateway(session, board)
|
|
|
|
|
data = payload.model_dump()
|
2026-02-05 23:06:59 +05:30
|
|
|
requested_name = (data.get("name") or "").strip()
|
|
|
|
|
if requested_name:
|
|
|
|
|
existing = session.exec(
|
|
|
|
|
select(Agent)
|
|
|
|
|
.where(Agent.board_id == board.id)
|
|
|
|
|
.where(col(Agent.name).ilike(requested_name))
|
|
|
|
|
).first()
|
|
|
|
|
if existing:
|
|
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_409_CONFLICT,
|
|
|
|
|
detail="An agent with this name already exists on this board.",
|
|
|
|
|
)
|
2026-02-04 23:07:22 +05:30
|
|
|
if data.get("identity_template") == "":
|
|
|
|
|
data["identity_template"] = None
|
|
|
|
|
if data.get("soul_template") == "":
|
|
|
|
|
data["soul_template"] = None
|
2026-02-06 02:43:08 +05:30
|
|
|
data["identity_profile"] = _normalize_identity_profile(data.get("identity_profile"))
|
2026-02-04 23:07:22 +05:30
|
|
|
agent = Agent.model_validate(data)
|
2026-02-04 15:16:28 +05:30
|
|
|
agent.status = "provisioning"
|
2026-02-04 14:58:14 +05:30
|
|
|
raw_token = generate_agent_token()
|
|
|
|
|
agent.agent_token_hash = hash_agent_token(raw_token)
|
2026-02-04 17:05:58 +05:30
|
|
|
if agent.heartbeat_config is None:
|
|
|
|
|
agent.heartbeat_config = DEFAULT_HEARTBEAT_CONFIG.copy()
|
2026-02-04 17:24:52 +05:30
|
|
|
agent.provision_requested_at = datetime.utcnow()
|
|
|
|
|
agent.provision_action = "provision"
|
2026-02-05 00:21:33 +05:30
|
|
|
session_key, session_error = await _ensure_gateway_session(agent.name, client_config)
|
2026-02-04 03:46:46 +05:30
|
|
|
agent.openclaw_session_id = session_key
|
2026-02-04 02:28:51 +05:30
|
|
|
session.add(agent)
|
|
|
|
|
session.commit()
|
|
|
|
|
session.refresh(agent)
|
2026-02-04 03:46:46 +05:30
|
|
|
if session_error:
|
2026-02-04 03:57:19 +05:30
|
|
|
record_activity(
|
|
|
|
|
session,
|
|
|
|
|
event_type="agent.session.failed",
|
|
|
|
|
message=f"Session sync failed for {agent.name}: {session_error}",
|
|
|
|
|
agent_id=agent.id,
|
2026-02-04 03:46:46 +05:30
|
|
|
)
|
|
|
|
|
else:
|
2026-02-04 03:57:19 +05:30
|
|
|
record_activity(
|
|
|
|
|
session,
|
|
|
|
|
event_type="agent.session.created",
|
|
|
|
|
message=f"Session created for {agent.name}.",
|
|
|
|
|
agent_id=agent.id,
|
2026-02-04 02:28:51 +05:30
|
|
|
)
|
|
|
|
|
session.commit()
|
2026-02-04 03:46:46 +05:30
|
|
|
try:
|
2026-02-05 15:11:27 +05:30
|
|
|
await provision_agent(
|
|
|
|
|
agent,
|
|
|
|
|
board,
|
|
|
|
|
gateway,
|
|
|
|
|
raw_token,
|
|
|
|
|
actor.user if actor.actor_type == "user" else None,
|
|
|
|
|
action="provision",
|
|
|
|
|
)
|
2026-02-05 01:27:48 +05:30
|
|
|
await _send_wakeup_message(agent, client_config, verb="provisioned")
|
|
|
|
|
agent.provision_confirm_token_hash = None
|
|
|
|
|
agent.provision_requested_at = None
|
|
|
|
|
agent.provision_action = None
|
|
|
|
|
agent.updated_at = datetime.utcnow()
|
|
|
|
|
session.add(agent)
|
|
|
|
|
session.commit()
|
|
|
|
|
record_activity(
|
|
|
|
|
session,
|
|
|
|
|
event_type="agent.provision",
|
|
|
|
|
message=f"Provisioned directly for {agent.name}.",
|
|
|
|
|
agent_id=agent.id,
|
2026-02-04 20:21:33 +05:30
|
|
|
)
|
2026-02-04 16:08:28 +05:30
|
|
|
record_activity(
|
|
|
|
|
session,
|
2026-02-05 01:27:48 +05:30
|
|
|
event_type="agent.wakeup.sent",
|
|
|
|
|
message=f"Wakeup message sent to {agent.name}.",
|
2026-02-04 16:08:28 +05:30
|
|
|
agent_id=agent.id,
|
|
|
|
|
)
|
2026-02-05 01:27:48 +05:30
|
|
|
session.commit()
|
2026-02-04 03:46:46 +05:30
|
|
|
except OpenClawGatewayError as exc:
|
2026-02-04 17:05:58 +05:30
|
|
|
_record_instruction_failure(session, agent, str(exc), "provision")
|
2026-02-04 03:46:46 +05:30
|
|
|
session.commit()
|
|
|
|
|
except Exception as exc: # pragma: no cover - unexpected provisioning errors
|
2026-02-04 17:05:58 +05:30
|
|
|
_record_instruction_failure(session, agent, str(exc), "provision")
|
2026-02-04 03:46:46 +05:30
|
|
|
session.commit()
|
2026-02-04 02:28:51 +05:30
|
|
|
return agent
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.get("/{agent_id}", response_model=AgentRead)
|
|
|
|
|
def get_agent(
|
|
|
|
|
agent_id: str,
|
|
|
|
|
session: Session = Depends(get_session),
|
2026-02-04 03:57:19 +05:30
|
|
|
auth: AuthContext = Depends(require_admin_auth),
|
2026-02-04 02:28:51 +05:30
|
|
|
) -> Agent:
|
|
|
|
|
agent = session.get(Agent, agent_id)
|
|
|
|
|
if agent is None:
|
|
|
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
|
2026-02-05 19:29:17 +05:30
|
|
|
main_session_keys = _get_gateway_main_session_keys(session)
|
|
|
|
|
return _to_agent_read(_with_computed_status(agent), main_session_keys)
|
2026-02-04 02:28:51 +05:30
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.patch("/{agent_id}", response_model=AgentRead)
|
2026-02-04 16:23:54 +05:30
|
|
|
async def update_agent(
|
2026-02-04 02:28:51 +05:30
|
|
|
agent_id: str,
|
|
|
|
|
payload: AgentUpdate,
|
2026-02-05 19:06:32 +05:30
|
|
|
force: bool = False,
|
2026-02-04 02:28:51 +05:30
|
|
|
session: Session = Depends(get_session),
|
2026-02-04 03:57:19 +05:30
|
|
|
auth: AuthContext = Depends(require_admin_auth),
|
2026-02-04 02:28:51 +05:30
|
|
|
) -> Agent:
|
|
|
|
|
agent = session.get(Agent, agent_id)
|
|
|
|
|
if agent is None:
|
|
|
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
|
|
|
|
|
updates = payload.model_dump(exclude_unset=True)
|
2026-02-05 19:29:17 +05:30
|
|
|
make_main = updates.pop("is_gateway_main", None)
|
2026-02-04 15:16:28 +05:30
|
|
|
if "status" in updates:
|
|
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
|
|
|
detail="status is controlled by agent heartbeat",
|
|
|
|
|
)
|
2026-02-04 23:07:22 +05:30
|
|
|
if updates.get("identity_template") == "":
|
|
|
|
|
updates["identity_template"] = None
|
|
|
|
|
if updates.get("soul_template") == "":
|
|
|
|
|
updates["soul_template"] = None
|
2026-02-05 02:21:38 +05:30
|
|
|
if "identity_profile" in updates:
|
2026-02-06 02:43:08 +05:30
|
|
|
updates["identity_profile"] = _normalize_identity_profile(updates.get("identity_profile"))
|
2026-02-05 19:29:17 +05:30
|
|
|
if not updates and not force and make_main is None:
|
|
|
|
|
main_session_keys = _get_gateway_main_session_keys(session)
|
|
|
|
|
return _to_agent_read(_with_computed_status(agent), main_session_keys)
|
|
|
|
|
main_gateway = _find_gateway_for_main_session(session, agent.openclaw_session_id)
|
|
|
|
|
gateway_for_main: Gateway | None = None
|
|
|
|
|
if make_main is True:
|
|
|
|
|
board_source = updates.get("board_id") or agent.board_id
|
|
|
|
|
board_for_main = _require_board(session, board_source)
|
|
|
|
|
gateway_for_main, _ = _require_gateway(session, board_for_main)
|
|
|
|
|
updates["board_id"] = None
|
|
|
|
|
agent.is_board_lead = False
|
|
|
|
|
agent.openclaw_session_id = gateway_for_main.main_session_key
|
|
|
|
|
main_gateway = gateway_for_main
|
|
|
|
|
elif make_main is False:
|
|
|
|
|
agent.openclaw_session_id = None
|
|
|
|
|
if make_main is not True and "board_id" in updates:
|
2026-02-04 16:23:54 +05:30
|
|
|
_require_board(session, updates["board_id"])
|
2026-02-04 02:28:51 +05:30
|
|
|
for key, value in updates.items():
|
|
|
|
|
setattr(agent, key, value)
|
2026-02-05 19:29:17 +05:30
|
|
|
if make_main is None and main_gateway is not None:
|
|
|
|
|
agent.board_id = None
|
|
|
|
|
agent.is_board_lead = False
|
2026-02-04 02:28:51 +05:30
|
|
|
agent.updated_at = datetime.utcnow()
|
2026-02-04 17:05:58 +05:30
|
|
|
if agent.heartbeat_config is None:
|
|
|
|
|
agent.heartbeat_config = DEFAULT_HEARTBEAT_CONFIG.copy()
|
2026-02-04 02:28:51 +05:30
|
|
|
session.add(agent)
|
|
|
|
|
session.commit()
|
|
|
|
|
session.refresh(agent)
|
2026-02-05 19:29:17 +05:30
|
|
|
is_main_agent = False
|
|
|
|
|
board: Board | None = None
|
|
|
|
|
gateway: Gateway | None = None
|
|
|
|
|
client_config: GatewayClientConfig | None = None
|
|
|
|
|
if make_main is True:
|
|
|
|
|
is_main_agent = True
|
|
|
|
|
gateway = gateway_for_main
|
|
|
|
|
elif make_main is None and agent.board_id is None and main_gateway is not None:
|
|
|
|
|
is_main_agent = True
|
|
|
|
|
gateway = main_gateway
|
|
|
|
|
if is_main_agent:
|
|
|
|
|
if gateway is None:
|
|
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
|
|
|
detail="Main agent requires a gateway main_session_key",
|
|
|
|
|
)
|
|
|
|
|
if not gateway.main_session_key:
|
|
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
|
|
|
detail="Gateway main_session_key is required",
|
|
|
|
|
)
|
|
|
|
|
client_config = _gateway_client_config(gateway)
|
|
|
|
|
else:
|
|
|
|
|
if agent.board_id is None:
|
|
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
|
|
|
detail="board_id is required for non-main agents",
|
|
|
|
|
)
|
|
|
|
|
board = _require_board(session, agent.board_id)
|
|
|
|
|
gateway, client_config = _require_gateway(session, board)
|
2026-02-04 16:23:54 +05:30
|
|
|
session_key = agent.openclaw_session_id or _build_session_key(agent.name)
|
|
|
|
|
try:
|
2026-02-05 19:29:17 +05:30
|
|
|
if client_config is None:
|
|
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
|
|
|
detail="Gateway configuration is required",
|
|
|
|
|
)
|
2026-02-04 23:07:22 +05:30
|
|
|
await ensure_session(session_key, config=client_config, label=agent.name)
|
2026-02-04 16:23:54 +05:30
|
|
|
if not agent.openclaw_session_id:
|
|
|
|
|
agent.openclaw_session_id = session_key
|
|
|
|
|
session.add(agent)
|
|
|
|
|
session.commit()
|
|
|
|
|
session.refresh(agent)
|
|
|
|
|
except OpenClawGatewayError as exc:
|
2026-02-04 17:05:58 +05:30
|
|
|
_record_instruction_failure(session, agent, str(exc), "update")
|
2026-02-04 16:23:54 +05:30
|
|
|
session.commit()
|
|
|
|
|
raw_token = generate_agent_token()
|
|
|
|
|
agent.agent_token_hash = hash_agent_token(raw_token)
|
2026-02-04 17:24:52 +05:30
|
|
|
agent.provision_requested_at = datetime.utcnow()
|
|
|
|
|
agent.provision_action = "update"
|
2026-02-04 18:25:13 +05:30
|
|
|
agent.status = "updating"
|
2026-02-04 16:23:54 +05:30
|
|
|
session.add(agent)
|
|
|
|
|
session.commit()
|
|
|
|
|
session.refresh(agent)
|
|
|
|
|
try:
|
2026-02-05 19:29:17 +05:30
|
|
|
if gateway is None:
|
|
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
|
|
|
detail="Gateway configuration is required",
|
|
|
|
|
)
|
|
|
|
|
if is_main_agent:
|
2026-02-05 22:27:50 +05:30
|
|
|
await provision_main_agent(
|
|
|
|
|
agent,
|
|
|
|
|
gateway,
|
|
|
|
|
raw_token,
|
|
|
|
|
auth.user,
|
|
|
|
|
action="update",
|
|
|
|
|
force_bootstrap=force,
|
|
|
|
|
reset_session=True,
|
|
|
|
|
)
|
2026-02-05 19:29:17 +05:30
|
|
|
else:
|
2026-02-05 22:27:50 +05:30
|
|
|
await provision_agent(
|
|
|
|
|
agent,
|
|
|
|
|
board,
|
|
|
|
|
gateway,
|
|
|
|
|
raw_token,
|
|
|
|
|
auth.user,
|
|
|
|
|
action="update",
|
|
|
|
|
force_bootstrap=force,
|
|
|
|
|
reset_session=True,
|
|
|
|
|
)
|
2026-02-05 01:27:48 +05:30
|
|
|
await _send_wakeup_message(agent, client_config, verb="updated")
|
|
|
|
|
agent.provision_confirm_token_hash = None
|
|
|
|
|
agent.provision_requested_at = None
|
|
|
|
|
agent.provision_action = None
|
|
|
|
|
agent.status = "online"
|
|
|
|
|
agent.updated_at = datetime.utcnow()
|
|
|
|
|
session.add(agent)
|
|
|
|
|
session.commit()
|
|
|
|
|
record_activity(
|
|
|
|
|
session,
|
|
|
|
|
event_type="agent.update.direct",
|
|
|
|
|
message=f"Updated directly for {agent.name}.",
|
|
|
|
|
agent_id=agent.id,
|
|
|
|
|
)
|
2026-02-04 16:23:54 +05:30
|
|
|
record_activity(
|
|
|
|
|
session,
|
2026-02-05 01:27:48 +05:30
|
|
|
event_type="agent.wakeup.sent",
|
|
|
|
|
message=f"Wakeup message sent to {agent.name}.",
|
2026-02-04 16:23:54 +05:30
|
|
|
agent_id=agent.id,
|
|
|
|
|
)
|
|
|
|
|
session.commit()
|
|
|
|
|
except OpenClawGatewayError as exc:
|
2026-02-04 17:05:58 +05:30
|
|
|
_record_instruction_failure(session, agent, str(exc), "update")
|
2026-02-04 16:23:54 +05:30
|
|
|
session.commit()
|
2026-02-05 19:06:32 +05:30
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_502_BAD_GATEWAY,
|
|
|
|
|
detail=f"Gateway update failed: {exc}",
|
|
|
|
|
) from exc
|
2026-02-04 16:23:54 +05:30
|
|
|
except Exception as exc: # pragma: no cover - unexpected provisioning errors
|
2026-02-04 17:05:58 +05:30
|
|
|
_record_instruction_failure(session, agent, str(exc), "update")
|
2026-02-04 16:23:54 +05:30
|
|
|
session.commit()
|
2026-02-05 19:06:32 +05:30
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
|
|
|
detail="Unexpected error updating agent provisioning.",
|
|
|
|
|
) from exc
|
2026-02-05 19:29:17 +05:30
|
|
|
main_session_keys = _get_gateway_main_session_keys(session)
|
|
|
|
|
return _to_agent_read(_with_computed_status(agent), main_session_keys)
|
2026-02-04 02:28:51 +05:30
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.post("/{agent_id}/heartbeat", response_model=AgentRead)
|
|
|
|
|
def heartbeat_agent(
|
|
|
|
|
agent_id: str,
|
|
|
|
|
payload: AgentHeartbeat,
|
|
|
|
|
session: Session = Depends(get_session),
|
2026-02-04 14:58:14 +05:30
|
|
|
actor: ActorContext = Depends(require_admin_or_agent),
|
2026-02-06 11:50:14 +05:30
|
|
|
) -> AgentRead:
|
2026-02-04 02:28:51 +05:30
|
|
|
agent = session.get(Agent, agent_id)
|
|
|
|
|
if agent is None:
|
|
|
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
|
2026-02-04 14:58:14 +05:30
|
|
|
if actor.actor_type == "agent" and actor.agent and actor.agent.id != agent.id:
|
|
|
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
2026-02-04 02:28:51 +05:30
|
|
|
if payload.status:
|
|
|
|
|
agent.status = payload.status
|
2026-02-04 15:16:28 +05:30
|
|
|
elif agent.status == "provisioning":
|
|
|
|
|
agent.status = "online"
|
2026-02-04 02:28:51 +05:30
|
|
|
agent.last_seen_at = datetime.utcnow()
|
|
|
|
|
agent.updated_at = datetime.utcnow()
|
|
|
|
|
_record_heartbeat(session, agent)
|
|
|
|
|
session.add(agent)
|
|
|
|
|
session.commit()
|
|
|
|
|
session.refresh(agent)
|
2026-02-05 19:29:17 +05:30
|
|
|
main_session_keys = _get_gateway_main_session_keys(session)
|
|
|
|
|
return _to_agent_read(_with_computed_status(agent), main_session_keys)
|
2026-02-04 02:28:51 +05:30
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.post("/heartbeat", response_model=AgentRead)
|
|
|
|
|
async def heartbeat_or_create_agent(
|
|
|
|
|
payload: AgentHeartbeatCreate,
|
|
|
|
|
session: Session = Depends(get_session),
|
2026-02-04 14:58:14 +05:30
|
|
|
actor: ActorContext = Depends(require_admin_or_agent),
|
2026-02-06 11:50:14 +05:30
|
|
|
) -> AgentRead:
|
|
|
|
|
# Agent tokens must heartbeat their authenticated agent record. Names are not unique.
|
|
|
|
|
if actor.actor_type == "agent" and actor.agent:
|
|
|
|
|
return heartbeat_agent(
|
|
|
|
|
agent_id=str(actor.agent.id),
|
|
|
|
|
payload=AgentHeartbeat(status=payload.status),
|
|
|
|
|
session=session,
|
|
|
|
|
actor=actor,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
statement = select(Agent).where(Agent.name == payload.name)
|
|
|
|
|
if payload.board_id is not None:
|
|
|
|
|
statement = statement.where(Agent.board_id == payload.board_id)
|
|
|
|
|
agent = session.exec(statement).first()
|
2026-02-04 02:28:51 +05:30
|
|
|
if agent is None:
|
2026-02-04 14:58:14 +05:30
|
|
|
if actor.actor_type == "agent":
|
|
|
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
|
2026-02-04 16:04:52 +05:30
|
|
|
board = _require_board(session, payload.board_id)
|
2026-02-04 23:07:22 +05:30
|
|
|
gateway, client_config = _require_gateway(session, board)
|
2026-02-04 17:05:58 +05:30
|
|
|
agent = Agent(
|
|
|
|
|
name=payload.name,
|
|
|
|
|
status="provisioning",
|
|
|
|
|
board_id=board.id,
|
|
|
|
|
heartbeat_config=DEFAULT_HEARTBEAT_CONFIG.copy(),
|
|
|
|
|
)
|
2026-02-04 14:58:14 +05:30
|
|
|
raw_token = generate_agent_token()
|
|
|
|
|
agent.agent_token_hash = hash_agent_token(raw_token)
|
2026-02-04 17:24:52 +05:30
|
|
|
agent.provision_requested_at = datetime.utcnow()
|
|
|
|
|
agent.provision_action = "provision"
|
2026-02-05 00:21:33 +05:30
|
|
|
session_key, session_error = await _ensure_gateway_session(agent.name, client_config)
|
2026-02-04 03:46:46 +05:30
|
|
|
agent.openclaw_session_id = session_key
|
2026-02-04 02:28:51 +05:30
|
|
|
session.add(agent)
|
|
|
|
|
session.commit()
|
|
|
|
|
session.refresh(agent)
|
2026-02-04 03:46:46 +05:30
|
|
|
if session_error:
|
2026-02-04 03:57:19 +05:30
|
|
|
record_activity(
|
|
|
|
|
session,
|
|
|
|
|
event_type="agent.session.failed",
|
|
|
|
|
message=f"Session sync failed for {agent.name}: {session_error}",
|
|
|
|
|
agent_id=agent.id,
|
2026-02-04 02:28:51 +05:30
|
|
|
)
|
2026-02-04 03:46:46 +05:30
|
|
|
else:
|
2026-02-04 03:57:19 +05:30
|
|
|
record_activity(
|
|
|
|
|
session,
|
|
|
|
|
event_type="agent.session.created",
|
|
|
|
|
message=f"Session created for {agent.name}.",
|
|
|
|
|
agent_id=agent.id,
|
2026-02-04 03:46:46 +05:30
|
|
|
)
|
|
|
|
|
session.commit()
|
|
|
|
|
try:
|
2026-02-05 01:27:48 +05:30
|
|
|
await provision_agent(agent, board, gateway, raw_token, actor.user, action="provision")
|
|
|
|
|
await _send_wakeup_message(agent, client_config, verb="provisioned")
|
|
|
|
|
agent.provision_confirm_token_hash = None
|
|
|
|
|
agent.provision_requested_at = None
|
|
|
|
|
agent.provision_action = None
|
|
|
|
|
agent.updated_at = datetime.utcnow()
|
|
|
|
|
session.add(agent)
|
|
|
|
|
session.commit()
|
|
|
|
|
record_activity(
|
|
|
|
|
session,
|
|
|
|
|
event_type="agent.provision",
|
|
|
|
|
message=f"Provisioned directly for {agent.name}.",
|
|
|
|
|
agent_id=agent.id,
|
2026-02-04 20:21:33 +05:30
|
|
|
)
|
2026-02-04 16:08:28 +05:30
|
|
|
record_activity(
|
|
|
|
|
session,
|
2026-02-05 01:27:48 +05:30
|
|
|
event_type="agent.wakeup.sent",
|
|
|
|
|
message=f"Wakeup message sent to {agent.name}.",
|
2026-02-04 16:08:28 +05:30
|
|
|
agent_id=agent.id,
|
|
|
|
|
)
|
2026-02-05 01:27:48 +05:30
|
|
|
session.commit()
|
2026-02-04 14:58:14 +05:30
|
|
|
except OpenClawGatewayError as exc:
|
2026-02-04 17:05:58 +05:30
|
|
|
_record_instruction_failure(session, agent, str(exc), "provision")
|
2026-02-04 14:58:14 +05:30
|
|
|
session.commit()
|
|
|
|
|
except Exception as exc: # pragma: no cover - unexpected provisioning errors
|
2026-02-04 17:05:58 +05:30
|
|
|
_record_instruction_failure(session, agent, str(exc), "provision")
|
2026-02-04 14:58:14 +05:30
|
|
|
session.commit()
|
|
|
|
|
elif actor.actor_type == "agent" and actor.agent and actor.agent.id != agent.id:
|
|
|
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
|
|
|
|
elif agent.agent_token_hash is None and actor.actor_type == "user":
|
|
|
|
|
raw_token = generate_agent_token()
|
|
|
|
|
agent.agent_token_hash = hash_agent_token(raw_token)
|
2026-02-04 17:05:58 +05:30
|
|
|
if agent.heartbeat_config is None:
|
|
|
|
|
agent.heartbeat_config = DEFAULT_HEARTBEAT_CONFIG.copy()
|
2026-02-04 17:24:52 +05:30
|
|
|
agent.provision_requested_at = datetime.utcnow()
|
|
|
|
|
agent.provision_action = "provision"
|
2026-02-04 14:58:14 +05:30
|
|
|
session.add(agent)
|
|
|
|
|
session.commit()
|
|
|
|
|
session.refresh(agent)
|
|
|
|
|
try:
|
2026-02-04 16:04:52 +05:30
|
|
|
board = _require_board(session, str(agent.board_id) if agent.board_id else None)
|
2026-02-04 23:07:22 +05:30
|
|
|
gateway, client_config = _require_gateway(session, board)
|
2026-02-05 01:27:48 +05:30
|
|
|
await provision_agent(agent, board, gateway, raw_token, actor.user, action="provision")
|
|
|
|
|
await _send_wakeup_message(agent, client_config, verb="provisioned")
|
|
|
|
|
agent.provision_confirm_token_hash = None
|
|
|
|
|
agent.provision_requested_at = None
|
|
|
|
|
agent.provision_action = None
|
|
|
|
|
agent.updated_at = datetime.utcnow()
|
|
|
|
|
session.add(agent)
|
|
|
|
|
session.commit()
|
|
|
|
|
record_activity(
|
|
|
|
|
session,
|
|
|
|
|
event_type="agent.provision",
|
|
|
|
|
message=f"Provisioned directly for {agent.name}.",
|
|
|
|
|
agent_id=agent.id,
|
2026-02-04 20:21:33 +05:30
|
|
|
)
|
2026-02-04 16:08:28 +05:30
|
|
|
record_activity(
|
|
|
|
|
session,
|
2026-02-05 01:27:48 +05:30
|
|
|
event_type="agent.wakeup.sent",
|
|
|
|
|
message=f"Wakeup message sent to {agent.name}.",
|
2026-02-04 16:08:28 +05:30
|
|
|
agent_id=agent.id,
|
|
|
|
|
)
|
2026-02-05 01:27:48 +05:30
|
|
|
session.commit()
|
2026-02-04 03:46:46 +05:30
|
|
|
except OpenClawGatewayError as exc:
|
2026-02-04 17:05:58 +05:30
|
|
|
_record_instruction_failure(session, agent, str(exc), "provision")
|
2026-02-04 03:46:46 +05:30
|
|
|
session.commit()
|
|
|
|
|
except Exception as exc: # pragma: no cover - unexpected provisioning errors
|
2026-02-04 17:05:58 +05:30
|
|
|
_record_instruction_failure(session, agent, str(exc), "provision")
|
2026-02-04 03:46:46 +05:30
|
|
|
session.commit()
|
2026-02-04 02:28:51 +05:30
|
|
|
elif not agent.openclaw_session_id:
|
2026-02-04 16:04:52 +05:30
|
|
|
board = _require_board(session, str(agent.board_id) if agent.board_id else None)
|
2026-02-04 23:07:22 +05:30
|
|
|
gateway, client_config = _require_gateway(session, board)
|
2026-02-05 00:21:33 +05:30
|
|
|
session_key, session_error = await _ensure_gateway_session(agent.name, client_config)
|
2026-02-04 03:46:46 +05:30
|
|
|
agent.openclaw_session_id = session_key
|
|
|
|
|
if session_error:
|
2026-02-04 03:57:19 +05:30
|
|
|
record_activity(
|
|
|
|
|
session,
|
|
|
|
|
event_type="agent.session.failed",
|
|
|
|
|
message=f"Session sync failed for {agent.name}: {session_error}",
|
|
|
|
|
agent_id=agent.id,
|
2026-02-04 02:28:51 +05:30
|
|
|
)
|
2026-02-04 03:46:46 +05:30
|
|
|
else:
|
2026-02-04 03:57:19 +05:30
|
|
|
record_activity(
|
|
|
|
|
session,
|
|
|
|
|
event_type="agent.session.created",
|
|
|
|
|
message=f"Session created for {agent.name}.",
|
|
|
|
|
agent_id=agent.id,
|
2026-02-04 03:46:46 +05:30
|
|
|
)
|
|
|
|
|
session.commit()
|
2026-02-04 02:28:51 +05:30
|
|
|
if payload.status:
|
|
|
|
|
agent.status = payload.status
|
2026-02-04 15:16:28 +05:30
|
|
|
elif agent.status == "provisioning":
|
|
|
|
|
agent.status = "online"
|
2026-02-04 02:28:51 +05:30
|
|
|
agent.last_seen_at = datetime.utcnow()
|
|
|
|
|
agent.updated_at = datetime.utcnow()
|
|
|
|
|
_record_heartbeat(session, agent)
|
|
|
|
|
session.add(agent)
|
|
|
|
|
session.commit()
|
|
|
|
|
session.refresh(agent)
|
2026-02-05 19:29:17 +05:30
|
|
|
main_session_keys = _get_gateway_main_session_keys(session)
|
|
|
|
|
return _to_agent_read(_with_computed_status(agent), main_session_keys)
|
2026-02-04 02:28:51 +05:30
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.delete("/{agent_id}")
|
|
|
|
|
def delete_agent(
|
|
|
|
|
agent_id: str,
|
|
|
|
|
session: Session = Depends(get_session),
|
2026-02-04 03:57:19 +05:30
|
|
|
auth: AuthContext = Depends(require_admin_auth),
|
2026-02-04 02:28:51 +05:30
|
|
|
) -> dict[str, bool]:
|
|
|
|
|
agent = session.get(Agent, agent_id)
|
2026-02-04 17:05:58 +05:30
|
|
|
if agent is None:
|
|
|
|
|
return {"ok": True}
|
2026-02-04 14:58:14 +05:30
|
|
|
|
2026-02-04 17:05:58 +05:30
|
|
|
board = _require_board(session, str(agent.board_id) if agent.board_id else None)
|
2026-02-05 01:40:28 +05:30
|
|
|
gateway, client_config = _require_gateway(session, board)
|
2026-02-04 17:05:58 +05:30
|
|
|
try:
|
|
|
|
|
import asyncio
|
|
|
|
|
|
2026-02-05 01:40:28 +05:30
|
|
|
workspace_path = asyncio.run(cleanup_agent(agent, gateway))
|
2026-02-04 17:05:58 +05:30
|
|
|
except OpenClawGatewayError as exc:
|
|
|
|
|
_record_instruction_failure(session, agent, str(exc), "delete")
|
2026-02-04 02:28:51 +05:30
|
|
|
session.commit()
|
2026-02-04 17:05:58 +05:30
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_502_BAD_GATEWAY,
|
2026-02-05 01:27:48 +05:30
|
|
|
detail=f"Gateway cleanup failed: {exc}",
|
|
|
|
|
) from exc
|
|
|
|
|
except Exception as exc: # pragma: no cover - unexpected cleanup errors
|
|
|
|
|
_record_instruction_failure(session, agent, str(exc), "delete")
|
|
|
|
|
session.commit()
|
|
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
|
|
|
detail=f"Workspace cleanup failed: {exc}",
|
2026-02-04 17:05:58 +05:30
|
|
|
) from exc
|
|
|
|
|
|
2026-02-05 01:27:48 +05:30
|
|
|
record_activity(
|
|
|
|
|
session,
|
|
|
|
|
event_type="agent.delete.direct",
|
|
|
|
|
message=f"Deleted agent {agent.name}.",
|
|
|
|
|
agent_id=None,
|
|
|
|
|
)
|
2026-02-05 03:08:47 +05:30
|
|
|
now = datetime.now()
|
|
|
|
|
session.execute(
|
|
|
|
|
update(Task)
|
|
|
|
|
.where(col(Task.assigned_agent_id) == agent.id)
|
|
|
|
|
.where(col(Task.status) == "in_progress")
|
|
|
|
|
.values(
|
|
|
|
|
assigned_agent_id=None,
|
|
|
|
|
status="inbox",
|
|
|
|
|
in_progress_at=None,
|
|
|
|
|
updated_at=now,
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
session.execute(
|
|
|
|
|
update(Task)
|
|
|
|
|
.where(col(Task.assigned_agent_id) == agent.id)
|
|
|
|
|
.where(col(Task.status) != "in_progress")
|
|
|
|
|
.values(
|
|
|
|
|
assigned_agent_id=None,
|
|
|
|
|
updated_at=now,
|
|
|
|
|
)
|
|
|
|
|
)
|
2026-02-05 01:27:48 +05:30
|
|
|
session.execute(
|
2026-02-06 02:43:08 +05:30
|
|
|
update(ActivityEvent).where(col(ActivityEvent.agent_id) == agent.id).values(agent_id=None)
|
2026-02-05 01:27:48 +05:30
|
|
|
)
|
|
|
|
|
session.delete(agent)
|
|
|
|
|
session.commit()
|
2026-02-04 17:24:52 +05:30
|
|
|
|
2026-02-05 01:40:28 +05:30
|
|
|
# Always ask the main agent to confirm workspace cleanup.
|
2026-02-04 17:24:52 +05:30
|
|
|
try:
|
2026-02-05 01:40:28 +05:30
|
|
|
main_session = gateway.main_session_key
|
|
|
|
|
if main_session and workspace_path:
|
|
|
|
|
cleanup_message = (
|
|
|
|
|
"Cleanup request for deleted agent.\n\n"
|
|
|
|
|
f"Agent name: {agent.name}\n"
|
|
|
|
|
f"Agent id: {agent.id}\n"
|
|
|
|
|
f"Workspace path: {workspace_path}\n\n"
|
|
|
|
|
"Actions:\n"
|
|
|
|
|
"1) Remove the workspace directory.\n"
|
|
|
|
|
"2) Reply NO_REPLY.\n"
|
|
|
|
|
)
|
2026-02-04 17:05:58 +05:30
|
|
|
|
2026-02-05 01:40:28 +05:30
|
|
|
async def _request_cleanup() -> None:
|
|
|
|
|
await ensure_session(main_session, config=client_config, label="Main Agent")
|
|
|
|
|
await send_message(
|
|
|
|
|
cleanup_message,
|
|
|
|
|
session_key=main_session,
|
|
|
|
|
config=client_config,
|
|
|
|
|
deliver=False,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
import asyncio
|
|
|
|
|
|
|
|
|
|
asyncio.run(_request_cleanup())
|
|
|
|
|
except Exception:
|
|
|
|
|
# Cleanup request is best-effort; deletion already completed.
|
|
|
|
|
pass
|
2026-02-04 02:28:51 +05:30
|
|
|
return {"ok": True}
|