智能体分权

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

@@ -12,23 +12,33 @@ from deerflow.config.paths import get_paths
logger = logging.getLogger(__name__)
SOUL_FILENAME = "SOUL.md"
AGENT_NAME_PATTERN = re.compile(r"^[A-Za-z0-9-]+$")
AGENT_ID_PATTERN = re.compile(r"^[A-Za-z0-9_-]+$")
# Backward-compatible alias. Historically this validated the display name;
# after the DB-backed agent table, display names can be Chinese and duplicated.
# The pattern now applies only to storage/runtime ids.
AGENT_NAME_PATTERN = AGENT_ID_PATTERN
def validate_agent_id(agent_id: str | None) -> str | None:
"""Validate a custom agent id before using it in filesystem paths."""
if agent_id is None:
return None
if not isinstance(agent_id, str):
raise ValueError("Invalid agent id. Expected a string or None.")
if not AGENT_ID_PATTERN.fullmatch(agent_id):
raise ValueError(f"Invalid agent id '{agent_id}'. Must match pattern: {AGENT_ID_PATTERN.pattern}")
return agent_id
def validate_agent_name(name: str | None) -> str | None:
"""Validate a custom agent name before using it in filesystem paths."""
if name is None:
return None
if not isinstance(name, str):
raise ValueError("Invalid agent name. Expected a string or None.")
if not AGENT_NAME_PATTERN.fullmatch(name):
raise ValueError(f"Invalid agent name '{name}'. Must match pattern: {AGENT_NAME_PATTERN.pattern}")
return name
"""Backward-compatible alias for validating a storage/runtime agent id."""
return validate_agent_id(name)
class AgentConfig(BaseModel):
"""Configuration for a custom agent."""
id: str | None = None
name: str
description: str = ""
model: str | None = None
@@ -40,11 +50,11 @@ class AgentConfig(BaseModel):
skills: list[str] | None = None
def load_agent_config(name: str | None) -> AgentConfig | None:
def load_agent_config(agent_id: str | None) -> AgentConfig | None:
"""Load the custom or default agent's config from its directory.
Args:
name: The agent name.
agent_id: The agent storage/runtime id.
Returns:
AgentConfig instance.
@@ -54,28 +64,32 @@ def load_agent_config(name: str | None) -> AgentConfig | None:
ValueError: If config.yaml cannot be parsed.
"""
if name is None:
if agent_id is None:
return None
name = validate_agent_name(name)
agent_dir = get_paths().agent_dir(name)
agent_id = validate_agent_id(agent_id)
agent_dir = get_paths().agent_dir(agent_id)
config_file = agent_dir / "config.yaml"
if not agent_dir.exists():
raise FileNotFoundError(f"Agent directory not found: {agent_dir}")
if not config_file.exists():
if not config_file.exists() and not (agent_dir / SOUL_FILENAME).exists():
raise FileNotFoundError(f"Agent config not found: {config_file}")
try:
with open(config_file, encoding="utf-8") as f:
data: dict[str, Any] = yaml.safe_load(f) or {}
except yaml.YAMLError as e:
raise ValueError(f"Failed to parse agent config {config_file}: {e}") from e
data: dict[str, Any] = {}
if config_file.exists():
try:
with open(config_file, encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
except yaml.YAMLError as e:
raise ValueError(f"Failed to parse agent config {config_file}: {e}") from e
# Ensure name is set from directory name if not in file
# Ensure id/name are set from directory id if not in file.
if "id" not in data:
data["id"] = agent_id
if "name" not in data:
data["name"] = name
data["name"] = agent_id
# Strip unknown fields before passing to Pydantic (e.g. legacy prompt_file)
known_fields = set(AgentConfig.model_fields.keys())
@@ -84,19 +98,19 @@ def load_agent_config(name: str | None) -> AgentConfig | None:
return AgentConfig(**data)
def load_agent_soul(agent_name: str | None) -> str | None:
def load_agent_soul(agent_id: str | None) -> str | None:
"""Read the SOUL.md file for a custom agent, if it exists.
SOUL.md defines the agent's personality, values, and behavioral guardrails.
It is injected into the lead agent's system prompt as additional context.
Args:
agent_name: The name of the agent or None for the default agent.
agent_id: The storage/runtime id of the agent or None for the default agent.
Returns:
The SOUL.md content as a string, or None if the file does not exist.
"""
agent_dir = get_paths().agent_dir(agent_name) if agent_name else get_paths().base_dir
agent_dir = get_paths().agent_dir(validate_agent_id(agent_id)) if agent_id else get_paths().base_dir
soul_path = agent_dir / SOUL_FILENAME
if not soul_path.exists():
return None
@@ -122,8 +136,9 @@ def list_custom_agents() -> list[AgentConfig]:
continue
config_file = entry / "config.yaml"
if not config_file.exists():
logger.debug(f"Skipping {entry.name}: no config.yaml")
soul_file = entry / SOUL_FILENAME
if not config_file.exists() and not soul_file.exists():
logger.debug(f"Skipping {entry.name}: no config.yaml or SOUL.md")
continue
try:
@@ -68,7 +68,7 @@ class Paths:
├── memory.json
├── USER.md <-- global user profile (injected into all agents)
├── agents/
│ └── {agent_name}/
│ └── {agent_id}/
│ ├── config.yaml
│ ├── SOUL.md <-- agent personality/identity (injected alongside lead prompt)
│ └── memory.json
@@ -136,11 +136,11 @@ class Paths:
return self.base_dir / "agents"
def agent_dir(self, name: str) -> Path:
"""Directory for a specific agent: `{base_dir}/agents/{name}/`."""
"""Directory for a specific agent id: `{base_dir}/agents/{id}/`."""
return self.agents_dir / name.lower()
def agent_memory_file(self, name: str) -> Path:
"""Per-agent memory file: `{base_dir}/agents/{name}/memory.json`."""
"""Per-agent memory file: `{base_dir}/agents/{id}/memory.json`."""
return self.agent_dir(name) / "memory.json"
def user_dir(self, user_id: str) -> Path:
@@ -152,7 +152,7 @@ class Paths:
return self.user_dir(user_id) / "memory.json"
def user_agent_memory_file(self, user_id: str, agent_name: str) -> Path:
"""Per-user per-agent memory: `{base_dir}/users/{user_id}/agents/{name}/memory.json`."""
"""Per-user per-agent memory: `{base_dir}/users/{user_id}/agents/{id}/memory.json`."""
return self.user_dir(user_id) / "agents" / agent_name.lower() / "memory.json"
def thread_dir(self, thread_id: str, *, user_id: str | None = None) -> Path: