feat(agents): Move templates into dedicated folder
Provisioning now reads template files from templates/ and includes the\nbase URL for agent runtime setup. Remove unused root orchestration\ndocs to keep the repo tidy.\n\nCo-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -3,6 +3,7 @@ LOG_LEVEL=INFO
|
||||
DATABASE_URL=postgresql+psycopg://postgres:postgres@localhost:5432/openclaw_agency
|
||||
REDIS_URL=redis://localhost:6379/0
|
||||
CORS_ORIGINS=http://localhost:3000
|
||||
BASE_URL=
|
||||
|
||||
# Clerk (auth only)
|
||||
CLERK_JWKS_URL=
|
||||
@@ -12,6 +13,8 @@ CLERK_LEEWAY=10.0
|
||||
# OpenClaw Gateway
|
||||
OPENCLAW_GATEWAY_URL=ws://127.0.0.1:18789
|
||||
OPENCLAW_GATEWAY_TOKEN=
|
||||
OPENCLAW_MAIN_SESSION_KEY=agent:main:main
|
||||
OPENCLAW_WORKSPACE_ROOT=~/.openclaw/workspaces
|
||||
|
||||
# Database
|
||||
DB_AUTO_MIGRATE=false
|
||||
|
||||
@@ -20,11 +20,12 @@ from app.schemas.agents import (
|
||||
AgentUpdate,
|
||||
)
|
||||
from app.services.admin_access import require_admin
|
||||
from app.services.agent_provisioning import send_provisioning_message
|
||||
|
||||
router = APIRouter(prefix="/agents", tags=["agents"])
|
||||
|
||||
OFFLINE_AFTER = timedelta(minutes=10)
|
||||
DEFAULT_GATEWAY_CHANNEL = "openclaw-agency"
|
||||
AGENT_SESSION_PREFIX = "agent"
|
||||
|
||||
|
||||
def _slugify(value: str) -> str:
|
||||
@@ -32,17 +33,17 @@ def _slugify(value: str) -> str:
|
||||
return slug or uuid4().hex
|
||||
|
||||
|
||||
def _build_session_label(agent_name: str) -> str:
|
||||
return f"{DEFAULT_GATEWAY_CHANNEL}-{_slugify(agent_name)}"
|
||||
def _build_session_key(agent_name: str) -> str:
|
||||
return f"{AGENT_SESSION_PREFIX}:{_slugify(agent_name)}:main"
|
||||
|
||||
|
||||
async def _create_gateway_session(agent_name: str) -> str:
|
||||
label = _build_session_label(agent_name)
|
||||
async def _ensure_gateway_session(agent_name: str) -> tuple[str, str | None]:
|
||||
session_key = _build_session_key(agent_name)
|
||||
try:
|
||||
await openclaw_call("sessions.patch", {"key": label, "label": agent_name})
|
||||
await openclaw_call("sessions.patch", {"key": session_key, "label": agent_name})
|
||||
return session_key, None
|
||||
except OpenClawGatewayError as exc:
|
||||
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc)) from exc
|
||||
return label
|
||||
return session_key, str(exc)
|
||||
|
||||
|
||||
def _with_computed_status(agent: Agent) -> Agent:
|
||||
@@ -79,18 +80,48 @@ async def create_agent(
|
||||
) -> Agent:
|
||||
require_admin(auth)
|
||||
agent = Agent.model_validate(payload)
|
||||
agent.openclaw_session_id = await _create_gateway_session(agent.name)
|
||||
session_key, session_error = await _ensure_gateway_session(agent.name)
|
||||
agent.openclaw_session_id = session_key
|
||||
session.add(agent)
|
||||
session.commit()
|
||||
session.refresh(agent)
|
||||
session.add(
|
||||
ActivityEvent(
|
||||
event_type="agent.session.created",
|
||||
message=f"Session created for {agent.name}.",
|
||||
agent_id=agent.id,
|
||||
if session_error:
|
||||
session.add(
|
||||
ActivityEvent(
|
||||
event_type="agent.session.failed",
|
||||
message=f"Session sync failed for {agent.name}: {session_error}",
|
||||
agent_id=agent.id,
|
||||
)
|
||||
)
|
||||
else:
|
||||
session.add(
|
||||
ActivityEvent(
|
||||
event_type="agent.session.created",
|
||||
message=f"Session created for {agent.name}.",
|
||||
agent_id=agent.id,
|
||||
)
|
||||
)
|
||||
)
|
||||
session.commit()
|
||||
try:
|
||||
await send_provisioning_message(agent)
|
||||
except OpenClawGatewayError as exc:
|
||||
session.add(
|
||||
ActivityEvent(
|
||||
event_type="agent.provision.failed",
|
||||
message=f"Provisioning message failed: {exc}",
|
||||
agent_id=agent.id,
|
||||
)
|
||||
)
|
||||
session.commit()
|
||||
except Exception as exc: # pragma: no cover - unexpected provisioning errors
|
||||
session.add(
|
||||
ActivityEvent(
|
||||
event_type="agent.provision.failed",
|
||||
message=f"Provisioning message failed: {exc}",
|
||||
agent_id=agent.id,
|
||||
)
|
||||
)
|
||||
session.commit()
|
||||
return agent
|
||||
|
||||
|
||||
@@ -160,26 +191,88 @@ async def heartbeat_or_create_agent(
|
||||
agent = session.exec(select(Agent).where(Agent.name == payload.name)).first()
|
||||
if agent is None:
|
||||
agent = Agent(name=payload.name, status=payload.status or "online")
|
||||
agent.openclaw_session_id = await _create_gateway_session(agent.name)
|
||||
session_key, session_error = await _ensure_gateway_session(agent.name)
|
||||
agent.openclaw_session_id = session_key
|
||||
session.add(agent)
|
||||
session.commit()
|
||||
session.refresh(agent)
|
||||
session.add(
|
||||
ActivityEvent(
|
||||
event_type="agent.session.created",
|
||||
message=f"Session created for {agent.name}.",
|
||||
agent_id=agent.id,
|
||||
if session_error:
|
||||
session.add(
|
||||
ActivityEvent(
|
||||
event_type="agent.session.failed",
|
||||
message=f"Session sync failed for {agent.name}: {session_error}",
|
||||
agent_id=agent.id,
|
||||
)
|
||||
)
|
||||
)
|
||||
else:
|
||||
session.add(
|
||||
ActivityEvent(
|
||||
event_type="agent.session.created",
|
||||
message=f"Session created for {agent.name}.",
|
||||
agent_id=agent.id,
|
||||
)
|
||||
)
|
||||
session.commit()
|
||||
try:
|
||||
await send_provisioning_message(agent)
|
||||
except OpenClawGatewayError as exc:
|
||||
session.add(
|
||||
ActivityEvent(
|
||||
event_type="agent.provision.failed",
|
||||
message=f"Provisioning message failed: {exc}",
|
||||
agent_id=agent.id,
|
||||
)
|
||||
)
|
||||
session.commit()
|
||||
except Exception as exc: # pragma: no cover - unexpected provisioning errors
|
||||
session.add(
|
||||
ActivityEvent(
|
||||
event_type="agent.provision.failed",
|
||||
message=f"Provisioning message failed: {exc}",
|
||||
agent_id=agent.id,
|
||||
)
|
||||
)
|
||||
session.commit()
|
||||
elif not agent.openclaw_session_id:
|
||||
agent.openclaw_session_id = await _create_gateway_session(agent.name)
|
||||
session.add(
|
||||
ActivityEvent(
|
||||
event_type="agent.session.created",
|
||||
message=f"Session created for {agent.name}.",
|
||||
agent_id=agent.id,
|
||||
session_key, session_error = await _ensure_gateway_session(agent.name)
|
||||
agent.openclaw_session_id = session_key
|
||||
if session_error:
|
||||
session.add(
|
||||
ActivityEvent(
|
||||
event_type="agent.session.failed",
|
||||
message=f"Session sync failed for {agent.name}: {session_error}",
|
||||
agent_id=agent.id,
|
||||
)
|
||||
)
|
||||
)
|
||||
else:
|
||||
session.add(
|
||||
ActivityEvent(
|
||||
event_type="agent.session.created",
|
||||
message=f"Session created for {agent.name}.",
|
||||
agent_id=agent.id,
|
||||
)
|
||||
)
|
||||
session.commit()
|
||||
try:
|
||||
await send_provisioning_message(agent)
|
||||
except OpenClawGatewayError as exc:
|
||||
session.add(
|
||||
ActivityEvent(
|
||||
event_type="agent.provision.failed",
|
||||
message=f"Provisioning message failed: {exc}",
|
||||
agent_id=agent.id,
|
||||
)
|
||||
)
|
||||
session.commit()
|
||||
except Exception as exc: # pragma: no cover - unexpected provisioning errors
|
||||
session.add(
|
||||
ActivityEvent(
|
||||
event_type="agent.provision.failed",
|
||||
message=f"Provisioning message failed: {exc}",
|
||||
agent_id=agent.id,
|
||||
)
|
||||
)
|
||||
session.commit()
|
||||
if payload.status:
|
||||
agent.status = payload.status
|
||||
agent.last_seen_at = datetime.utcnow()
|
||||
|
||||
@@ -22,8 +22,11 @@ class Settings(BaseSettings):
|
||||
# OpenClaw Gateway
|
||||
openclaw_gateway_url: str = ""
|
||||
openclaw_gateway_token: str = ""
|
||||
openclaw_main_session_key: str = "agent:main:main"
|
||||
openclaw_workspace_root: str = "~/.openclaw/workspaces"
|
||||
|
||||
cors_origins: str = ""
|
||||
base_url: str = ""
|
||||
|
||||
# Database lifecycle
|
||||
db_auto_migrate: bool = False
|
||||
|
||||
93
backend/app/services/agent_provisioning.py
Normal file
93
backend/app/services/agent_provisioning.py
Normal file
@@ -0,0 +1,93 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
from app.core.config import settings
|
||||
from app.integrations.openclaw_gateway import send_message
|
||||
from app.models.agents import Agent
|
||||
|
||||
TEMPLATE_FILES = [
|
||||
"AGENTS.md",
|
||||
"BOOT.md",
|
||||
"BOOTSTRAP.md",
|
||||
"HEARTBEAT.md",
|
||||
"IDENTITY.md",
|
||||
"SOUL.md",
|
||||
"TOOLS.md",
|
||||
"USER.md",
|
||||
]
|
||||
|
||||
|
||||
def _repo_root() -> Path:
|
||||
return Path(__file__).resolve().parents[3]
|
||||
|
||||
|
||||
def _templates_root() -> Path:
|
||||
return _repo_root() / "templates"
|
||||
|
||||
|
||||
def _slugify(value: str) -> str:
|
||||
slug = re.sub(r"[^a-z0-9]+", "-", value.lower()).strip("-")
|
||||
return slug or uuid4().hex
|
||||
|
||||
|
||||
def _read_templates() -> dict[str, str]:
|
||||
root = _templates_root()
|
||||
templates: dict[str, str] = {}
|
||||
for name in TEMPLATE_FILES:
|
||||
path = root / name
|
||||
if path.exists():
|
||||
templates[name] = path.read_text(encoding="utf-8").strip()
|
||||
else:
|
||||
templates[name] = ""
|
||||
return templates
|
||||
|
||||
|
||||
def _render_file_block(name: str, content: str) -> str:
|
||||
body = content if content else f"# {name}\n\nTODO: add content\n"
|
||||
return f"\n{name}\n```md\n{body}\n```\n"
|
||||
|
||||
|
||||
def _workspace_path(agent_name: str) -> str:
|
||||
root = settings.openclaw_workspace_root or "~/.openclaw/workspaces"
|
||||
root = root.rstrip("/")
|
||||
return f"{root}/{_slugify(agent_name)}"
|
||||
|
||||
|
||||
def build_provisioning_message(agent: Agent) -> str:
|
||||
templates = _read_templates()
|
||||
agent_id = _slugify(agent.name)
|
||||
workspace_path = _workspace_path(agent.name)
|
||||
session_key = agent.openclaw_session_id or ""
|
||||
base_url = settings.base_url or ""
|
||||
|
||||
file_blocks = "".join(
|
||||
_render_file_block(name, templates.get(name, "")) for name in TEMPLATE_FILES
|
||||
)
|
||||
|
||||
return (
|
||||
"Provision a new OpenClaw agent workspace.\n\n"
|
||||
f"Agent name: {agent.name}\n"
|
||||
f"Agent id: {agent_id}\n"
|
||||
f"Session key: {session_key}\n"
|
||||
f"Workspace path: {workspace_path}\n\n"
|
||||
f"Base URL: {base_url or 'UNSET'}\n\n"
|
||||
"Steps:\n"
|
||||
"1) Create the workspace directory.\n"
|
||||
"2) Write the files below with the exact contents.\n"
|
||||
f"3) Set BASE_URL to {base_url or '{{BASE_URL}}'} for the agent runtime.\n"
|
||||
"4) Replace placeholders like {{AGENT_NAME}}, {{AGENT_ID}}, {{BASE_URL}}, {{AUTH_TOKEN}}.\n"
|
||||
"5) Leave BOOTSTRAP.md in place; the agent should run it on first start and delete it.\n"
|
||||
"6) Register agent id in OpenClaw so it uses this workspace path.\n\n"
|
||||
"Files:" + file_blocks
|
||||
)
|
||||
|
||||
|
||||
async def send_provisioning_message(agent: Agent) -> None:
|
||||
main_session = settings.openclaw_main_session_key
|
||||
if not main_session:
|
||||
return
|
||||
message = build_provisioning_message(agent)
|
||||
await send_message(message, session_key=main_session, deliver=False)
|
||||
Reference in New Issue
Block a user