智能体分权

This commit is contained in:
吉鑫升 committed 2026-05-13 11:36:17 +08:00
1 parent e7a455f22e
commit cf2e4bdd9c
31 files changed
+1237 -436

No files matched your search

@@ -24,6 +24,7 @@ from deerflow.runtime.runs.store.base import RunStore
if TYPE_CHECKING:
from app.gateway.auth.local_provider import LocalAuthProvider
from app.gateway.auth.repositories.sqlite import SQLiteUserRepository
from deerflow.persistence.agents import AgentStore
from deerflow.persistence.scheduled_tasks import ScheduledTaskStore
from deerflow.persistence.thread_meta.base import ThreadMetaStore
@@ -89,6 +90,10 @@ async def langgraph_runtime(app: FastAPI) -> AsyncGenerator[None, None]:
app.state.scheduled_task_store = make_scheduled_task_store(sf)
from deerflow.persistence.agents import make_agent_store
app.state.agent_store = make_agent_store(sf)
# Run event store (has its own factory with config-driven backend selection)
run_events_config = getattr(config, "run_events", None)
app.state.run_event_store = make_run_event_store(run_events_config)
@@ -149,6 +154,14 @@ def get_scheduled_task_store(request: Request) -> ScheduledTaskStore:
return val
def get_agent_store(request: Request) -> AgentStore:
"""Return the custom-agent store."""
val = getattr(request.app.state, "agent_store", None)
if val is None:
raise HTTPException(status_code=503, detail="Agent store not available")
return val
def get_run_context(request: Request) -> RunContext:
"""Build a :class:`RunContext` from ``app.state`` singletons.
@@ -1,36 +1,50 @@
"""CRUD API for custom agents."""
from __future__ import annotations
import logging
import re
import shutil
from datetime import datetime
from typing import Any
from uuid import uuid4
import yaml
from fastapi import APIRouter, HTTPException
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel, Field
from app.gateway.deps import get_agent_store
from deerflow.config.agents_api_config import get_agents_api_config
from deerflow.config.agents_config import AgentConfig, list_custom_agents, load_agent_config, load_agent_soul
from deerflow.config.agents_config import list_custom_agents, load_agent_config, load_agent_soul, validate_agent_id
from deerflow.config.paths import get_paths
from deerflow.persistence.agents import AgentStore
from deerflow.runtime.user_context import get_effective_user_id
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api", tags=["agents"])
AGENT_NAME_PATTERN = re.compile(r"^[A-Za-z0-9-]+$")
class AgentResponse(BaseModel):
"""Response model for a custom agent."""
"""Response model for an agent."""
name: str = Field(..., description="Agent name (hyphen-case)")
id: str = Field(..., description="Agent id used for routing and filesystem storage")
name: str = Field(..., description="Display name. Chinese and duplicate names are allowed.")
description: str = Field(default="", description="Agent description")
model: str | None = Field(default=None, description="Optional model override")
tool_groups: list[str] | None = Field(default=None, description="Optional tool group whitelist")
skills: list[str] | None = Field(default=None, description="Optional skill whitelist (None/[]=none)")
user_id: str | None = Field(default=None, description="Owner user id. Null means built-in.")
published: bool = Field(default=False, description="Whether a user-created agent is public")
builtin: bool = Field(default=False, description="True when user_id is null")
created_at: datetime | str | None = None
updated_at: datetime | str | None = None
soul: str | None = Field(default=None, description="SOUL.md content")
# Deprecated compatibility fields. Agent runtime configuration is no longer
# stored in the agents table, but older frontends may still read these keys.
model: str | None = None
tool_groups: list[str] | None = None
skills: list[str] | None = None
class AgentsListResponse(BaseModel):
"""Response model for listing all custom agents."""
"""Response model for listing all visible agents."""
agents: list[AgentResponse]
@@ -38,43 +52,25 @@ class AgentsListResponse(BaseModel):
class AgentCreateRequest(BaseModel):
"""Request body for creating a custom agent."""
name: str = Field(..., description="Agent name (must match ^[A-Za-z0-9-]+$, stored as lowercase)")
name: str = Field(..., description="Display name; Chinese and duplicate names are allowed")
description: str = Field(default="", description="Agent description")
model: str | None = Field(default=None, description="Optional model override")
tool_groups: list[str] | None = Field(default=None, description="Optional tool group whitelist")
skills: list[str] | None = Field(default=None, description="Optional skill whitelist (None/[]=none)")
soul: str = Field(default="", description="SOUL.md content — agent personality and behavioral guardrails")
soul: str = Field(default="", description="SOUL.md content - agent personality and behavioral guardrails")
published: bool = Field(default=False, description="Whether the new agent should be public")
skills: list[str] | None = Field(default=None, description="Skill whitelist persisted to the agent's config.yaml")
model: str | None = Field(default=None, description="Optional model override persisted to config.yaml")
tool_groups: list[str] | None = Field(default=None, description="Optional tool group whitelist persisted to config.yaml")
class AgentUpdateRequest(BaseModel):
"""Request body for updating a custom agent."""
name: str | None = Field(default=None, description="Updated display name")
description: str | None = Field(default=None, description="Updated description")
model: str | None = Field(default=None, description="Updated model override")
tool_groups: list[str] | None = Field(default=None, description="Updated tool group whitelist")
skills: list[str] | None = Field(default=None, description="Updated skill whitelist (None/[]=none)")
soul: str | None = Field(default=None, description="Updated SOUL.md content")
def _validate_agent_name(name: str) -> None:
"""Validate agent name against allowed pattern.
Args:
name: The agent name to validate.
Raises:
HTTPException: 422 if the name is invalid.
"""
if not AGENT_NAME_PATTERN.match(name):
raise HTTPException(
status_code=422,
detail=f"Invalid agent name '{name}'. Must match ^[A-Za-z0-9-]+$ (letters, digits, and hyphens only).",
)
def _normalize_agent_name(name: str) -> str:
"""Normalize agent name to lowercase for filesystem storage."""
return name.lower()
published: bool | None = Field(default=None, description="Updated publication state")
skills: list[str] | None = Field(default=None, description="Updated skill whitelist (config.yaml)")
model: str | None = Field(default=None, description="Updated model override (config.yaml)")
tool_groups: list[str] | None = Field(default=None, description="Updated tool group whitelist (config.yaml)")
def _require_agents_api_enabled() -> None:
@@ -86,242 +82,290 @@ def _require_agents_api_enabled() -> None:
)
def _agent_config_to_response(agent_cfg: AgentConfig, include_soul: bool = False) -> AgentResponse:
"""Convert AgentConfig to AgentResponse."""
def _current_user_id(request: Request) -> str:
user = getattr(request.state, "user", None)
if user is not None:
return str(user.id)
return get_effective_user_id()
def _validate_display_name(name: str) -> str:
normalized = name.strip()
if not normalized:
raise HTTPException(status_code=422, detail="Agent name cannot be empty")
return normalized
def _validate_storage_id(agent_id: str) -> str:
try:
return validate_agent_id(agent_id) or agent_id
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
def _write_agent_config(
agent_id: str,
*,
name: str,
description: str,
skills: list[str] | None = None,
model: str | None = None,
tool_groups: list[str] | None = None,
) -> None:
agent_dir = get_paths().agent_dir(agent_id)
agent_dir.mkdir(parents=True, exist_ok=True)
config_file = agent_dir / "config.yaml"
config_data: dict[str, Any] = {
"id": agent_id,
"name": name,
"description": description or "",
}
if skills is not None:
config_data["skills"] = skills
if model is not None:
config_data["model"] = model
if tool_groups is not None:
config_data["tool_groups"] = tool_groups
with open(config_file, "w", encoding="utf-8") as f:
yaml.dump(config_data, f, default_flow_style=False, allow_unicode=True)
def _load_config_extras(agent_id: str) -> dict[str, Any]:
"""Read skills/model/tool_groups from the agent's config.yaml, tolerant of missing files."""
try:
cfg = load_agent_config(agent_id)
except (FileNotFoundError, ValueError):
return {"skills": None, "model": None, "tool_groups": None}
if cfg is None:
return {"skills": None, "model": None, "tool_groups": None}
return {"skills": cfg.skills, "model": cfg.model, "tool_groups": cfg.tool_groups}
def _write_agent_soul(agent_id: str, soul: str) -> None:
agent_dir = get_paths().agent_dir(agent_id)
agent_dir.mkdir(parents=True, exist_ok=True)
(agent_dir / "SOUL.md").write_text(soul, encoding="utf-8")
async def _sync_legacy_agents(store: AgentStore) -> None:
"""Import existing folder-backed agents as built-in DB records.
This preserves old deployments where agents already existed under
``.deer-flow/agents/{name}`` before the agents table was introduced.
"""
try:
for agent_cfg in list_custom_agents():
agent_id = agent_cfg.id or agent_cfg.name
if not agent_id:
continue
await store.ensure_builtin(
{
"id": agent_id,
"name": agent_cfg.name,
"description": agent_cfg.description or "",
"published": True,
}
)
except Exception:
logger.exception("Failed to sync legacy folder-backed agents")
def _record_to_response(record: dict[str, Any], *, include_soul: bool = False) -> AgentResponse:
soul: str | None = None
if include_soul:
soul = load_agent_soul(agent_cfg.name) or ""
soul = load_agent_soul(record["id"]) or ""
extras = _load_config_extras(record["id"])
return AgentResponse(
name=agent_cfg.name,
description=agent_cfg.description,
model=agent_cfg.model,
tool_groups=agent_cfg.tool_groups,
skills=agent_cfg.skills,
id=record["id"],
name=record["name"],
description=record.get("description") or "",
user_id=record.get("user_id"),
published=bool(record.get("published", False)),
builtin=record.get("user_id") is None,
created_at=record.get("created_at"),
updated_at=record.get("updated_at"),
soul=soul,
model=extras["model"],
tool_groups=extras["tool_groups"],
skills=extras["skills"],
)
async def _get_owned_or_raise(store: AgentStore, agent_id: str, user_id: str) -> dict[str, Any]:
owned = await store.get_owned(agent_id, user_id)
if owned is not None:
return owned
visible = await store.get_visible(agent_id, user_id)
if visible is None:
raise HTTPException(status_code=404, detail=f"Agent '{agent_id}' not found")
raise HTTPException(status_code=403, detail="You can only modify agents that you created")
@router.get(
"/agents",
response_model=AgentsListResponse,
summary="List Custom Agents",
description="List all custom agents available in the agents directory, including their soul content.",
summary="List Agents",
description="List built-in agents, the current user's agents, and published agents.",
)
async def list_agents() -> AgentsListResponse:
"""List all custom agents.
Returns:
List of all custom agents with their metadata and soul content.
"""
async def list_agents(request: Request) -> AgentsListResponse:
_require_agents_api_enabled()
try:
agents = list_custom_agents()
return AgentsListResponse(agents=[_agent_config_to_response(a, include_soul=True) for a in agents])
store = get_agent_store(request)
await _sync_legacy_agents(store)
user_id = _current_user_id(request)
agents = await store.list_visible(user_id)
return AgentsListResponse(agents=[_record_to_response(a, include_soul=True) for a in agents])
except HTTPException:
raise
except Exception as e:
logger.error(f"Failed to list agents: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Failed to list agents: {str(e)}")
logger.error("Failed to list agents: %s", e, exc_info=True)
raise HTTPException(status_code=500, detail=f"Failed to list agents: {str(e)}") from e
@router.get(
"/agents/check",
summary="Check Agent Name",
description="Validate an agent name and check if it is available (case-insensitive).",
description="Validate an agent display name. Duplicate names are allowed.",
)
async def check_agent_name(name: str) -> dict:
"""Check whether an agent name is valid and not yet taken.
Args:
name: The agent name to check.
Returns:
``{"available": true/false, "name": "<normalized>"}``
Raises:
HTTPException: 422 if the name is invalid.
"""
async def check_agent_name(name: str) -> dict[str, Any]:
_require_agents_api_enabled()
_validate_agent_name(name)
normalized = _normalize_agent_name(name)
available = not get_paths().agent_dir(normalized).exists()
return {"available": available, "name": normalized}
normalized = _validate_display_name(name)
return {"available": True, "name": normalized}
@router.get(
"/agents/{name}",
"/agents/{agent_id}",
response_model=AgentResponse,
summary="Get Custom Agent",
description="Retrieve details and SOUL.md content for a specific custom agent.",
summary="Get Agent",
description="Retrieve details and SOUL.md content for a visible agent.",
)
async def get_agent(name: str) -> AgentResponse:
"""Get a specific custom agent by name.
Args:
name: The agent name.
Returns:
Agent details including SOUL.md content.
Raises:
HTTPException: 404 if agent not found.
"""
async def get_agent(agent_id: str, request: Request) -> AgentResponse:
_require_agents_api_enabled()
_validate_agent_name(name)
name = _normalize_agent_name(name)
agent_id = _validate_storage_id(agent_id)
try:
agent_cfg = load_agent_config(name)
return _agent_config_to_response(agent_cfg, include_soul=True)
except FileNotFoundError:
raise HTTPException(status_code=404, detail=f"Agent '{name}' not found")
store = get_agent_store(request)
await _sync_legacy_agents(store)
record = await store.get_visible(agent_id, _current_user_id(request))
if record is None:
raise HTTPException(status_code=404, detail=f"Agent '{agent_id}' not found")
return _record_to_response(record, include_soul=True)
except HTTPException:
raise
except Exception as e:
logger.error(f"Failed to get agent '{name}': {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Failed to get agent: {str(e)}")
logger.error("Failed to get agent '%s': %s", agent_id, e, exc_info=True)
raise HTTPException(status_code=500, detail=f"Failed to get agent: {str(e)}") from e
@router.post(
"/agents",
response_model=AgentResponse,
status_code=201,
summary="Create Custom Agent",
description="Create a new custom agent with its config and SOUL.md.",
summary="Create Agent",
description="Create a new user-owned agent. The display name can be Chinese and may duplicate existing names.",
)
async def create_agent_endpoint(request: AgentCreateRequest) -> AgentResponse:
"""Create a new custom agent.
Args:
request: The agent creation request.
Returns:
The created agent details.
Raises:
HTTPException: 409 if agent already exists, 422 if name is invalid.
"""
async def create_agent_endpoint(request: AgentCreateRequest, http_request: Request) -> AgentResponse:
_require_agents_api_enabled()
_validate_agent_name(request.name)
normalized_name = _normalize_agent_name(request.name)
agent_dir = get_paths().agent_dir(normalized_name)
if agent_dir.exists():
raise HTTPException(status_code=409, detail=f"Agent '{normalized_name}' already exists")
name = _validate_display_name(request.name)
agent_id = uuid4().hex
agent_dir = get_paths().agent_dir(agent_id)
try:
agent_dir.mkdir(parents=True, exist_ok=True)
store = get_agent_store(http_request)
if agent_dir.exists():
raise HTTPException(status_code=409, detail=f"Generated agent id '{agent_id}' already exists")
# Write config.yaml
config_data: dict = {"name": normalized_name}
if request.description:
config_data["description"] = request.description
if request.model is not None:
config_data["model"] = request.model
if request.tool_groups is not None:
config_data["tool_groups"] = request.tool_groups
if request.skills is not None:
config_data["skills"] = request.skills
_write_agent_config(
agent_id,
name=name,
description=request.description or "",
skills=request.skills,
model=request.model,
tool_groups=request.tool_groups,
)
_write_agent_soul(agent_id, request.soul)
config_file = agent_dir / "config.yaml"
with open(config_file, "w", encoding="utf-8") as f:
yaml.dump(config_data, f, default_flow_style=False, allow_unicode=True)
# Write SOUL.md
soul_file = agent_dir / "SOUL.md"
soul_file.write_text(request.soul, encoding="utf-8")
logger.info(f"Created agent '{normalized_name}' at {agent_dir}")
agent_cfg = load_agent_config(normalized_name)
return _agent_config_to_response(agent_cfg, include_soul=True)
record = await store.create(
{
"id": agent_id,
"name": name,
"description": request.description or "",
"user_id": _current_user_id(http_request),
"published": request.published,
}
)
logger.info("Created agent '%s' (%s) at %s", name, agent_id, agent_dir)
return _record_to_response(record, include_soul=True)
except HTTPException:
raise
except Exception as e:
# Clean up on failure
if agent_dir.exists():
shutil.rmtree(agent_dir)
logger.error(f"Failed to create agent '{request.name}': {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Failed to create agent: {str(e)}")
logger.error("Failed to create agent '%s': %s", request.name, e, exc_info=True)
raise HTTPException(status_code=500, detail=f"Failed to create agent: {str(e)}") from e
@router.put(
"/agents/{name}",
"/agents/{agent_id}",
response_model=AgentResponse,
summary="Update Custom Agent",
description="Update an existing custom agent's config and/or SOUL.md.",
summary="Update Agent",
description="Update an existing user-owned agent.",
)
async def update_agent(name: str, request: AgentUpdateRequest) -> AgentResponse:
"""Update an existing custom agent.
Args:
name: The agent name.
request: The update request (all fields optional).
Returns:
The updated agent details.
Raises:
HTTPException: 404 if agent not found.
"""
async def update_agent(agent_id: str, request: AgentUpdateRequest, http_request: Request) -> AgentResponse:
_require_agents_api_enabled()
_validate_agent_name(name)
name = _normalize_agent_name(name)
agent_id = _validate_storage_id(agent_id)
try:
agent_cfg = load_agent_config(name)
except FileNotFoundError:
raise HTTPException(status_code=404, detail=f"Agent '{name}' not found")
store = get_agent_store(http_request)
user_id = _current_user_id(http_request)
current = await _get_owned_or_raise(store, agent_id, user_id)
agent_dir = get_paths().agent_dir(name)
try:
# Update config if any config fields changed
# Use model_fields_set to distinguish "field omitted" from "explicitly set to null".
# This is critical for skills where None means "inherit all" (not "don't change").
fields_set = request.model_fields_set
config_changed = bool(fields_set & {"description", "model", "tool_groups", "skills"})
update_data: dict[str, Any] = {}
if "name" in fields_set:
update_data["name"] = _validate_display_name(request.name or "")
if "description" in fields_set:
update_data["description"] = request.description or ""
if "published" in fields_set:
update_data["published"] = bool(request.published)
if config_changed:
updated: dict = {
"name": agent_cfg.name,
"description": request.description if "description" in fields_set else agent_cfg.description,
}
new_model = request.model if "model" in fields_set else agent_cfg.model
if new_model is not None:
updated["model"] = new_model
next_name = update_data.get("name", current["name"])
next_description = update_data.get("description", current.get("description") or "")
new_tool_groups = request.tool_groups if "tool_groups" in fields_set else agent_cfg.tool_groups
if new_tool_groups is not None:
updated["tool_groups"] = new_tool_groups
existing_extras = _load_config_extras(agent_id)
next_skills = request.skills if "skills" in fields_set else existing_extras["skills"]
next_model = request.model if "model" in fields_set else existing_extras["model"]
next_tool_groups = request.tool_groups if "tool_groups" in fields_set else existing_extras["tool_groups"]
# skills: None = inherit all, [] = no skills, ["a","b"] = whitelist
if "skills" in fields_set:
new_skills = request.skills
else:
new_skills = agent_cfg.skills
if new_skills is not None:
updated["skills"] = new_skills
config_file = agent_dir / "config.yaml"
with open(config_file, "w", encoding="utf-8") as f:
yaml.dump(updated, f, default_flow_style=False, allow_unicode=True)
# Update SOUL.md if provided
config_dirty = bool(update_data) or any(key in fields_set for key in ("skills", "model", "tool_groups"))
if config_dirty:
_write_agent_config(
agent_id,
name=next_name,
description=next_description,
skills=next_skills,
model=next_model,
tool_groups=next_tool_groups,
)
if request.soul is not None:
soul_path = agent_dir / "SOUL.md"
soul_path.write_text(request.soul, encoding="utf-8")
_write_agent_soul(agent_id, request.soul)
logger.info(f"Updated agent '{name}'")
record = await store.update(agent_id, user_id, update_data) if update_data else current
if record is None:
raise HTTPException(status_code=404, detail=f"Agent '{agent_id}' not found")
refreshed_cfg = load_agent_config(name)
return _agent_config_to_response(refreshed_cfg, include_soul=True)
logger.info("Updated agent '%s' (%s)", record["name"], agent_id)
return _record_to_response(record, include_soul=True)
except HTTPException:
raise
except Exception as e:
logger.error(f"Failed to update agent '{name}': {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Failed to update agent: {str(e)}")
logger.error("Failed to update agent '%s': %s", agent_id, e, exc_info=True)
raise HTTPException(status_code=500, detail=f"Failed to update agent: {str(e)}") from e
class UserProfileResponse(BaseModel):
@@ -333,7 +377,7 @@ class UserProfileResponse(BaseModel):
class UserProfileUpdateRequest(BaseModel):
"""Request body for setting the global user profile."""
content: str = Field(default="", description="USER.md content — describes the user's background and preferences")
content: str = Field(default="", description="USER.md content - describes the user's background and preferences")
@router.get(
@@ -343,11 +387,6 @@ class UserProfileUpdateRequest(BaseModel):
description="Read the global USER.md file that is injected into all custom agents.",
)
async def get_user_profile() -> UserProfileResponse:
"""Return the current USER.md content.
Returns:
UserProfileResponse with content=None if USER.md does not exist yet.
"""
_require_agents_api_enabled()
try:
@@ -357,8 +396,8 @@ async def get_user_profile() -> UserProfileResponse:
raw = user_md_path.read_text(encoding="utf-8").strip()
return UserProfileResponse(content=raw or None)
except Exception as e:
logger.error(f"Failed to read user profile: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Failed to read user profile: {str(e)}")
logger.error("Failed to read user profile: %s", e, exc_info=True)
raise HTTPException(status_code=500, detail=f"Failed to read user profile: {str(e)}") from e
@router.put(
@@ -368,54 +407,43 @@ async def get_user_profile() -> UserProfileResponse:
description="Write the global USER.md file that is injected into all custom agents.",
)
async def update_user_profile(request: UserProfileUpdateRequest) -> UserProfileResponse:
"""Create or overwrite the global USER.md.
Args:
request: The update request with the new USER.md content.
Returns:
UserProfileResponse with the saved content.
"""
_require_agents_api_enabled()
try:
paths = get_paths()
paths.base_dir.mkdir(parents=True, exist_ok=True)
paths.user_md_file.write_text(request.content, encoding="utf-8")
logger.info(f"Updated USER.md at {paths.user_md_file}")
logger.info("Updated USER.md at %s", paths.user_md_file)
return UserProfileResponse(content=request.content or None)
except Exception as e:
logger.error(f"Failed to update user profile: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Failed to update user profile: {str(e)}")
logger.error("Failed to update user profile: %s", e, exc_info=True)
raise HTTPException(status_code=500, detail=f"Failed to update user profile: {str(e)}") from e
@router.delete(
"/agents/{name}",
"/agents/{agent_id}",
status_code=204,
summary="Delete Custom Agent",
description="Delete a custom agent and all its files (config, SOUL.md, memory).",
summary="Delete Agent",
description="Delete a user-owned agent and all its files.",
)
async def delete_agent(name: str) -> None:
"""Delete a custom agent.
Args:
name: The agent name.
Raises:
HTTPException: 404 if agent not found.
"""
async def delete_agent(agent_id: str, request: Request) -> None:
_require_agents_api_enabled()
_validate_agent_name(name)
name = _normalize_agent_name(name)
agent_dir = get_paths().agent_dir(name)
if not agent_dir.exists():
raise HTTPException(status_code=404, detail=f"Agent '{name}' not found")
agent_id = _validate_storage_id(agent_id)
try:
shutil.rmtree(agent_dir)
logger.info(f"Deleted agent '{name}' from {agent_dir}")
store = get_agent_store(request)
user_id = _current_user_id(request)
await _get_owned_or_raise(store, agent_id, user_id)
deleted = await store.delete(agent_id, user_id)
if not deleted:
raise HTTPException(status_code=404, detail=f"Agent '{agent_id}' not found")
agent_dir = get_paths().agent_dir(agent_id)
if agent_dir.exists():
shutil.rmtree(agent_dir)
logger.info("Deleted agent '%s' from %s", agent_id, agent_dir)
except HTTPException:
raise
except Exception as e:
logger.error(f"Failed to delete agent '{name}': {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Failed to delete agent: {str(e)}")
logger.error("Failed to delete agent '%s': %s", agent_id, e, exc_info=True)
raise HTTPException(status_code=500, detail=f"Failed to delete agent: {str(e)}") from e
@@ -13,7 +13,7 @@ import logging
from datetime import UTC, datetime
from typing import Any
from fastapi import APIRouter, HTTPException
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel, Field
logger = logging.getLogger(__name__)
@@ -56,23 +56,37 @@ def _get_default_assistant() -> AssistantResponse:
)
def _list_assistants() -> list[AssistantResponse]:
"""List all available assistants from config."""
assistants = [_get_default_assistant()]
async def _sync_legacy_agents(store) -> None:
from deerflow.config.agents_config import list_custom_agents
# Also include custom agents from config.yaml agents directory
for agent_cfg in list_custom_agents():
agent_id = agent_cfg.id or agent_cfg.name
if agent_id:
await store.ensure_builtin(
{
"id": agent_id,
"name": agent_cfg.name,
"description": agent_cfg.description or "",
"published": True,
}
)
def _legacy_assistants() -> list[AssistantResponse]:
assistants: list[AssistantResponse] = []
try:
from deerflow.config.agents_config import list_custom_agents
for agent_cfg in list_custom_agents():
now = datetime.now(UTC).isoformat()
assistant_id = agent_cfg.id or agent_cfg.name
assistants.append(
AssistantResponse(
assistant_id=agent_cfg.name,
graph_id="lead_agent", # All agents use the same graph
assistant_id=assistant_id,
graph_id="lead_agent",
name=agent_cfg.name,
config={},
metadata={"created_by": "user"},
metadata={"created_by": "system", "agent_id": assistant_id},
description=agent_cfg.description or "",
created_at=now,
updated_at=now,
@@ -80,18 +94,54 @@ def _list_assistants() -> list[AssistantResponse]:
)
)
except Exception:
logger.debug("Could not load custom agents for assistants list")
logger.debug("Could not load legacy custom agents for assistants list")
return assistants
async def _list_assistants(request: Request) -> list[AssistantResponse]:
"""List all available assistants from config."""
assistants = [_get_default_assistant()]
try:
from app.gateway.deps import get_agent_store
from deerflow.runtime.user_context import get_effective_user_id
store = get_agent_store(request)
await _sync_legacy_agents(store)
for record in await store.list_visible(get_effective_user_id()):
created_at = str(record.get("created_at") or datetime.now(UTC).isoformat())
updated_at = str(record.get("updated_at") or created_at)
assistants.append(
AssistantResponse(
assistant_id=record["id"],
graph_id="lead_agent", # All agents use the same graph
name=record["name"],
config={},
metadata={
"created_by": "system" if record.get("user_id") is None else "user",
"agent_id": record["id"],
"published": bool(record.get("published", False)),
},
description=record.get("description") or "",
created_at=created_at,
updated_at=updated_at,
version=1,
)
)
except Exception:
logger.debug("Could not load DB-backed custom agents for assistants list")
assistants.extend(_legacy_assistants())
return assistants
@router.post("/search", response_model=list[AssistantResponse])
async def search_assistants(body: AssistantSearchRequest | None = None) -> list[AssistantResponse]:
async def search_assistants(request: Request, body: AssistantSearchRequest | None = None) -> list[AssistantResponse]:
"""Search assistants.
Returns all registered assistants (lead_agent + custom agents from config).
"""
assistants = _list_assistants()
assistants = await _list_assistants(request)
if body and body.graph_id:
assistants = [a for a in assistants if a.graph_id == body.graph_id]
@@ -104,22 +154,22 @@ async def search_assistants(body: AssistantSearchRequest | None = None) -> list[
@router.get("/{assistant_id}", response_model=AssistantResponse)
async def get_assistant_compat(assistant_id: str) -> AssistantResponse:
async def get_assistant_compat(assistant_id: str, request: Request) -> AssistantResponse:
"""Get an assistant by ID."""
for a in _list_assistants():
for a in await _list_assistants(request):
if a.assistant_id == assistant_id:
return a
raise HTTPException(status_code=404, detail=f"Assistant {assistant_id} not found")
@router.get("/{assistant_id}/graph")
async def get_assistant_graph(assistant_id: str) -> dict:
async def get_assistant_graph(assistant_id: str, request: Request) -> dict:
"""Get the graph structure for an assistant.
Returns a minimal graph description. Full graph introspection is
not supported in the Gateway — this stub satisfies SDK validation.
"""
found = any(a.assistant_id == assistant_id for a in _list_assistants())
found = any(a.assistant_id == assistant_id for a in await _list_assistants(request))
if not found:
raise HTTPException(status_code=404, detail=f"Assistant {assistant_id} not found")
@@ -131,12 +181,12 @@ async def get_assistant_graph(assistant_id: str) -> dict:
@router.get("/{assistant_id}/schemas")
async def get_assistant_schemas(assistant_id: str) -> dict:
async def get_assistant_schemas(assistant_id: str, request: Request) -> dict:
"""Get JSON schemas for an assistant's input/output/state.
Returns empty schemas — full introspection not supported in Gateway.
"""
found = any(a.assistant_id == assistant_id for a in _list_assistants())
found = any(a.assistant_id == assistant_id for a in await _list_assistants(request))
if not found:
raise HTTPException(status_code=404, detail=f"Assistant {assistant_id} not found")
@@ -106,6 +106,7 @@ _DEFAULT_ASSISTANT_ID = "lead_agent"
# ``configurable`` for consumers like ``setup_agent``.
_CONTEXT_CONFIGURABLE_KEYS: frozenset[str] = frozenset(
{
"agent_id",
"model_name",
"mode",
"thinking_enabled",
@@ -139,11 +140,11 @@ def merge_run_context_overrides(config: dict[str, Any], context: Mapping[str, An
def resolve_agent_factory(assistant_id: str | None):
"""Resolve the agent factory callable from config.
Custom agents are implemented as ``lead_agent`` + an ``agent_name``
Custom agents are implemented as ``lead_agent`` + an ``agent_id``
injected into ``configurable`` or ``context`` — see
:func:`build_run_config`. All ``assistant_id`` values therefore map to the
same factory; the routing happens inside ``make_lead_agent`` when it reads
``cfg["agent_name"]``.
``cfg["agent_id"]``.
"""
from deerflow.agents.lead_agent.agent import make_lead_agent
@@ -160,11 +161,11 @@ def build_run_config(
"""Build a RunnableConfig dict for the agent.
When *assistant_id* refers to a custom agent (anything other than
``"lead_agent"`` / ``None``), the name is forwarded as ``agent_name`` in
``"lead_agent"`` / ``None``), the id is forwarded as ``agent_id`` in
whichever runtime options container is active: ``context`` for
LangGraph >= 0.6.0 requests, otherwise ``configurable``.
``make_lead_agent`` reads this key to load the matching
``agents/<name>/SOUL.md`` and per-agent config — without it the agent
``agents/<id>/SOUL.md`` and per-agent config — without it the agent
silently runs as the default lead agent.
This mirrors the channel manager's ``_resolve_run_params`` logic so that
@@ -202,25 +203,96 @@ def build_run_config(
else:
config["configurable"] = {"thread_id": thread_id}
# Inject custom agent name when the caller specified a non-default assistant.
# Honour an explicit agent_name in the active runtime options container.
# Inject custom agent id when the caller specified a non-default assistant.
# Honour an explicit agent_id in the active runtime options container.
if assistant_id and assistant_id != _DEFAULT_ASSISTANT_ID:
normalized = assistant_id.strip().lower().replace("_", "-")
if not normalized or not re.fullmatch(r"[a-z0-9-]+", normalized):
raise ValueError(f"Invalid assistant_id {assistant_id!r}: must contain only letters, digits, and hyphens after normalization.")
normalized = assistant_id.strip()
if not normalized or not re.fullmatch(r"[A-Za-z0-9_-]+", normalized):
raise ValueError(f"Invalid assistant_id {assistant_id!r}: must contain only letters, digits, hyphens, and underscores.")
if "configurable" in config:
target = config["configurable"]
elif "context" in config:
target = config["context"]
else:
target = config.setdefault("configurable", {})
if target is not None and "agent_name" not in target:
target["agent_name"] = normalized
if target is not None and "agent_id" not in target:
target["agent_id"] = normalized
if metadata:
config.setdefault("metadata", {}).update(metadata)
return config
def _collect_requested_agent_ids(body: Any) -> set[str]:
"""Collect agent ids from assistant_id/config/context for access checks."""
agent_ids: set[str] = set()
if body.assistant_id and body.assistant_id != _DEFAULT_ASSISTANT_ID:
agent_ids.add(str(body.assistant_id))
def collect(container: Mapping[str, Any] | None) -> None:
if not container:
return
for key in ("agent_id", "agent_name"):
value = container.get(key)
if value:
agent_ids.add(str(value))
context = getattr(body, "context", None)
if isinstance(context, Mapping):
collect(context)
config = body.config or {}
if isinstance(config, Mapping):
nested_context = config.get("context")
nested_configurable = config.get("configurable")
if isinstance(nested_context, Mapping):
collect(nested_context)
if isinstance(nested_configurable, Mapping):
collect(nested_configurable)
return agent_ids
async def _sync_legacy_agent_records(store) -> None:
"""Import existing folder-backed agents as built-in records."""
from deerflow.config.agents_config import list_custom_agents
for agent_cfg in list_custom_agents():
agent_id = agent_cfg.id or agent_cfg.name
if not agent_id:
continue
await store.ensure_builtin(
{
"id": agent_id,
"name": agent_cfg.name,
"description": agent_cfg.description or "",
"published": True,
}
)
async def _enforce_agent_access(body: Any, request: Request) -> None:
agent_ids = _collect_requested_agent_ids(body)
if not agent_ids:
return
from app.gateway.deps import get_agent_store
from deerflow.config.agents_config import validate_agent_id
from deerflow.runtime.user_context import get_effective_user_id
store = get_agent_store(request)
await _sync_legacy_agent_records(store)
user_id = get_effective_user_id()
for agent_id in agent_ids:
try:
normalized = validate_agent_id(agent_id)
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
if normalized is None:
continue
if await store.get_visible(normalized, user_id) is None:
raise HTTPException(status_code=404, detail=f"Agent {normalized} not found")
# ---------------------------------------------------------------------------
# Run lifecycle
# ---------------------------------------------------------------------------
@@ -249,6 +321,8 @@ async def start_run(
disconnect = DisconnectMode.cancel if body.on_disconnect == "cancel" else DisconnectMode.continue_
await _enforce_agent_access(body, request)
try:
record = await run_mgr.create_or_reject(
thread_id,