Skip to content

Self-improving AI Employees for everyone

feat: add durable parallel agent delegation

trohitg1e7c0fd72cd6
diff --git a/.env.template b/.env.template
index 5f23cae5..1d68bdd2 100644
--- a/.env.template
+++ b/.env.template
@@ -150,6 +150,11 @@ COMPACTION_RATIO=0.8
# Per-user overrides via the UserSettings row (Settings tab).
AGENT_RECURSION_LIMIT=200
+# Multi-agent delegation. The concurrency limit counts all active children
+# and grandchildren in one root execution; the root agent is not counted.
+MAX_CONCURRENT_SUBAGENTS=3
+MAX_DELEGATION_DEPTH=2
+
# Browser automation (agent-browser CLI). Each distinct browser
# session maps to one Chrome instance. BROWSER_MAX_INSTANCES caps
# concurrent instances — when a new session would exceed it, the
diff --git a/client/src/components/TeamMonitorNode.tsx b/client/src/components/TeamMonitorNode.tsx
index 5eb61d0b..19f79437 100644
--- a/client/src/components/TeamMonitorNode.tsx
+++ b/client/src/components/TeamMonitorNode.tsx
@@ -30,6 +30,7 @@ interface TeamStatus {
total: number;
completed: number;
active: number;
+ queued: number;
pending: number;
failed: number;
};
@@ -39,6 +40,7 @@ interface TeamStatus {
const TeamMonitorNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectable, selected }) => {
const theme = useAppTheme();
const setSelectedNode = useAppStore((s) => s.setSelectedNode);
+ const workflowId = useAppStore((s) => s.currentWorkflow?.id);
const { sendRequest } = useWebSocket();
const edges = useEdges();
const nodes = useNodes();
@@ -74,7 +76,8 @@ const TeamMonitorNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConn
// Request team status - backend will find the active team for the workflow
const response = await sendRequest<{ status?: any }>('get_team_status', {
team_id: teamId,
- team_lead_node_id: connectedTeamLead?.id
+ workflow_id: workflowId,
+ team_lead_node_id: connectedTeamLead?.id,
});
if (response?.status) {
setTeamStatus({
@@ -84,6 +87,7 @@ const TeamMonitorNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConn
total: response.status.task_count || 0,
completed: response.status.completed_count || 0,
active: response.status.active_count || 0,
+ queued: response.status.queued_count ?? response.status.pending_count ?? 0,
pending: response.status.pending_count || 0,
failed: response.status.failed_count || 0,
},
@@ -95,7 +99,7 @@ const TeamMonitorNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConn
} finally {
setIsLoading(false);
}
- }, [data?.teamId, connectedTeamLead, sendRequest]);
+ }, [data?.teamId, connectedTeamLead, workflowId, sendRequest]);
// Auto-refresh when connected to a team lead
useEffect(() => {
@@ -155,7 +159,7 @@ const TeamMonitorNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConn
{/* Stats Grid */}
<div style={{
display: 'grid',
- gridTemplateColumns: 'repeat(4, 1fr)',
+ gridTemplateColumns: 'repeat(5, 1fr)',
gap: 2,
padding: '6px 4px',
borderBottom: `1px solid ${theme.colors.border}`,
@@ -184,6 +188,12 @@ const TeamMonitorNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConn
</div>
<div style={{ fontSize: 8, color: theme.colors.textSecondary }}>Active</div>
</div>
+ <div style={{ textAlign: 'center' }}>
+ <div style={{ fontSize: 12, fontWeight: 'bold', color: 'var(--warning)' }}>
+ {teamStatus?.tasks?.queued || 0}
+ </div>
+ <div style={{ fontSize: 8, color: theme.colors.textSecondary }}>Queued</div>
+ </div>
</div>
{/* Active Tasks */}
diff --git a/server/core/config.py b/server/core/config.py
index 5228d9c1..f38f3e61 100644
--- a/server/core/config.py
+++ b/server/core/config.py
@@ -338,6 +338,13 @@ class Settings(BaseSettings):
# innermost override.
agent_recursion_limit: int = Field(default=200, env="AGENT_RECURSION_LIMIT", ge=1)
+ # Multi-agent delegation guardrails. The concurrency cap applies to all
+ # active descendants of one root execution (the root itself is excluded).
+ # Team leads may delegate one additional level, but deeper trees are
+ # rejected before a child workflow is scheduled.
+ max_concurrent_subagents: int = Field(default=3, env="MAX_CONCURRENT_SUBAGENTS", ge=1, le=50)
+ max_delegation_depth: int = Field(default=2, env="MAX_DELEGATION_DEPTH", ge=1, le=2)
+
# Gunicorn Configuration (for production deployment)
gunicorn_timeout: int = Field(default=120, env="GUNICORN_TIMEOUT", ge=30)
gunicorn_graceful_timeout: int = Field(default=30, env="GUNICORN_GRACEFUL_TIMEOUT", ge=10)
diff --git a/server/core/database.py b/server/core/database.py
index 92685ecd..e65e47a1 100644
--- a/server/core/database.py
+++ b/server/core/database.py
@@ -34,6 +34,8 @@ from models.database import (
TeamMember,
TeamTask,
AgentMessage,
+ SubagentConcurrencyCounter,
+ SubagentConcurrencyPermit,
GoogleConnection,
ProxyProviderConfig,
ProxyRoutingRule,
@@ -103,6 +105,7 @@ class Database:
# Add missing columns to existing tables (simple migration)
await self._migrate_user_settings()
+ await self._migrate_agent_teams()
logger.info("Database initialized successfully")
@@ -164,6 +167,11 @@ class Database:
await conn.execute(text("ALTER TABLE user_settings ADD COLUMN agent_recursion_limit INTEGER DEFAULT 200"))
logger.info("Added agent_recursion_limit column to user_settings")
+ if "max_concurrent_subagents" not in columns:
+ await conn.execute(text("ALTER TABLE user_settings ADD COLUMN max_concurrent_subagents INTEGER DEFAULT 3"))
+ if "max_delegation_depth" not in columns:
+ await conn.execute(text("ALTER TABLE user_settings ADD COLUMN max_delegation_depth INTEGER DEFAULT 2"))
+
# Migrate token_usage_metrics table - add cost columns
result = await conn.execute(text("PRAGMA table_info(token_usage_metrics)"))
columns = {row[1] for row in result.fetchall()}
@@ -225,6 +233,28 @@ class Database:
except Exception as e:
logger.warning(f"Migration check failed (table may not exist yet): {e}")
+ async def _migrate_agent_teams(self):
+ """Add execution identity columns used by durable delegation."""
+ try:
+ async with self.engine.begin() as conn:
+ result = await conn.execute(text("PRAGMA table_info(agent_teams)"))
+ columns = {row[1] for row in result.fetchall()}
+ if columns and "execution_id" not in columns:
+ await conn.execute(text("ALTER TABLE agent_teams ADD COLUMN execution_id VARCHAR(255)"))
+ if columns and "root_execution_id" not in columns:
+ await conn.execute(text("ALTER TABLE agent_teams ADD COLUMN root_execution_id VARCHAR(255)"))
+ await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_agent_teams_execution_id ON agent_teams(execution_id)"))
+ await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_agent_teams_root_execution_id ON agent_teams(root_execution_id)"))
+ await conn.execute(text("CREATE UNIQUE INDEX IF NOT EXISTS uq_agent_team_execution_lead ON agent_teams(execution_id, team_lead_node_id) WHERE execution_id IS NOT NULL"))
+
+ result = await conn.execute(text("PRAGMA table_info(agent_messages)"))
+ message_columns = {row[1] for row in result.fetchall()}
+ if message_columns and "event_id" not in message_columns:
+ await conn.execute(text("ALTER TABLE agent_messages ADD COLUMN event_id VARCHAR(255)"))
+ await conn.execute(text("CREATE UNIQUE INDEX IF NOT EXISTS ix_agent_messages_event_id ON agent_messages(event_id) WHERE event_id IS NOT NULL"))
+ except Exception as e:
+ logger.warning(f"Agent-team migration check failed: {e}")
+
async def shutdown(self):
"""Close database connections."""
if self.engine:
@@ -1430,6 +1460,10 @@ class Database:
if not schema:
return None
+ pending_count = sum(1 for t in tasks if t.status == "pending")
+ active_count = sum(1 for t in tasks if t.status == "in_progress")
+ completed_count = sum(1 for t in tasks if t.status == "completed")
+ failed_count = sum(1 for t in tasks if t.status == "failed")
return {
"node_id": schema.node_id,
"tool_name": schema.tool_name,
@@ -1763,6 +1797,8 @@ class Database:
"auto_add_skill_for_tools": settings.auto_add_skill_for_tools,
"auto_rebind_tools_after_canvas_change": settings.auto_rebind_tools_after_canvas_change,
"agent_recursion_limit": settings.agent_recursion_limit,
+ "max_concurrent_subagents": settings.max_concurrent_subagents,
+ "max_delegation_depth": settings.max_delegation_depth,
"created_at": settings.created_at.isoformat() if settings.created_at else None,
"updated_at": settings.updated_at.isoformat() if settings.updated_at else None,
}
@@ -2302,7 +2338,8 @@ class Database:
# ============================================================================
async def create_team(
- self, team_id: str, workflow_id: str, team_lead_node_id: str, config: Optional[Dict[str, Any]] = None
+ self, team_id: str, workflow_id: str, team_lead_node_id: str, config: Optional[Dict[str, Any]] = None,
+ execution_id: Optional[str] = None, root_execution_id: Optional[str] = None,
) -> Optional[Dict[str, Any]]:
"""Create a new agent team."""
try:
@@ -2311,13 +2348,16 @@ class Database:
id=team_id,
workflow_id=workflow_id,
team_lead_node_id=team_lead_node_id,
+ execution_id=execution_id,
+ root_execution_id=root_execution_id or execution_id,
config=config or {},
created_at=datetime.now(timezone.utc),
)
session.add(team)
await session.commit()
logger.info(f"[Teams] Created team {team_id}")
- return {"id": team.id, "workflow_id": team.workflow_id, "status": team.status}
+ return {"id": team.id, "workflow_id": team.workflow_id, "execution_id": team.execution_id,
+ "root_execution_id": team.root_execution_id, "status": team.status}
except Exception as e:
logger.error(f"Failed to create team: {e}")
return None
@@ -2334,6 +2374,8 @@ class Database:
"id": team.id,
"workflow_id": team.workflow_id,
"team_lead_node_id": team.team_lead_node_id,
+ "execution_id": team.execution_id,
+ "root_execution_id": team.root_execution_id,
"status": team.status,
"config": team.config,
"created_at": team.created_at.isoformat() if team.created_at else None,
@@ -2342,6 +2384,30 @@ class Database:
logger.error(f"Failed to get team: {e}")
return None
+ async def find_team(
+ self, workflow_id: str, team_lead_node_id: str,
+ execution_id: Optional[str] = None, active_first: bool = True,
+ ) -> Optional[Dict[str, Any]]:
+ """Resolve an execution team, or the latest team for a workflow lead."""
+ try:
+ async with self.get_session() as session:
+ query = select(AgentTeam).where(
+ AgentTeam.workflow_id == workflow_id,
+ AgentTeam.team_lead_node_id == team_lead_node_id,
+ )
+ if execution_id:
+ query = query.where(AgentTeam.execution_id == execution_id)
+ elif active_first:
+ query = query.order_by(case((AgentTeam.status == "active", 0), else_=1), AgentTeam.created_at.desc())
+ else:
+ query = query.order_by(AgentTeam.created_at.desc())
+ result = await session.execute(query.limit(1))
+ team = result.scalar_one_or_none()
+ return await self.get_team(team.id) if team else None
+ except Exception as e:
+ logger.error(f"Failed to find team: {e}")
+ return None
+
async def update_team_status(self, team_id: str, status: str) -> bool:
"""Update team status."""
try:
@@ -2353,6 +2419,8 @@ class Database:
team.status = status
if status in ("completed", "failed", "dissolved"):
team.completed_at = datetime.now(timezone.utc)
+ elif status == "active":
+ team.completed_at = None
await session.commit()
return True
except Exception as e:
@@ -2360,17 +2428,28 @@ class Database:
return False
async def add_team_member(
- self, team_id: str, agent_node_id: str, agent_type: str, role: str = "teammate", agent_label: Optional[str] = None
+ self, team_id: str, agent_node_id: str, agent_type: str, role: str = "teammate", agent_label: Optional[str] = None,
+ capabilities: Optional[Dict[str, Any]] = None,
) -> Optional[Dict[str, Any]]:
"""Add member to team."""
try:
async with self.get_session() as session:
+ existing = await session.execute(select(TeamMember).where(
+ TeamMember.team_id == team_id, TeamMember.agent_node_id == agent_node_id
+ ))
+ member = existing.scalar_one_or_none()
+ if member:
+ member.agent_type, member.agent_label, member.role = agent_type, agent_label, role
+ member.capabilities = capabilities
+ await session.commit()
+ return {"id": member.id, "agent_node_id": agent_node_id, "role": role}
member = TeamMember(
team_id=team_id,
agent_node_id=agent_node_id,
agent_type=agent_type,
agent_label=agent_label,
role=role,
+ capabilities=capabilities,
joined_at=datetime.now(timezone.utc),
)
session.add(member)
@@ -2430,6 +2509,12 @@ class Database:
"""Add task to team's shared list."""
try:
async with self.get_session() as session:
+ existing = await session.execute(select(TeamTask).where(TeamTask.id == task_id))
+ task = existing.scalar_one_or_none()
+ if task:
+ if task.team_id != team_id:
+ return None
+ return {"id": task.id, "title": task.title, "status": task.status}
task = TeamTask(
id=task_id,
team_id=team_id,
@@ -2638,22 +2723,30 @@ class Database:
return []
async def add_agent_message(
- self, team_id: str, from_agent: str, content: str, message_type: str = "direct", to_agent: Optional[str] = None
+ self, team_id: str, from_agent: str, content: str, message_type: str = "direct", to_agent: Optional[str] = None,
+ event_id: Optional[str] = None, extra_data: Optional[Dict[str, Any]] = None,
) -> Optional[Dict[str, Any]]:
"""Add message between agents."""
try:
async with self.get_session() as session:
+ if event_id:
+ existing = await session.execute(select(AgentMessage).where(AgentMessage.event_id == event_id))
+ msg = existing.scalar_one_or_none()
+ if msg:
+ return {"id": msg.id, "event_id": msg.event_id, "from_agent": msg.from_agent, "to_agent": msg.to_agent}
msg = AgentMessage(
+ event_id=event_id,
team_id=team_id,
from_agent=from_agent,
to_agent=to_agent,
message_type=message_type,
content=content,
+ extra_data=extra_data,
created_at=datetime.now(timezone.utc),
)
session.add(msg)
await session.commit()
- return {"id": msg.id, "from_agent": from_agent, "to_agent": to_agent}
+ return {"id": msg.id, "event_id": msg.event_id, "from_agent": from_agent, "to_agent": to_agent}
except Exception as e:
logger.error(f"Failed to add agent message: {e}")
return None
@@ -2676,12 +2769,14 @@ class Database:
return [
{
"id": m.id,
+ "event_id": m.event_id,
"from_agent": m.from_agent,
"to_agent": m.to_agent,
"message_type": m.message_type,
"content": m.content,
"read": m.read,
"created_at": m.created_at.isoformat() if m.created_at else None,
+ "extra_data": m.extra_data,
}
for m in result.scalars().all()
]
@@ -2730,13 +2825,31 @@ class Database:
return {
"team_id": team_id,
"status": team.status,
+ "workflow_id": team.workflow_id,
+ "team_lead_node_id": team.team_lead_node_id,
+ "execution_id": team.execution_id,
+ "root_execution_id": team.root_execution_id,
"member_count": len(members),
"task_total": len(tasks),
- "task_pending": sum(1 for t in tasks if t.status == "pending"),
- "task_in_progress": sum(1 for t in tasks if t.status == "in_progress"),
- "task_completed": sum(1 for t in tasks if t.status == "completed"),
- "task_failed": sum(1 for t in tasks if t.status == "failed"),
- "members": [{"id": m.agent_node_id, "type": m.agent_type, "status": m.status} for m in members],
+ "task_pending": pending_count,
+ "task_in_progress": active_count,
+ "task_completed": completed_count,
+ "task_failed": failed_count,
+ # Stable response aliases consumed by TeamMonitor and
+ # existing WS clients.
+ "task_count": len(tasks),
+ "pending_count": pending_count,
+ "queued_count": pending_count,
+ "active_count": active_count,
+ "completed_count": completed_count,
+ "failed_count": failed_count,
+ "members": [{"id": m.agent_node_id, "agent_node_id": m.agent_node_id,
+ "type": m.agent_type, "agent_type": m.agent_type, "label": m.agent_label,
+ "role": m.role, "status": m.status, "capabilities": m.capabilities} for m in members],
+ "queued_tasks": [
+ {"id": t.id, "title": t.title, "assigned_to": t.assigned_to}
+ for t in tasks if t.status == "pending"
+ ],
"active_tasks": [
{"id": t.id, "title": t.title, "assigned_to": t.assigned_to, "progress": t.progress}
for t in tasks
@@ -2747,6 +2860,96 @@ class Database:
logger.error(f"Failed to get team stats: {e}")
return {"error": str(e)}
+ async def acquire_subagent_permit(self, root_execution_id: str, permit_id: str, limit: int = 3) -> bool:
+ """Atomically acquire a root-global permit; retries by the owner succeed."""
+ if limit < 1:
+ return False
+ try:
+ async with self.get_session() as session:
+ existing = await session.execute(
+ select(SubagentConcurrencyPermit).where(SubagentConcurrencyPermit.permit_id == permit_id)
+ )
+ permit = existing.scalar_one_or_none()
+ if permit:
+ return permit.root_execution_id == root_execution_id and permit.status == "active"
+
+ await session.execute(text(
+ "INSERT OR IGNORE INTO subagent_concurrency_counters "
+ "(root_execution_id, active_count, updated_at) VALUES (:root, 0, CURRENT_TIMESTAMP)"
+ ), {"root": root_execution_id})
+ claimed = await session.execute(
+ update(SubagentConcurrencyCounter)
+ .where(
+ SubagentConcurrencyCounter.root_execution_id == root_execution_id,
+ SubagentConcurrencyCounter.active_count < limit,
+ )
+ .values(
+ active_count=SubagentConcurrencyCounter.active_count + 1,
+ updated_at=datetime.now(timezone.utc),
+ )
+ )
+ if claimed.rowcount != 1:
+ await session.rollback()
+ return False
+ session.add(SubagentConcurrencyPermit(
+ permit_id=permit_id, root_execution_id=root_execution_id, status="active"
+ ))
+ await session.commit()
+ return True
+ except IntegrityError:
+ # A concurrent retry inserted the same permit. Resolve ownership
+ # from durable state rather than incrementing the counter again.
+ async with self.get_session() as session:
+ result = await session.execute(
+ select(SubagentConcurrencyPermit).where(SubagentConcurrencyPermit.permit_id == permit_id)
+ )
+ permit = result.scalar_one_or_none()
+ return bool(permit and permit.root_execution_id == root_execution_id and permit.status == "active")
+ except Exception as e:
+ logger.error("Failed to acquire subagent permit", root_execution_id=root_execution_id, permit_id=permit_id, error=str(e))
+ return False
+
+ async def release_subagent_permit(self, root_execution_id: str, permit_id: str) -> bool:
+ """Idempotently release a permit and decrement its root counter once."""
+ try:
+ async with self.get_session() as session:
+ released = await session.execute(
+ update(SubagentConcurrencyPermit)
+ .where(
+ SubagentConcurrencyPermit.permit_id == permit_id,
+ SubagentConcurrencyPermit.root_execution_id == root_execution_id,
+ SubagentConcurrencyPermit.status == "active",
+ )
+ .values(status="released", released_at=datetime.now(timezone.utc))
+ )
+ if released.rowcount == 1:
+ await session.execute(
+ update(SubagentConcurrencyCounter)
+ .where(
+ SubagentConcurrencyCounter.root_execution_id == root_execution_id,
+ SubagentConcurrencyCounter.active_count > 0,
+ )
+ .values(
+ active_count=SubagentConcurrencyCounter.active_count - 1,
+ updated_at=datetime.now(timezone.utc),
+ )
+ )
+ await session.commit()
+ return True
+ existing = await session.execute(
+ select(SubagentConcurrencyPermit).where(
+ SubagentConcurrencyPermit.permit_id == permit_id,
+ SubagentConcurrencyPermit.root_execution_id == root_execution_id,
+ )
+ )
+ permit = existing.scalar_one_or_none()
+ already_released = bool(permit and permit.status == "released")
+ await session.rollback()
+ return already_released
+ except Exception as e:
+ logger.error("Failed to release subagent permit", root_execution_id=root_execution_id, permit_id=permit_id, error=str(e))
+ return False
+
# ============================================================================
# Google Connections - Customer Mode OAuth Storage
# ============================================================================
diff --git a/server/models/database.py b/server/models/database.py
index ee0f9736..a62f23d7 100644
--- a/server/models/database.py
+++ b/server/models/database.py
@@ -275,6 +275,8 @@ class UserSettings(SQLModel, table=True):
memory_window_size: int = Field(default=100) # Message pairs in short-term memory (1-100)
compaction_ratio: float = Field(default=0.8) # Fraction of context window triggering compaction (0.05-0.99). Mirrors COMPACTION_RATIO env default.
agent_recursion_limit: int = Field(default=200) # Hard step cap for the agent loop. Mirrors AGENT_RECURSION_LIMIT env default.
+ max_concurrent_subagents: int = Field(default=3)
+ max_delegation_depth: int = Field(default=2)
examples_loaded: bool = Field(default=False) # Track if example workflows were imported
onboarding_completed: bool = Field(default=False) # Track if user completed or skipped onboarding
onboarding_step: int = Field(default=0) # Last completed onboarding step (for resuming)
@@ -440,6 +442,8 @@ class AgentTeam(SQLModel, table=True):
id: str = Field(primary_key=True, max_length=255)
workflow_id: str = Field(index=True, max_length=255)
team_lead_node_id: str = Field(max_length=255)
+ execution_id: Optional[str] = Field(default=None, index=True, max_length=255)
+ root_execution_id: Optional[str] = Field(default=None, index=True, max_length=255)
status: str = Field(default="active", max_length=20) # active, completed, failed, dissolved
config: Dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
created_at: datetime = Field(
@@ -508,6 +512,7 @@ class AgentMessage(SQLModel, table=True):
__tablename__ = "agent_messages"
id: Optional[int] = Field(default=None, primary_key=True)
+ event_id: Optional[str] = Field(default=None, unique=True, index=True, max_length=255)
team_id: str = Field(index=True, max_length=255)
from_agent: str = Field(max_length=255) # node_id
to_agent: Optional[str] = Field(default=None, max_length=255) # None = broadcast
@@ -520,6 +525,34 @@ class AgentMessage(SQLModel, table=True):
)
+class SubagentConcurrencyCounter(SQLModel, table=True):
+ """Durable active-descendant count scoped to one root execution."""
+
+ __tablename__ = "subagent_concurrency_counters"
+
+ root_execution_id: str = Field(primary_key=True, max_length=255)
+ active_count: int = Field(default=0)
+ updated_at: datetime = Field(
+ default_factory=lambda: datetime.now(timezone.utc),
+ sa_column=Column(DateTime(timezone=True), onupdate=func.now()),
+ )
+
+
+class SubagentConcurrencyPermit(SQLModel, table=True):
+ """Idempotency record for a delegation's global concurrency permit."""
+
+ __tablename__ = "subagent_concurrency_permits"
+
+ permit_id: str = Field(primary_key=True, max_length=255)
+ root_execution_id: str = Field(index=True, max_length=255)
+ status: str = Field(default="active", max_length=20)
+ acquired_at: datetime = Field(
+ default_factory=lambda: datetime.now(timezone.utc),
+ sa_column=Column(DateTime(timezone=True), server_default=func.now()),
+ )
+ released_at: Optional[datetime] = Field(default=None)
+
+
class ProxyProviderConfig(SQLModel, table=True):
"""Proxy provider configuration stored in database.
diff --git a/server/nodes/agent/_inline.py b/server/nodes/agent/_inline.py
index 21bb310f..7e135c3f 100644
--- a/server/nodes/agent/_inline.py
+++ b/server/nodes/agent/_inline.py
@@ -99,48 +99,15 @@ async def prepare_agent_call(
teammates = await collect_teammate_connections(node_id, context, database)
if teammates:
tool_data = tool_data or []
- # Walk each teammate's own ``input-tools`` edges so the
- # delegation tool description (built later in
- # ``ai.py:_build_tool_from_node``) lists what each teammate
- # can actually do. Without ``child_tools`` populated, the
- # LLM only sees the generic "ONE-SHOT delegation to X"
- # string and has no signal for which teammate fits a given
- # task -- the orchestrator answers in one turn instead of
- # delegating. Scoped to the team-handle path on purpose;
- # ``input-tools``-connected agents already get this
- # capability injection inside ``edge_walker``.
- all_nodes = context.get("nodes", []) or []
- all_edges = context.get("edges", []) or []
for tm in teammates:
- tm_id = tm["node_id"]
- child_tools = []
- for child_edge in all_edges:
- if child_edge.get("target") != tm_id or child_edge.get("targetHandle") != "input-tools":
- continue
- child_id = child_edge.get("source")
- child_node = next(
- (n for n in all_nodes if n.get("id") == child_id),
- None,
- )
- if not child_node:
- continue
- child_tools.append(
- {
- "node_id": child_id,
- "node_type": child_node.get("type"),
- "label": child_node.get("data", {}).get(
- "label",
- child_node.get("type"),
- ),
- }
- )
tool_data.append(
{
- "node_id": tm_id,
+ "node_id": tm["node_id"],
"node_type": tm["node_type"],
"label": tm["label"],
"parameters": tm.get("parameters", {}),
- "child_tools": child_tools,
+ "child_tools": tm.get("child_tools", []),
+ "delegate_tool_name": tm["delegate_tool_name"],
}
)
logger.info(f"[Teams] Added {len(teammates)} teammates as delegation tools")
diff --git a/server/nodes/tool/agent_builder/__init__.py b/server/nodes/tool/agent_builder/__init__.py
index cf6ca267..d2896739 100644
--- a/server/nodes/tool/agent_builder/__init__.py
+++ b/server/nodes/tool/agent_builder/__init__.py
@@ -1150,7 +1150,10 @@ class AgentBuilderNode(ToolNode):
# Idempotent duplicate check — see add_tool above for rationale.
existing_teammates = _find_wired_types(nodes, edges, caller_id, _TEAMMATES_HANDLE)
- if agent_type in existing_teammates:
+ # Custom aiAgent nodes are intentionally repeatable: their delegation
+ # identity is label/node based. Every other agent type has a stable
+ # type-wide delegate name and is therefore one-per-team.
+ if agent_type != "aiAgent" and agent_type in existing_teammates:
return AgentBuilderOutput(
operation="add_subagent",
summary=(
diff --git a/server/services/agent_team.py b/server/services/agent_team.py
index b13a882c..d8a56741 100644
--- a/server/services/agent_team.py
+++ b/server/services/agent_team.py
@@ -5,6 +5,7 @@ Teams are scoped to specific workflow executions.
"""
import uuid
+import hashlib
from typing import Dict, Any, List, Optional
from core.database import Database
from core.logging import get_logger
@@ -29,7 +30,9 @@ class AgentTeamService:
# -------------------------------------------------------------------------
async def create_team(
- self, team_lead_node_id: str, teammate_node_ids: List[Dict[str, Any]], workflow_id: str, config: Optional[Dict[str, Any]] = None
+ self, team_lead_node_id: str, teammate_node_ids: List[Dict[str, Any]], workflow_id: str, config: Optional[Dict[str, Any]] = None,
+ execution_id: Optional[str] = None, root_execution_id: Optional[str] = None,
+ team_lead_type: str = "orchestrator_agent", team_lead_label: Optional[str] = None,
) -> Optional[Dict[str, Any]]:
"""Create a team with lead and teammates.
@@ -42,18 +45,28 @@ class AgentTeamService:
Returns:
Team dict or None on failure
"""
- team_id = f"team_{uuid.uuid4().hex[:12]}"
+ if execution_id:
+ digest = hashlib.sha256(f"{execution_id}:{team_lead_node_id}".encode()).hexdigest()[:16]
+ team_id = f"team_{digest}"
+ existing = await self.database.get_team(team_id)
+ if existing:
+ return {"team_id": team_id, **existing}
+ else:
+ team_id = f"team_{uuid.uuid4().hex[:12]}"
# Create team
team = await self.database.create_team(
- team_id=team_id, workflow_id=workflow_id, team_lead_node_id=team_lead_node_id, config=config or {"mode": "parallel"}
+ team_id=team_id, workflow_id=workflow_id, team_lead_node_id=team_lead_node_id,
+ config=config or {"mode": "parallel"}, execution_id=execution_id,
+ root_execution_id=root_execution_id or execution_id,
)
if not team:
return None
# Add team lead as member
await self.database.add_team_member(
- team_id=team_id, agent_node_id=team_lead_node_id, agent_type="orchestrator_agent", role="team_lead"
+ team_id=team_id, agent_node_id=team_lead_node_id, agent_type=team_lead_type,
+ agent_label=team_lead_label, role="team_lead"
)
# Add teammates
@@ -64,6 +77,7 @@ class AgentTeamService:
agent_type=teammate.get("node_type", "agent"),
agent_label=teammate.get("label"),
role="teammate",
+ capabilities=teammate.get("capabilities"),
)
# Broadcast team creation
@@ -78,6 +92,21 @@ class AgentTeamService:
logger.info(f"[Teams] Created team {team_id} with {len(teammate_node_ids)} teammates")
return {"team_id": team_id, **team}
+ async def get_or_create_execution_team(
+ self, *, team_lead_node_id: str, teammates: List[Dict[str, Any]], workflow_id: str,
+ execution_id: str, root_execution_id: Optional[str] = None,
+ team_lead_type: str = "orchestrator_agent", team_lead_label: Optional[str] = None,
+ config: Optional[Dict[str, Any]] = None,
+ ) -> Optional[Dict[str, Any]]:
+ """Idempotently create the durable team for a lead execution."""
+ existing = await self.database.find_team(workflow_id, team_lead_node_id, execution_id)
+ if existing:
+ return {"team_id": existing["id"], **existing}
+ return await self.create_team(
+ team_lead_node_id, teammates, workflow_id, config,
+ execution_id, root_execution_id, team_lead_type, team_lead_label,
+ )
+
def get_active_team_for_workflow(self, workflow_id: str) -> Optional[str]:
"""Get the active team ID for a workflow."""
return self._active_teams.get(workflow_id)
@@ -93,8 +122,16 @@ class AgentTeamService:
await self.broadcaster.broadcast_team_event(team_id, "team_dissolved", {"team_id": team_id})
return success
- async def get_team_status(self, team_id: str) -> Dict[str, Any]:
+ async def get_team_status(
+ self, team_id: Optional[str] = None, *, workflow_id: Optional[str] = None,
+ team_lead_node_id: Optional[str] = None, execution_id: Optional[str] = None,
+ ) -> Dict[str, Any]:
"""Get comprehensive team status."""
+ if not team_id and workflow_id and team_lead_node_id:
+ team = await self.database.find_team(workflow_id, team_lead_node_id, execution_id)
+ team_id = team["id"] if team else None
+ if not team_id:
+ return {"error": "Team not found"}
return await self.database.get_team_stats(team_id)
# -------------------------------------------------------------------------
@@ -109,9 +146,10 @@ class AgentTeamService:
description: Optional[str] = None,
priority: int = 3,
depends_on: Optional[List[str]] = None,
+ task_id: Optional[str] = None,
) -> Optional[Dict[str, Any]]:
"""Add a task to the shared task list."""
- task_id = f"task_{uuid.uuid4().hex[:12]}"
+ task_id = task_id or f"task_{uuid.uuid4().hex[:12]}"
task = await self.database.add_team_task(
task_id=task_id,
@@ -123,6 +161,12 @@ class AgentTeamService:
depends_on=depends_on,
)
+ # A completed execution team may receive another delegation later in
+ # the same lead run (legacy fire-and-forget loop). Re-open it before
+ # broadcasting the newly queued task.
+ if task:
+ await self.database.update_team_status(team_id, "active")
+
if task and self.broadcaster:
await self.broadcaster.broadcast_team_event(team_id, "task_added", task)
@@ -188,12 +232,21 @@ class AgentTeamService:
return True
return all(t["status"] in ("completed", "failed", "skipped") for t in tasks)
+ async def acquire_subagent_permit(self, root_execution_id: str, permit_id: str, limit: int = 3) -> bool:
+ """Acquire one cross-process descendant slot for a delegation."""
+ return await self.database.acquire_subagent_permit(root_execution_id, permit_id, limit)
+
+ async def release_subagent_permit(self, root_execution_id: str, permit_id: str) -> bool:
+ """Release a descendant slot; repeated releases are successful no-ops."""
+ return await self.database.release_subagent_permit(root_execution_id, permit_id)
+
# -------------------------------------------------------------------------
# Messaging
# -------------------------------------------------------------------------
async def send_message(
- self, team_id: str, from_agent: str, content: str, to_agent: Optional[str] = None, message_type: str = "direct"
+ self, team_id: str, from_agent: str, content: str, to_agent: Optional[str] = None, message_type: str = "direct",
+ event_id: Optional[str] = None, extra_data: Optional[Dict[str, Any]] = None,
) -> Optional[Dict[str, Any]]:
"""Send a message to a specific agent or broadcast."""
msg = await self.database.add_agent_message(
@@ -202,6 +255,8 @@ class AgentTeamService:
content=content,
message_type=message_type if to_agent else "broadcast",
to_agent=to_agent,
+ event_id=event_id,
+ extra_data=extra_data,
)
if msg and self.broadcaster:
diff --git a/server/services/agent_teams/handlers.py b/server/services/agent_teams/handlers.py
index bfe3e926..e18de468 100644
--- a/server/services/agent_teams/handlers.py
+++ b/server/services/agent_teams/handlers.py
@@ -30,6 +30,10 @@ async def handle_create_team(data: Dict[str, Any], websocket: WebSocket) -> Dict
teammate_node_ids=data.get("teammates", []),
workflow_id=data["workflow_id"],
config=data.get("config"),
+ execution_id=data.get("execution_id"),
+ root_execution_id=data.get("root_execution_id"),
+ team_lead_type=data.get("team_lead_type", "orchestrator_agent"),
+ team_lead_label=data.get("team_lead_label"),
)
return {"team": team} if team else {"success": False, "error": "Failed to create team"}
@@ -69,13 +73,15 @@ async def handle_get_team_status(data: Dict[str, Any], websocket: WebSocket) ->
team_id = data.get("team_id")
- if not team_id and data.get("team_lead_node_id"):
- return {"status": {**empty_status, "message": "No active team yet"}}
-
- if not team_id:
+ if not team_id and not (data.get("workflow_id") and data.get("team_lead_node_id")):
return {"status": {**empty_status, "message": "No team connected"}}
- status = await service.get_team_status(team_id)
+ status = await service.get_team_status(
+ team_id, workflow_id=data.get("workflow_id"),
+ team_lead_node_id=data.get("team_lead_node_id"), execution_id=data.get("execution_id"),
+ )
+ if status.get("error") == "Team not found":
+ status = {**empty_status, "message": "No active team yet"}
return {"status": status}
diff --git a/server/services/ai.py b/server/services/ai.py
index 6dcad852..8577f547 100644
--- a/server/services/ai.py
+++ b/server/services/ai.py
@@ -1841,6 +1841,11 @@ class AIService:
# Stable per-run id so session-keyed tools (browser)
# reuse one instance across the agent loop.
config["execution_id"] = context.get("execution_id")
+ config["root_execution_id"] = context.get("root_execution_id")
+ config["delegation_depth"] = context.get("delegation_depth", 0)
+ config["team_id"] = context.get("team_id")
+ config["max_concurrent_subagents"] = context.get("max_concurrent_subagents", 3)
+ config["max_delegation_depth"] = context.get("max_delegation_depth", 2)
try:
result = await execute_tool(tool_name, tool_args, config)
@@ -2435,6 +2440,11 @@ class AIService:
# Stable per-run id so session-keyed tools (browser)
# reuse one instance across the agent loop.
config["execution_id"] = context.get("execution_id")
+ config["root_execution_id"] = context.get("root_execution_id")
+ config["delegation_depth"] = context.get("delegation_depth", 0)
+ config["team_id"] = context.get("team_id")
+ config["max_concurrent_subagents"] = context.get("max_concurrent_subagents", 3)
+ config["max_delegation_depth"] = context.get("max_delegation_depth", 2)
try:
result = await execute_tool(tool_name, tool_args, config)
@@ -2792,6 +2802,10 @@ class AIService:
connected_services = tool_info.get("connected_services", [])
default_tool_name, default_tool_description = _resolve_default_tool_name_description(node_type)
+ # Team-handle expansion assigns a per-node identity to custom
+ # aiAgent delegates. It intentionally outranks schemas and class
+ # defaults because those are type-wide and would collide.
+ delegated_name = tool_info.get("delegate_tool_name")
# Check database for stored schema (source of truth)
db_schema = await self.database.get_tool_schema(node_id) if node_id else None
@@ -2799,14 +2813,14 @@ class AIService:
if db_schema:
# Use database schema as source of truth
logger.debug(f"[Agent] Using DB schema for tool node {node_id}")
- tool_name = db_schema.get("tool_name", default_tool_name or f"tool_{node_label}")
+ tool_name = delegated_name or db_schema.get("tool_name", default_tool_name or f"tool_{node_label}")
tool_description = db_schema.get("tool_description", default_tool_description or f"Execute {node_label}")
# Use stored connected_services if available (for toolkit nodes)
if db_schema.get("connected_services"):
connected_services = db_schema["connected_services"]
else:
# Fall back to dynamic generation from node params
- tool_name = (
+ tool_name = delegated_name or (
node_params.get("tool_name") or default_tool_name or f"tool_{node_label}".replace(" ", "_").replace("-", "_").lower()
)
tool_description = node_params.get("tool_description") or default_tool_description or f"Execute {node_label} node"
diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.py
index c2c1e85a..31db105e 100644
--- a/server/services/handlers/tools.py
+++ b/server/services/handlers/tools.py
@@ -59,6 +59,12 @@ _active_delegations: Dict[Tuple[str, str, str], str] = {}
# instead of a plain set.
_active_delegated_nodes: Dict[str, int] = {}
+# Legacy (non-Temporal) executions are single-process, so an asyncio
+# semaphore provides the same bounded fan-out contract as AgentWorkflow.
+# Temporal owns its own durable scheduling path. Semaphores are scoped by the
+# root execution and intentionally exclude the root agent itself.
+_delegation_semaphores: Dict[str, asyncio.Semaphore] = {}
+
def is_node_in_active_delegation(node_id: str) -> bool:
"""Return True iff ``node_id`` has at least one in-flight
@@ -374,6 +380,80 @@ async def _execute_delegated_agent(args: Dict[str, Any], config: Dict[str, Any])
# Generate unique task ID
task_id = f"delegated_{node_id}_{uuid.uuid4().hex[:8]}"
+ root_execution_id = str(config.get("root_execution_id") or config.get("execution_id") or workflow_id or parent_node_id)
+ delegation_depth = int(config.get("delegation_depth") or 0)
+ from core.config import Settings as _DelegationSettings
+
+ delegation_settings = _DelegationSettings()
+ maybe_user_settings = database.get_user_settings()
+ user_settings = await maybe_user_settings if hasattr(maybe_user_settings, "__await__") else None
+ max_depth = int(
+ config.get("max_delegation_depth")
+ or (user_settings or {}).get("max_delegation_depth")
+ or delegation_settings.max_delegation_depth
+ )
+ if delegation_depth >= max_depth:
+ return {
+ "success": False,
+ "status": "error",
+ "error": f"Maximum delegation depth {max_depth} exceeded",
+ }
+
+ max_concurrency = max(
+ 1,
+ int(
+ config.get("max_concurrent_subagents")
+ or (user_settings or {}).get("max_concurrent_subagents")
+ or delegation_settings.max_concurrent_subagents
+ ),
+ )
+ semaphore = _delegation_semaphores.setdefault(root_execution_id, asyncio.Semaphore(max_concurrency))
+
+ # Team-handle delegation participates in the durable AgentTeam lifecycle.
+ # Ordinary agent-as-tool edges keep their historical standalone behavior.
+ team_id: Optional[str] = config.get("team_id")
+ is_team_delegation = any(
+ edge.get("source") == node_id
+ and edge.get("target") == parent_node_id
+ and (edge.get("targetHandle") or edge.get("target_handle")) == "input-teammates"
+ for edge in edges
+ )
+ team_service = None
+ if is_team_delegation:
+ from services.agent_team import get_agent_team_service
+ from services.plugin.edge_walker import collect_teammate_connections
+
+ team_service = get_agent_team_service()
+ parent_node = next((item for item in nodes if item.get("id") == parent_node_id), {})
+ teammates = await collect_teammate_connections(
+ parent_node_id,
+ {"nodes": nodes, "edges": edges, "workflow_id": workflow_id},
+ database,
+ )
+ execution_key = str(config.get("execution_id") or root_execution_id)
+ team = await team_service.get_or_create_execution_team(
+ team_lead_node_id=parent_node_id,
+ teammates=teammates,
+ workflow_id=str(workflow_id or "default"),
+ execution_id=execution_key,
+ root_execution_id=root_execution_id,
+ team_lead_type=parent_node.get("type", "orchestrator_agent"),
+ team_lead_label=(parent_node.get("data") or {}).get("label"),
+ config={"mode": "parallel", "max_concurrent_subagents": max_concurrency},
+ )
+ team_id = (team or {}).get("team_id") or (team or {}).get("id")
+ if not team_id:
+ return {"success": False, "status": "error", "error": "Failed to persist agent execution team"}
+ persisted = await team_service.add_task(
+ team_id,
+ title=task_description[:500] or f"Delegation to {node_type}",
+ description=task_context or task_description,
+ created_by=parent_node_id,
+ task_id=task_id,
+ )
+ if not persisted:
+ return {"success": False, "status": "error", "error": "Failed to persist delegated team task"}
+
# Register this delegation to prevent duplicates
_active_delegations[delegation_key] = task_id
@@ -425,6 +505,12 @@ async def _execute_delegated_agent(args: Dict[str, Any], config: Dict[str, Any])
"outputs": {},
"parent_task_id": task_id,
"execution_id": config.get("execution_id"),
+ "root_execution_id": root_execution_id,
+ "parent_node_id": parent_node_id,
+ "delegation_depth": delegation_depth + 1,
+ "team_id": team_id,
+ "team_task_id": task_id if team_id else None,
+ "trace_id": task_id,
}
broadcaster = get_status_broadcaster()
@@ -435,35 +521,78 @@ async def _execute_delegated_agent(args: Dict[str, Any], config: Dict[str, Any])
f"[Delegated Agent] Context: {len(nodes)} nodes, {len(edges)} edges, " f"edge_targets={set(e.get('target') for e in edges)}"
)
+ async def finalize_team_task(*, result_data: Optional[Dict[str, Any]] = None, error: Optional[str] = None) -> None:
+ if not team_service or not team_id:
+ return
+ if error is not None:
+ await team_service.fail_task(team_id, task_id, error)
+ event_type, message_type, content = "failed", "task_failed", error
+ else:
+ await team_service.complete_task(team_id, task_id, result_data)
+ event_type, message_type, content = "completed", "task_complete", str((result_data or {}).get("result", ""))
+ await team_service.send_message(
+ team_id,
+ from_agent=node_id,
+ to_agent=parent_node_id,
+ content=content,
+ message_type=message_type,
+ event_id=f"{task_id}:{event_type}",
+ extra_data={"task_id": task_id, "root_execution_id": root_execution_id, **(result_data or {})},
+ )
+ if await team_service.is_team_done(team_id):
+ tasks = await team_service.database.get_team_tasks(team_id)
+ final_status = "failed" if any(item.get("status") == "failed" for item in tasks) else "completed"
+ await team_service.database.update_team_status(team_id, final_status)
+
# Define the background coroutine
async def run_child_agent():
+ durable_permit_acquired = False
try:
+ async with semaphore:
+ if team_service and team_id:
+ while not await team_service.acquire_subagent_permit(
+ root_execution_id, task_id, max_concurrency
+ ):
+ await asyncio.sleep(0.25)
+ durable_permit_acquired = True
+ claimed = await team_service.claim_task(team_id, task_id, node_id)
+ if not claimed:
+ raise RuntimeError("Delegated team task could not be claimed")
+ await team_service.send_message(
+ team_id,
+ from_agent=parent_node_id,
+ to_agent=node_id,
+ content=task_description,
+ message_type="task_assignment",
+ event_id=f"{task_id}:assigned",
+ extra_data={"task_id": task_id, "root_execution_id": root_execution_id},
+ )
# Broadcast that child agent is starting
- await broadcaster.update_node_status(
- node_id,
- "executing",
- {"phase": "delegated_task", "task_id": task_id, "message": f"Working on: {task_description[:100]}..."},
- workflow_id=workflow_id,
- )
+ await broadcaster.update_node_status(
+ node_id,
+ "executing",
+ {"phase": "delegated_task", "task_id": task_id, "message": f"Working on: {task_description[:100]}..."},
+ workflow_id=workflow_id,
+ )
# Execute the child agent via its own plugin class.
# Wave 11.E.3: replaces the legacy handle_ai_agent /
# handle_chat_agent imports — every agent type already owns
# an @Operation method that wraps prepare_agent_call +
# AIService dispatch, so we just go through BaseNode.execute.
- from services.node_registry import get_node_class
- from services.plugin import NodeContext
-
- plugin_cls = get_node_class(node_type)
- if plugin_cls is None:
- raise RuntimeError(f"Unknown delegated agent type: {node_type}")
- instance = plugin_cls()
- child_ctx = NodeContext.from_legacy(
- node_id=node_id,
- node_type=node_type,
- context=child_context,
- )
- result = await instance.execute(node_id, child_params, child_ctx)
+ from services.node_registry import get_node_class
+ from services.plugin import NodeContext
+
+ plugin_cls = get_node_class(node_type)
+ if plugin_cls is None:
+ raise RuntimeError(f"Unknown delegated agent type: {node_type}")
+ instance = plugin_cls()
+ child_ctx = NodeContext.from_legacy(
+ node_id=node_id,
+ node_type=node_type,
+ context=child_context,
+ )
+ result = await instance.execute(node_id, child_params, child_ctx)
logger.info(f"[Delegated Agent] Task {task_id} completed: success={result.get('success')}")
@@ -514,6 +643,8 @@ async def _execute_delegated_agent(args: Dict[str, Any], config: Dict[str, Any])
error=error_msg,
)
+ await finalize_team_task(error=error_msg)
+
return result
# Success case - extract response properly
@@ -568,6 +699,8 @@ async def _execute_delegated_agent(args: Dict[str, Any], config: Dict[str, Any])
result=response_text,
)
+ await finalize_team_task(result_data={"result": response_text})
+
return result
except Exception as e:
@@ -613,9 +746,19 @@ async def _execute_delegated_agent(args: Dict[str, Any], config: Dict[str, Any])
error=str(e),
)
+ await finalize_team_task(error=str(e))
+
return {"success": False, "error": str(e)}
finally:
+ if durable_permit_acquired and team_service:
+ released = await team_service.release_subagent_permit(root_execution_id, task_id)
+ if not released:
+ logger.error(
+ "[Delegated Agent] Failed to release durable permit %s for root %s",
+ task_id,
+ root_execution_id,
+ )
# Cleanup task reference
_delegated_tasks.pop(task_id, None)
# Cleanup delegation tracking (allows re-delegation after completion)
diff --git a/server/services/plugin/edge_walker.py b/server/services/plugin/edge_walker.py
index 5264d5c1..eefd6fec 100644
--- a/server/services/plugin/edge_walker.py
+++ b/server/services/plugin/edge_walker.py
@@ -33,6 +33,9 @@ shims to call here directly.
from __future__ import annotations
+import hashlib
+import re
+from collections import Counter
from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, List, Optional, Tuple
from constants import AI_AGENT_TYPES, ANDROID_SERVICE_NODE_TYPES
@@ -43,6 +46,61 @@ if TYPE_CHECKING:
logger = get_logger(__name__)
+TEAM_LEAD_TYPES = frozenset({"orchestrator_agent", "ai_employee"})
+TEAMMATE_HANDLE = "input-teammates"
+
+
+def edge_target_handle(edge: Dict[str, Any]) -> Optional[str]:
+ """Return the canonical ReactFlow handle, accepting legacy imports."""
+ return edge.get("targetHandle") or edge.get("target_handle")
+
+
+def _delegate_slug(value: Any) -> str:
+ slug = re.sub(r"[^a-zA-Z0-9]+", "_", str(value or "").strip()).strip("_").lower()
+ return slug or "ai_agent"
+
+
+def build_teammate_descriptors(node_id: str, context: Dict[str, Any]) -> List[Dict[str, Any]]:
+ """Build deterministic, LLM-visible identities for a lead's teammates.
+
+ Specialized agents retain their stable type-derived name. Custom
+ ``aiAgent`` nodes are label-addressable and receive a node-id suffix when
+ their label is empty or collides on the same lead surface.
+ """
+ nodes = context.get("nodes", []) or []
+ edges = context.get("edges", []) or []
+ node_by_id = {n.get("id"): n for n in nodes if n.get("id")}
+ candidates: List[Dict[str, Any]] = []
+ for edge in edges:
+ if edge.get("target") != node_id or edge_target_handle(edge) != TEAMMATE_HANDLE:
+ continue
+ source = node_by_id.get(edge.get("source"))
+ if not source or source.get("type") not in AI_AGENT_TYPES:
+ continue
+ node_type = source.get("type", "")
+ raw_label = (source.get("data") or {}).get("label")
+ label = str(raw_label or node_type)
+ candidates.append({
+ "node_id": source["id"],
+ "node_type": node_type,
+ "label": label,
+ "_raw_label": raw_label,
+ "_slug": _delegate_slug(raw_label),
+ })
+
+ custom_counts = Counter(c["_slug"] for c in candidates if c["node_type"] == "aiAgent" and c["_raw_label"])
+ for item in candidates:
+ if item["node_type"] == "aiAgent":
+ needs_suffix = not item["_raw_label"] or custom_counts[item["_slug"]] > 1
+ stable_id = hashlib.sha1(str(item["node_id"]).encode("utf-8")).hexdigest()[:8]
+ suffix = f"_{stable_id}" if needs_suffix else ""
+ item["delegate_tool_name"] = f"delegate_to_{item['_slug']}{suffix}"
+ else:
+ item["delegate_tool_name"] = f"delegate_to_{item['node_type']}"
+ item.pop("_raw_label", None)
+ item.pop("_slug", None)
+ return candidates
+
# ---- Master-Skill expander callback registry ----------------------------
@@ -414,30 +472,26 @@ async def collect_teammate_connections(
Used by ``orchestrator_agent`` / ``ai_employee``.
"""
- nodes = context.get("nodes", [])
- edges = context.get("edges", [])
teammates: List[Dict[str, Any]] = []
-
- for edge in edges:
- if edge.get("target") != node_id or edge.get("targetHandle") != "input-teammates":
- continue
- source_id = edge.get("source")
- source_node = next((n for n in nodes if n.get("id") == source_id), None)
- if not source_node:
- continue
- node_type = source_node.get("type", "")
- if node_type not in AI_AGENT_TYPES:
- continue
+ descriptors = build_teammate_descriptors(node_id, context)
+ nodes = context.get("nodes", []) or []
+ edges = context.get("edges", []) or []
+ for descriptor in descriptors:
+ source_id = descriptor["node_id"]
params = await database.get_node_parameters(source_id) or {}
- teammates.append(
- {
- "node_id": source_id,
- "node_type": node_type,
- "label": source_node.get("data", {}).get("label", node_type),
- "parameters": params,
- }
- )
- logger.debug(f"[Teams] Found teammate: {node_type} ({source_id})")
+ child_tools: List[Dict[str, Any]] = []
+ for edge in edges:
+ if edge.get("target") != source_id or edge_target_handle(edge) != "input-tools":
+ continue
+ child = next((n for n in nodes if n.get("id") == edge.get("source")), None)
+ if child:
+ child_tools.append({
+ "node_id": child.get("id"),
+ "node_type": child.get("type"),
+ "label": (child.get("data") or {}).get("label", child.get("type")),
+ })
+ teammates.append({**descriptor, "parameters": params, "child_tools": child_tools})
+ logger.debug(f"[Teams] Found teammate: {descriptor['node_type']} ({source_id})")
return teammates
diff --git a/server/services/temporal/agent_activities.py b/server/services/temporal/agent_activities.py
index 41713562..b9747040 100644
--- a/server/services/temporal/agent_activities.py
+++ b/server/services/temporal/agent_activities.py
@@ -34,6 +34,7 @@ References:
from __future__ import annotations
+import asyncio
import logging
from typing import Any, Dict, List, Optional
@@ -498,7 +499,10 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:
from core.container import container
from services.ai import _resolve_max_tokens, _resolve_temperature
from services.ai import ThinkingConfig, get_default_model_async, is_model_valid_for_provider
- from services.plugin.edge_walker import collect_agent_connections
+ from services.plugin.edge_walker import (
+ collect_agent_connections,
+ collect_teammate_connections,
+ )
node_id = context["node_id"]
node_type = context["node_type"]
@@ -613,6 +617,70 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:
log_prefix=f"[AgentWorkflow:{node_type}]",
)
+ # Team-handle edges are configuration edges and are intentionally not
+ # returned by collect_agent_connections. Expand them here before tools
+ # are built, mirroring the legacy inline agent path. Without this step
+ # Temporal removes teammates from graph scheduling but never exposes a
+ # delegate_to_* function to the lead LLM.
+ execution_team_id: Optional[str] = context.get("team_id")
+ owns_execution_team = False
+ if node_type in {"orchestrator_agent", "ai_employee"}:
+ teammates = await collect_teammate_connections(
+ node_id, walk_context, database
+ )
+ all_nodes = walk_context["nodes"]
+ all_edges = walk_context["edges"]
+ for teammate in teammates:
+ teammate_id = teammate["node_id"]
+ child_tools: List[Dict[str, Any]] = []
+ for edge in all_edges:
+ if (
+ edge.get("target") != teammate_id
+ or edge.get("targetHandle") != "input-tools"
+ ):
+ continue
+ child_id = edge.get("source")
+ child = next(
+ (candidate for candidate in all_nodes if candidate.get("id") == child_id),
+ None,
+ )
+ if child:
+ child_tools.append(
+ {
+ "node_id": child_id,
+ "node_type": child.get("type", ""),
+ "label": child.get("data", {}).get("label")
+ or child.get("type", ""),
+ }
+ )
+ entry = {
+ **teammate,
+ "child_tools": child_tools,
+ }
+ tool_data = [*(tool_data or []), entry]
+ if teammates and workflow_id:
+ from services.agent_team import get_agent_team_service
+
+ execution_id = str(context.get("execution_id") or "")
+ root_execution_id = str(
+ context.get("root_execution_id") or execution_id
+ )
+ if execution_id:
+ team = await get_agent_team_service().get_or_create_execution_team(
+ team_lead_node_id=node_id,
+ teammates=teammates,
+ workflow_id=workflow_id,
+ execution_id=execution_id,
+ root_execution_id=root_execution_id,
+ team_lead_type=node_type,
+ team_lead_label=parameters.get("label") or node_type,
+ config={"mode": "parallel"},
+ )
+ if not team:
+ raise RuntimeError("Failed to persist agent execution team")
+ execution_team_id = team.get("team_id") or team.get("id")
+ owns_execution_team = True
+
# ---- Skill prompt injection ----------------------------------------
from services.ai import _build_skill_system_prompt
@@ -675,6 +743,21 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:
}
)
+ if any(tool["name"].startswith("delegate_to_") for tool in tools_payload):
+ delegates = "\n".join(
+ f"- {tool['name']}: {(tool.get('tool_info') or {}).get('label', tool['node_type'])}"
+ for tool in tools_payload
+ if tool["name"].startswith("delegate_to_")
+ )
+ system_message = (
+ f"{system_message}\n\n"
+ "You lead a team of independent agents. Delegate a bounded mission "
+ "when a connected agent's capabilities fit the work. Delegations in "
+ "the same response may run in parallel. Do not delegate the same "
+ "mission twice. After results return, synthesize them into one answer.\n"
+ f"Available delegates:\n{delegates}"
+ )
+
# ---- Compaction threshold ------------------------------------------
# Model-aware threshold (50% of context window per agent.compaction.ratio
# in llm_defaults.json). Reuse the existing CompactionService helper.
@@ -712,6 +795,11 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:
# cap. Per-user override beats env Settings.
auto_rebind_tools = True
settings_recursion_limit: Optional[int] = None
+ from core.config import Settings as _DelegationSettings
+
+ delegation_settings = _DelegationSettings()
+ max_concurrent_subagents = int(delegation_settings.max_concurrent_subagents)
+ max_delegation_depth = int(delegation_settings.max_delegation_depth)
try:
user_settings = await database.get_user_settings()
if user_settings is not None:
@@ -721,6 +809,12 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:
raw_limit = user_settings.get("agent_recursion_limit")
if isinstance(raw_limit, int) and raw_limit > 0:
settings_recursion_limit = raw_limit
+ raw_concurrency = user_settings.get("max_concurrent_subagents")
+ if isinstance(raw_concurrency, int) and raw_concurrency > 0:
+ max_concurrent_subagents = raw_concurrency
+ raw_depth = user_settings.get("max_delegation_depth")
+ if isinstance(raw_depth, int) and raw_depth > 0:
+ max_delegation_depth = min(2, raw_depth)
except Exception as exc: # noqa: BLE001 — defensive read
activity.logger.debug(f"user_settings read failed: {exc}")
@@ -758,6 +852,15 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:
"thinking_config": thinking_config_dict,
"compaction_threshold": compaction_threshold,
"auto_rebind_tools": auto_rebind_tools,
+ "max_concurrent_subagents": max_concurrent_subagents,
+ "max_delegation_depth": max_delegation_depth,
+ "team_id": execution_team_id,
+ "owns_execution_team": owns_execution_team,
+ "root_execution_id": str(
+ context.get("root_execution_id")
+ or context.get("execution_id")
+ or ""
+ ),
}
@@ -812,9 +915,10 @@ async def refresh_agent_tools(payload: Dict[str, Any]) -> Dict[str, Any]:
# spawnable plugins — twitterSearch / googleGmail / pythonExecutor
# / fileRead / etc.). Exclude chat-model plugins even when
# usable_as_tool=True.
+ is_agent_delegate = kind == "agent"
is_tool = kind == "tool"
is_dual_purpose = bool(getattr(cls, "usable_as_tool", False)) and kind != "model"
- if not (is_tool or is_dual_purpose):
+ if not (is_tool or is_dual_purpose or is_agent_delegate):
continue
tool_info: Dict[str, Any] = {
"node_id": op.get("minted_id") or op.get("client_ref") or f"new_{node_type}",
@@ -853,6 +957,190 @@ async def refresh_agent_tools(payload: Dict[str, Any]) -> Dict[str, Any]:
return {"tools": new_tools_payload}
[email protected](name="agent.begin_delegation.v1")
+async def begin_agent_delegation(payload: Dict[str, Any]) -> Dict[str, Any]:
+ """Idempotently persist and claim a delegation before child startup."""
+ from services.agent_team import get_agent_team_service
+
+ team_id = str(payload.get("team_id") or "")
+ task_id = str(payload.get("team_task_id") or "")
+ child_id = str(payload.get("child_agent_node_id") or "")
+ parent_id = str(payload.get("parent_agent_node_id") or "")
+ mission = str(payload.get("task") or "")
+ if not all((team_id, task_id, child_id, parent_id, mission)):
+ raise ValueError("Incomplete durable delegation payload")
+
+ service = get_agent_team_service()
+ tasks = await service.database.get_team_tasks(team_id)
+ task = next((item for item in tasks if item.get("id") == task_id), None)
+ if task is None:
+ task = await service.add_task(
+ team_id, title=mission[:200], description=mission,
+ created_by=parent_id, task_id=task_id,
+ )
+ if not task:
+ raise RuntimeError("Failed to persist delegated team task")
+
+ if str(task.get("status") or "") in {"pending", "queued", ""}:
+ claimed = await service.claim_task(team_id, task_id, child_id)
+ if not claimed:
+ tasks = await service.database.get_team_tasks(team_id)
+ task = next((item for item in tasks if item.get("id") == task_id), None)
+ if not task or task.get("assigned_to") != child_id:
+ raise RuntimeError("Failed to claim delegated team task")
+ elif task.get("assigned_to") and task.get("assigned_to") != child_id:
+ raise RuntimeError("Delegated team task is claimed by another agent")
+
+ message = await service.send_message(
+ team_id, parent_id, f"Assigned task to {child_id}: {mission}",
+ to_agent=child_id, message_type="assignment",
+ event_id=str(payload.get("assignment_event_id") or f"{task_id}:assigned"),
+ extra_data={
+ "status": "started", "task_id": task_id,
+ "root_execution_id": payload.get("root_execution_id"),
+ "delegation_depth": payload.get("delegation_depth"),
+ "trace_id": payload.get("trace_id"),
+ },
+ )
+ if not message:
+ raise RuntimeError("Failed to persist delegation assignment event")
+ return {"team_id": team_id, "team_task_id": task_id, "claimed": True}
+
+
[email protected](name="agent.queue_delegation.v1")
+async def queue_agent_delegation(payload: Dict[str, Any]) -> Dict[str, Any]:
+ """Create a pending task before it waits for a root-wide permit."""
+ from services.agent_team import get_agent_team_service
+
+ team_id = str(payload.get("team_id") or "")
+ task_id = str(payload.get("team_task_id") or "")
+ parent_id = str(payload.get("parent_agent_node_id") or "")
+ child_id = str(payload.get("child_agent_node_id") or "")
+ mission = str(payload.get("task") or "")
+ if not all((team_id, task_id, parent_id, child_id, mission)):
+ raise ValueError("Incomplete queued delegation payload")
+ service = get_agent_team_service()
+ tasks = await service.database.get_team_tasks(team_id)
+ task = next((item for item in tasks if item.get("id") == task_id), None)
+ if task is None:
+ task = await service.add_task(
+ team_id, title=mission[:200], description=mission,
+ created_by=parent_id, task_id=task_id,
+ )
+ if not task:
+ raise RuntimeError("Failed to persist queued delegation")
+ message = await service.send_message(
+ team_id, parent_id, f"Queued task for {child_id}: {mission}",
+ to_agent=child_id, message_type="assignment",
+ event_id=str(payload.get("queued_event_id") or f"{task_id}:queued"),
+ extra_data={"status": "queued", "task_id": task_id},
+ )
+ if not message:
+ raise RuntimeError("Failed to persist delegation queue event")
+ return {"team_id": team_id, "team_task_id": task_id, "status": "pending"}
+
+
[email protected](name="agent.acquire_subagent_permit.v1")
+async def acquire_subagent_permit(payload: Dict[str, Any]) -> Dict[str, Any]:
+ """Poll the durable root coordinator until this delegation is admitted."""
+ from services.agent_team import get_agent_team_service
+
+ root_id = str(payload.get("root_execution_id") or "")
+ permit_id = str(payload.get("permit_id") or "")
+ limit = max(1, int(payload.get("limit") or 3))
+ if not root_id or not permit_id:
+ raise ValueError("root_execution_id and permit_id are required")
+ service = get_agent_team_service()
+ while True:
+ if await service.acquire_subagent_permit(root_id, permit_id, limit):
+ return {"root_execution_id": root_id, "permit_id": permit_id, "acquired": True}
+ activity.heartbeat({"root_execution_id": root_id, "permit_id": permit_id, "status": "queued"})
+ await asyncio.sleep(1)
+
+
[email protected](name="agent.release_subagent_permit.v1")
+async def release_subagent_permit(payload: Dict[str, Any]) -> Dict[str, Any]:
+ """Idempotently release a durable root-wide concurrency permit."""
+ from services.agent_team import get_agent_team_service
+
+ root_id = str(payload.get("root_execution_id") or "")
+ permit_id = str(payload.get("permit_id") or "")
+ if not root_id or not permit_id:
+ raise ValueError("root_execution_id and permit_id are required")
+ released = await get_agent_team_service().release_subagent_permit(root_id, permit_id)
+ if not released:
+ raise RuntimeError("Failed to release subagent permit")
+ return {"root_execution_id": root_id, "permit_id": permit_id, "released": True}
+
+
[email protected](name="agent.finish_delegation.v1")
+async def finish_agent_delegation(payload: Dict[str, Any]) -> Dict[str, Any]:
+ """Idempotently persist a delegated child's terminal result."""
+ from services.agent_team import get_agent_team_service
+
+ team_id = str(payload.get("team_id") or "")
+ task_id = str(payload.get("team_task_id") or "")
+ child_id = str(payload.get("child_agent_node_id") or "")
+ parent_id = str(payload.get("parent_agent_node_id") or "")
+ if not all((team_id, task_id, child_id, parent_id)):
+ raise ValueError("Incomplete delegation completion payload")
+ service = get_agent_team_service()
+ tasks = await service.database.get_team_tasks(team_id)
+ task = next((item for item in tasks if item.get("id") == task_id), None)
+ if task is None:
+ raise RuntimeError("Delegated team task does not exist")
+
+ succeeded = bool(payload.get("success"))
+ target_status = "completed" if succeeded else "failed"
+ if task.get("status") not in {"completed", "failed", "skipped"}:
+ if succeeded:
+ ok = await service.complete_task(team_id, task_id, payload.get("result") or {})
+ else:
+ ok = await service.fail_task(
+ team_id, task_id, str(payload.get("error") or "Delegated agent failed")
+ )
+ if not ok:
+ raise RuntimeError(f"Failed to mark delegated task {target_status}")
+
+ error = str(payload.get("error") or "Delegated agent failed")
+ content = f"Task {task_id} completed" if succeeded else f"Task {task_id} failed: {error}"
+ message = await service.send_message(
+ team_id, child_id, content, to_agent=parent_id,
+ message_type="result" if succeeded else "error",
+ event_id=str(payload.get("terminal_event_id") or f"{task_id}:{target_status}"),
+ extra_data={
+ "status": target_status, "task_id": task_id,
+ "root_execution_id": payload.get("root_execution_id"),
+ "trace_id": payload.get("trace_id"),
+ },
+ )
+ if not message:
+ raise RuntimeError("Failed to persist delegation terminal event")
+ return {"team_id": team_id, "team_task_id": task_id, "status": target_status}
+
+
[email protected](name="agent.finalize_team.v1")
+async def finalize_agent_team(payload: Dict[str, Any]) -> Dict[str, Any]:
+ """Finalize a lead's team after all delegated tasks become terminal."""
+ from services.agent_team import get_agent_team_service
+
+ team_id = str(payload.get("team_id") or "")
+ if not team_id:
+ raise ValueError("team_id is required")
+ service = get_agent_team_service()
+ tasks = await service.database.get_team_tasks(team_id)
+ if any(task.get("status") not in {"completed", "failed", "skipped"} for task in tasks):
+ return {"team_id": team_id, "status": "active"}
+ status = "failed" if any(task.get("status") == "failed" for task in tasks) else "completed"
+ if not await service.database.update_team_status(team_id, status):
+ raise RuntimeError(f"Failed to finalize team as {status}")
+ if service.broadcaster:
+ await service.broadcaster.broadcast_team_event(
+ team_id, f"team_{status}", {"team_id": team_id, "status": status}
+ )
+ return {"team_id": team_id, "status": status}
+
+
def collect_agent_activities() -> List[Any]:
"""Return the F4.B agent activities for worker registration.
@@ -870,4 +1158,10 @@ def collect_agent_activities() -> List[Any]:
broadcast_agent_progress,
store_agent_output,
refresh_agent_tools,
+ begin_agent_delegation,
+ queue_agent_delegation,
+ acquire_subagent_permit,
+ release_subagent_permit,
+ finish_agent_delegation,
+ finalize_agent_team,
]
diff --git a/server/services/temporal/agent_workflow.py b/server/services/temporal/agent_workflow.py
index e3ca2c34..0c03ab64 100644
--- a/server/services/temporal/agent_workflow.py
+++ b/server/services/temporal/agent_workflow.py
@@ -478,6 +478,15 @@ class AgentWorkflow:
if kind == "final":
final_content = step_result.get("content", "")
await self._persist_turn(payload, human_text=user_prompt, assistant_text=final_content)
+ team_id = str(payload.get("team_id") or "")
+ if team_id and payload.get("owns_execution_team"):
+ await workflow.execute_activity(
+ "agent.finalize_team.v1",
+ args=[{"team_id": team_id}],
+ activity_id="finalize-agent-team",
+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,
+ retry_policy=AGENT_ACTIVITY_RETRY,
+ )
break
if kind != "tool_calls":
@@ -488,6 +497,210 @@ class AgentWorkflow:
calls = step_result.get("calls") or []
workflow.logger.info(f"AgentWorkflow scheduling {len(calls)} tool call(s)")
+ # Start delegation children before awaiting their results. The
+ # previous per-call execute_child_workflow loop serialized an
+ # entire team. Keep a bounded sliding window so at most three
+ # descendants from this turn are active, while tool messages are
+ # still appended in the model's original call order.
+ delegation_depth = int(context.get("delegation_depth") or 0)
+ max_delegation_depth = min(
+ 2, int(payload.get("max_delegation_depth") or 2)
+ )
+ max_concurrent_subagents = max(
+ 1, int(payload.get("max_concurrent_subagents") or 3)
+ )
+ root_execution_id = str(
+ payload.get("root_execution_id")
+ or context.get("root_execution_id")
+ or execution_id
+ )
+ delegation_call_indices = [
+ index
+ for index, candidate in enumerate(calls)
+ if str(candidate.get("name", "")).startswith("delegate_to_")
+ and (tool_index.get(candidate.get("name", "")) or {}).get("node_type")
+ in AGENT_WORKFLOW_TYPES
+ and (
+ str((candidate.get("args") or {}).get("task", "") or "")
+ or str((candidate.get("args") or {}).get("context", "") or "")
+ )
+ and delegation_depth < max_delegation_depth
+ ]
+ delegation_handles: Dict[int, Any] = {}
+ delegation_permits: Dict[int, str] = {}
+ yielded_own_permit = False
+
+ # A child that waits for grandchildren must not retain a slot,
+ # otherwise N admitted children can all block forever trying to
+ # acquire the N+1th permit. Yield while orchestrating descendants
+ # and reacquire before resuming this agent's next LLM turn.
+ own_permit_id = str(context.get("team_task_id") or "")
+ if delegation_call_indices and own_permit_id:
+ await workflow.execute_activity(
+ "agent.release_subagent_permit.v1",
+ args=[{
+ "root_execution_id": root_execution_id,
+ "permit_id": own_permit_id,
+ }],
+ activity_id=f"yield-own-permit-{iteration + 1}",
+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,
+ retry_policy=AGENT_ACTIVITY_RETRY,
+ )
+ yielded_own_permit = True
+
+ async def _start_delegation(call_index: int) -> None:
+ candidate = calls[call_index]
+ candidate_tool = tool_index[candidate.get("name", "")]
+ candidate_args = candidate.get("args") or {}
+ task = str(candidate_args.get("task", "") or "")
+ task_context = str(candidate_args.get("context", "") or "")
+ call_metadata = (
+ _tool_call_metadata(
+ agent_node_id=agent_node_id,
+ iteration=iteration,
+ call_index=call_index,
+ call=candidate,
+ )
+ if use_tool_call_identity_v2
+ else {}
+ )
+ child_context = {
+ "node_id": candidate_tool["tool_node_id"],
+ "node_type": candidate_tool["node_type"],
+ "node_data": {
+ **(candidate_tool.get("parameters") or {}),
+ "system_message": task,
+ "prompt": task_context or task,
+ },
+ "inputs": {},
+ "workflow_id": payload.get("workflow_id"),
+ "session_id": payload.get("session_id", "default"),
+ "execution_id": execution_id,
+ "root_execution_id": root_execution_id,
+ "parent_node_id": agent_node_id,
+ "delegation_depth": delegation_depth + 1,
+ "team_id": payload.get("team_id") or context.get("team_id"),
+ "team_task_id": (
+ f"task-{root_execution_id}-{agent_node_id}-"
+ f"{iteration + 1}-{call_index + 1}"
+ ),
+ "trace_id": str(candidate.get("id", "") or ""),
+ "nodes": context.get("nodes") or [],
+ "edges": context.get("edges") or [],
+ "invocation": {"task": task, "context": task_context},
+ **call_metadata,
+ }
+ team_id = str(child_context.get("team_id") or "")
+ if team_id:
+ permit_id = child_context["team_task_id"]
+ lifecycle_payload = {
+ "team_id": team_id,
+ "team_task_id": child_context["team_task_id"],
+ "parent_agent_node_id": agent_node_id,
+ "child_agent_node_id": candidate_tool["tool_node_id"],
+ "task": task,
+ "root_execution_id": root_execution_id,
+ "delegation_depth": delegation_depth + 1,
+ "trace_id": child_context["trace_id"],
+ "assignment_event_id": (
+ f"{child_context['team_task_id']}:assigned"
+ ),
+ }
+ await workflow.execute_activity(
+ "agent.queue_delegation.v1",
+ args=[{
+ **lifecycle_payload,
+ "queued_event_id": (
+ f"{child_context['team_task_id']}:queued"
+ ),
+ }],
+ activity_id=(
+ f"queue-delegation-{iteration + 1}-{call_index + 1}"
+ ),
+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,
+ retry_policy=AGENT_ACTIVITY_RETRY,
+ )
+ await workflow.execute_activity(
+ "agent.acquire_subagent_permit.v1",
+ args=[{
+ "root_execution_id": root_execution_id,
+ "permit_id": permit_id,
+ "limit": max_concurrent_subagents,
+ }],
+ activity_id=(
+ f"acquire-permit-{iteration + 1}-{call_index + 1}"
+ ),
+ start_to_close_timeout=timedelta(hours=1),
+ heartbeat_timeout=timedelta(seconds=10),
+ retry_policy=AGENT_ACTIVITY_RETRY,
+ )
+ delegation_permits[call_index] = permit_id
+ # Claim only after admission. Persistence failure still
+ # prevents child startup and the task remains pending
+ # while the coordinator queues it.
+ try:
+ await workflow.execute_activity(
+ "agent.begin_delegation.v1",
+ args=[lifecycle_payload],
+ activity_id=(
+ f"begin-delegation-{iteration + 1}-{call_index + 1}"
+ ),
+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,
+ retry_policy=AGENT_ACTIVITY_RETRY,
+ )
+ except BaseException:
+ await workflow.execute_activity(
+ "agent.release_subagent_permit.v1",
+ args=[{
+ "root_execution_id": root_execution_id,
+ "permit_id": permit_id,
+ }],
+ activity_id=(
+ f"release-permit-{iteration + 1}-{call_index + 1}"
+ ),
+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,
+ retry_policy=AGENT_ACTIVITY_RETRY,
+ )
+ raise
+ child_id = (
+ _delegation_child_id_v2(
+ workflow.info().workflow_id,
+ candidate_tool["tool_node_id"],
+ iteration,
+ call_index,
+ )
+ if use_tool_call_identity_v2
+ else f"{workflow.info().workflow_id}-delegate-{candidate_tool['tool_node_id']}-{iteration}"
+ )
+ try:
+ delegation_handles[call_index] = await workflow.start_child_workflow(
+ "AgentWorkflow",
+ args=[child_context],
+ id=child_id,
+ execution_timeout=timedelta(hours=1),
+ run_timeout=timedelta(hours=1),
+ )
+ except BaseException:
+ if team_id and call_index in delegation_permits:
+ await workflow.execute_activity(
+ "agent.release_subagent_permit.v1",
+ args=[{
+ "root_execution_id": root_execution_id,
+ "permit_id": delegation_permits[call_index],
+ }],
+ activity_id=(
+ f"release-permit-{iteration + 1}-{call_index + 1}"
+ ),
+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,
+ retry_policy=AGENT_ACTIVITY_RETRY,
+ )
+ raise
+
+ next_delegation_to_start = 0
+ for delegation_index in delegation_call_indices[:max_concurrent_subagents]:
+ await _start_delegation(delegation_index)
+ next_delegation_to_start += 1
+
for call_index, call in enumerate(calls):
tool_info = tool_index.get(call.get("name", ""))
if tool_info is None:
@@ -554,6 +767,21 @@ class AgentWorkflow:
}
)
continue
+ if delegation_depth >= max_delegation_depth:
+ messages.append(
+ {
+ "type": "tool",
+ "data": {
+ "content": (
+ '{"error": "Maximum delegation depth '
+ f'{max_delegation_depth} exceeded."}}'
+ ),
+ "tool_call_id": call.get("id", ""),
+ "name": tool_name,
+ },
+ }
+ )
+ continue
tool_node_data = {
**(tool_info.get("parameters") or {}),
# Consumed only by the activity-dispatch fallback
@@ -622,31 +850,57 @@ class AgentWorkflow:
try:
if is_delegation and tool_info["node_type"] in AGENT_WORKFLOW_TYPES:
- child_context = {
- **tool_payload,
- "parent_node_id": agent_node_id,
- "invocation": {
- "task": task_description,
- "context": task_context,
- },
- }
- delegation_child_id = (
- _delegation_child_id_v2(
- workflow.info().workflow_id,
- tool_info["tool_node_id"],
- iteration,
- call_index,
+ handle = delegation_handles[call_index]
+ try:
+ tool_result = await handle
+ finally:
+ permit_id = delegation_permits.get(call_index)
+ if permit_id:
+ await workflow.execute_activity(
+ "agent.release_subagent_permit.v1",
+ args=[{
+ "root_execution_id": root_execution_id,
+ "permit_id": permit_id,
+ }],
+ activity_id=(
+ f"release-permit-{iteration + 1}-{call_index + 1}"
+ ),
+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,
+ retry_policy=AGENT_ACTIVITY_RETRY,
+ )
+ team_id = str(payload.get("team_id") or context.get("team_id") or "")
+ if team_id:
+ task_id = (
+ f"task-{root_execution_id}-{agent_node_id}-"
+ f"{iteration + 1}-{call_index + 1}"
)
- if use_tool_call_identity_v2
- else f"{workflow.info().workflow_id}-delegate-{tool_info['tool_node_id']}-{iteration}"
- )
- tool_result = await workflow.execute_child_workflow(
- "AgentWorkflow",
- args=[child_context],
- id=delegation_child_id,
- execution_timeout=timedelta(hours=1),
- run_timeout=timedelta(hours=1),
- )
+ await workflow.execute_activity(
+ "agent.finish_delegation.v1",
+ args=[{
+ "team_id": team_id,
+ "team_task_id": task_id,
+ "parent_agent_node_id": agent_node_id,
+ "child_agent_node_id": tool_info["tool_node_id"],
+ "root_execution_id": root_execution_id,
+ "trace_id": str(call.get("id", "") or ""),
+ "success": bool(tool_result.get("success", True))
+ if isinstance(tool_result, dict) else True,
+ "result": tool_result if isinstance(tool_result, dict) else {"result": tool_result},
+ "error": tool_result.get("error")
+ if isinstance(tool_result, dict) else None,
+ "terminal_event_id": f"{task_id}:terminal",
+ }],
+ activity_id=(
+ f"finish-delegation-{iteration + 1}-{call_index + 1}"
+ ),
+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,
+ retry_policy=AGENT_ACTIVITY_RETRY,
+ )
+ if next_delegation_to_start < len(delegation_call_indices):
+ await _start_delegation(
+ delegation_call_indices[next_delegation_to_start]
+ )
+ next_delegation_to_start += 1
else:
tool_activity_id = (
_tool_activity_id_v2(
@@ -761,6 +1015,31 @@ class AgentWorkflow:
# the LLM (per user decision: LLM sees error and
# continues — matches the in-process agent loop).
workflow.logger.warning(f"AgentWorkflow tool {tool_info['node_type']!r} failed: {e}")
+ team_id = str(payload.get("team_id") or context.get("team_id") or "")
+ if is_delegation and team_id:
+ task_id = (
+ f"task-{root_execution_id}-{agent_node_id}-"
+ f"{iteration + 1}-{call_index + 1}"
+ )
+ await workflow.execute_activity(
+ "agent.finish_delegation.v1",
+ args=[{
+ "team_id": team_id,
+ "team_task_id": task_id,
+ "parent_agent_node_id": agent_node_id,
+ "child_agent_node_id": tool_info["tool_node_id"],
+ "root_execution_id": root_execution_id,
+ "trace_id": str(call.get("id", "") or ""),
+ "success": False,
+ "error": f"{type(e).__name__}: {e}",
+ "terminal_event_id": f"{task_id}:terminal",
+ }],
+ activity_id=(
+ f"finish-delegation-{iteration + 1}-{call_index + 1}"
+ ),
+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,
+ retry_policy=AGENT_ACTIVITY_RETRY,
+ )
tool_content = f'{{"error": "{type(e).__name__}: {e}"}}'
messages.append(
@@ -774,6 +1053,20 @@ class AgentWorkflow:
}
)
+ if yielded_own_permit:
+ await workflow.execute_activity(
+ "agent.acquire_subagent_permit.v1",
+ args=[{
+ "root_execution_id": root_execution_id,
+ "permit_id": own_permit_id,
+ "limit": max_concurrent_subagents,
+ }],
+ activity_id=f"reacquire-own-permit-{iteration + 1}",
+ start_to_close_timeout=timedelta(hours=1),
+ heartbeat_timeout=timedelta(seconds=10),
+ retry_policy=AGENT_ACTIVITY_RETRY,
+ )
+
# ---- Persist this turn (append-per-turn) -------------------
# Snapshot the most recent user/assistant pair into memory.
await self._persist_turn(
diff --git a/server/services/workflow_import.py b/server/services/workflow_import.py
index 39281996..e49400c7 100644
--- a/server/services/workflow_import.py
+++ b/server/services/workflow_import.py
@@ -85,9 +85,15 @@ def remap_node_ids(
for edge in edges:
src = id_map.get(edge.get("source"), edge.get("source"))
tgt = id_map.get(edge.get("target"), edge.get("target"))
+ # Older backend-generated workflow operations used snake_case.
+ # Persist imports in the canonical ReactFlow shape.
+ target_handle = edge.get("targetHandle") or edge.get("target_handle")
+ normalized_edge = {key: value for key, value in edge.items() if key != "target_handle"}
+ if target_handle is not None:
+ normalized_edge["targetHandle"] = target_handle
new_edges.append(
{
- **edge,
+ **normalized_edge,
"source": src,
"target": tgt,
"id": f"e-{src}-{tgt}-{now}-{salt}",
diff --git a/server/services/workflow_validator.py b/server/services/workflow_validator.py
index 96e20d0b..edf2c722 100644
--- a/server/services/workflow_validator.py
+++ b/server/services/workflow_validator.py
@@ -36,7 +36,14 @@ from __future__ import annotations
from typing import Any, Dict, List, Optional
from core.logging import get_logger
+from constants import AI_AGENT_TYPES
from services.node_registry import get_node_class
+from services.plugin.edge_walker import (
+ TEAM_LEAD_TYPES,
+ TEAMMATE_HANDLE,
+ build_teammate_descriptors,
+ edge_target_handle,
+)
logger = get_logger(__name__)
@@ -91,6 +98,101 @@ async def validate_workflow(
}
)
+ # Team topology is validated independently from ordinary execution edges.
+ # ReactFlow stores teammate edges as worker -> lead, while delegation runs
+ # lead -> worker, so cycle/depth analysis below reverses them.
+ team_edges: List[tuple[str, str]] = []
+ for edge in edges:
+ handle = edge_target_handle(edge)
+ if handle != TEAMMATE_HANDLE:
+ if isinstance(handle, str) and handle.startswith("input-team"):
+ errors.append({
+ "code": "INVALID_TEAM_EDGE",
+ "node_id": edge.get("target"),
+ "message": f"Unsupported teammate handle {handle!r}; use {TEAMMATE_HANDLE!r}",
+ })
+ continue
+ source = node_by_id.get(edge.get("source"))
+ target = node_by_id.get(edge.get("target"))
+ if not source or not target:
+ continue # already reported as DANGLING_EDGE
+ if target.get("type") not in TEAM_LEAD_TYPES:
+ errors.append({
+ "code": "INVALID_TEAM_EDGE",
+ "node_id": target.get("id"),
+ "message": "The input-teammates handle is only valid on orchestrator_agent or ai_employee",
+ })
+ continue
+ if source.get("type") not in AI_AGENT_TYPES:
+ errors.append({
+ "code": "INVALID_TEAM_EDGE",
+ "node_id": source.get("id"),
+ "message": f"Node type {source.get('type')!r} cannot be connected as a teammate",
+ })
+ continue
+ team_edges.append((target["id"], source["id"]))
+
+ for lead_id in sorted({lead for lead, _ in team_edges}):
+ descriptors = build_teammate_descriptors(lead_id, {"nodes": nodes, "edges": edges})
+ by_type: Dict[str, List[Dict[str, Any]]] = {}
+ by_name: Dict[str, List[Dict[str, Any]]] = {}
+ for descriptor in descriptors:
+ by_type.setdefault(descriptor["node_type"], []).append(descriptor)
+ by_name.setdefault(descriptor["delegate_tool_name"], []).append(descriptor)
+ for teammate_type, duplicates in sorted(by_type.items()):
+ if teammate_type != "aiAgent" and len(duplicates) > 1:
+ errors.append({
+ "code": "DUPLICATE_TEAMMATE_TYPE",
+ "node_id": lead_id,
+ "node_type": teammate_type,
+ "nodes": sorted(item["node_id"] for item in duplicates),
+ "message": f"Team lead {lead_id!r} may connect only one {teammate_type!r} teammate",
+ })
+ for name, duplicates in sorted(by_name.items()):
+ if len(duplicates) > 1:
+ errors.append({
+ "code": "DUPLICATE_DELEGATE_NAME",
+ "node_id": lead_id,
+ "tool_name": name,
+ "nodes": sorted(item["node_id"] for item in duplicates),
+ "message": f"Delegation tool name {name!r} is ambiguous on team lead {lead_id!r}",
+ })
+
+ delegation_graph: Dict[str, List[str]] = {}
+ for lead, teammate in team_edges:
+ delegation_graph.setdefault(lead, []).append(teammate)
+
+ cycle_nodes: set[str] = set()
+ depth_nodes: set[str] = set()
+
+ def walk_team(node_id: str, path: List[str]) -> None:
+ if node_id in path:
+ cycle_nodes.update(path[path.index(node_id):] + [node_id])
+ return
+ next_path = [*path, node_id]
+ # At most two delegated child layers beneath a root lead.
+ if len(next_path) - 1 > 2:
+ depth_nodes.update(next_path)
+ return
+ for child_id in delegation_graph.get(node_id, []):
+ walk_team(child_id, next_path)
+
+ for lead_id in sorted(delegation_graph):
+ walk_team(lead_id, [])
+ if cycle_nodes:
+ errors.append({
+ "code": "TEAM_DELEGATION_CYCLE",
+ "node_id": None,
+ "nodes": sorted(cycle_nodes),
+ "message": f"Team delegation cycle detected involving nodes: {sorted(cycle_nodes)}",
+ })
+ if depth_nodes:
+ errors.append({
+ "code": "TEAM_DEPTH_EXCEEDED",
+ "node_id": None,
+ "nodes": sorted(depth_nodes),
+ "message": "Team delegation exceeds the maximum of two child layers",
+ })
# 2. Unknown node types — plugin not installed on this instance. Errors.
# 3. Per-node Pydantic param validation. Warnings (matches runtime
# soft-fail at node_executor._prepare_parameters).
diff --git a/server/tests/services/test_subagent_concurrency.py b/server/tests/services/test_subagent_concurrency.py
new file mode 100644
index 00000000..3a13f9fa
--- /dev/null
+++ b/server/tests/services/test_subagent_concurrency.py
@@ -0,0 +1,55 @@
+from __future__ import annotations
+
+import asyncio
+import importlib.util
+import sys
+import uuid
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+
+async def concurrency_database():
+ module_name = "tests._real_concurrency_database"
+ spec = importlib.util.spec_from_file_location(
+ module_name, Path(__file__).resolve().parents[2] / "core" / "database.py"
+ )
+ assert spec and spec.loader
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[module_name] = module
+ spec.loader.exec_module(module)
+ db_path = Path.cwd() / f".subagent-concurrency-{uuid.uuid4().hex}.db"
+ database = module.Database(SimpleNamespace(
+ database_url=f"sqlite+aiosqlite:///{db_path.as_posix()}",
+ database_echo=False, database_pool_size=5, database_max_overflow=5,
+ ))
+ await database.startup()
+ try:
+ yield database
+ finally:
+ await database.shutdown()
+ sys.modules.pop(module_name, None)
+ for candidate in (db_path, Path(f"{db_path}-wal"), Path(f"{db_path}-shm")):
+ candidate.unlink(missing_ok=True)
+
+
+async def test_root_limit_is_atomic_across_parallel_acquires(concurrency_database):
+ results = await asyncio.gather(*(
+ concurrency_database.acquire_subagent_permit("root-1", f"call-{i}", 3)
+ for i in range(10)
+ ))
+ assert sum(results) == 3
+
+
+async def test_acquire_and_release_are_idempotent(concurrency_database):
+ assert await concurrency_database.acquire_subagent_permit("root-1", "call-1", 1)
+ assert await concurrency_database.acquire_subagent_permit("root-1", "call-1", 1)
+ assert not await concurrency_database.acquire_subagent_permit("root-1", "call-2", 1)
+ assert await concurrency_database.release_subagent_permit("root-1", "call-1")
+ assert await concurrency_database.release_subagent_permit("root-1", "call-1")
+ assert await concurrency_database.acquire_subagent_permit("root-1", "call-2", 1)
+
diff --git a/server/tests/temporal/test_agent_workflow.py b/server/tests/temporal/test_agent_workflow.py
index 07a58d21..2e8e075a 100644
--- a/server/tests/temporal/test_agent_workflow.py
+++ b/server/tests/temporal/test_agent_workflow.py
@@ -39,6 +39,65 @@ class TestAgentWorkflowDefinition:
assert defn.sandboxed is False, "AgentWorkflow must be sandboxed=False so it can read " "services.node_registry deterministically"
+class TestDurableTeamDelegationContract:
+ """Regression coverage for team-handle Temporal delegation."""
+
+ def test_prepare_payload_expands_team_handle(self):
+ import inspect
+
+ from services.temporal.agent_activities import prepare_agent_payload
+
+ source = inspect.getsource(prepare_agent_payload)
+ assert "collect_teammate_connections" in source
+ assert '"input-tools"' in source
+ assert "get_or_create_execution_team" in source
+ assert '"team_id": execution_team_id' in source
+
+ def test_same_turn_delegations_start_before_ordered_await(self):
+ import inspect
+
+ from services.temporal.agent_workflow import AgentWorkflow
+
+ source = inspect.getsource(AgentWorkflow.run)
+ assert "workflow.start_child_workflow" in source
+ assert "max_concurrent_subagents" in source
+ assert "delegation_handles[call_index]" in source
+ assert "tool_result = await handle" in source
+
+ def test_child_invocation_has_isolated_trace_envelope(self):
+ import inspect
+
+ from services.temporal.agent_workflow import AgentWorkflow
+
+ source = inspect.getsource(AgentWorkflow.run)
+ for field in (
+ "root_execution_id",
+ "parent_node_id",
+ "delegation_depth",
+ "team_id",
+ "team_task_id",
+ "trace_id",
+ "invocation",
+ ):
+ assert f'"{field}"' in source
+
+ def test_durable_assignment_precedes_child_start(self):
+ import inspect
+
+ from services.temporal.agent_workflow import AgentWorkflow
+
+ source = inspect.getsource(AgentWorkflow.run)
+ queue_at = source.index('"agent.queue_delegation.v1"')
+ acquire_at = source.index('"agent.acquire_subagent_permit.v1"')
+ claim_at = source.index('"agent.begin_delegation.v1"')
+ start_at = source.index("workflow.start_child_workflow")
+ assert queue_at < acquire_at < claim_at < start_at
+ assert '"agent.finish_delegation.v1"' in source
+ assert '"agent.release_subagent_permit.v1"' in source
+ assert "assignment_event_id" in source
+ assert "terminal_event_id" in source
+
+
class TestAgentActivities:
"""The three agent activities must register under stable names so
``AgentWorkflow`` can schedule them by string."""
@@ -62,23 +121,29 @@ class TestAgentActivities:
defn = getattr(compact_agent_memory, "__temporal_activity_definition")
assert defn.name == "agent.compact_memory.v1"
- def test_collect_returns_all_seven(self):
+ def test_collect_returns_all_agent_activities(self):
"""Each successive sprint added one F4.B agent activity:
infra (3) → per-agent-wiring +prepare_payload (4) → CloudEvents
cleanup +broadcast_progress (5) → +store_output (6) →
- +refresh_tools (7). All must register so the AgentWorkflow loop
+ +refresh_tools (7) + durable delegation lifecycle/coordinator (13). All must register so the AgentWorkflow loop
can schedule them by name."""
from services.temporal.agent_activities import collect_agent_activities
activities = collect_agent_activities()
names = sorted(getattr(a, "__temporal_activity_definition").name for a in activities)
assert names == [
+ "agent.acquire_subagent_permit.v1",
+ "agent.begin_delegation.v1",
"agent.broadcast_progress.v1",
"agent.compact_memory.v1",
"agent.execute_llm_step.v1",
+ "agent.finalize_team.v1",
+ "agent.finish_delegation.v1",
"agent.persist_turn.v1",
"agent.prepare_payload.v1",
+ "agent.queue_delegation.v1",
"agent.refresh_tools.v1",
+ "agent.release_subagent_permit.v1",
"agent.store_output.v1",
]
diff --git a/server/tests/test_team_topology.py b/server/tests/test_team_topology.py
new file mode 100644
index 00000000..f625dd78
--- /dev/null
+++ b/server/tests/test_team_topology.py
@@ -0,0 +1,110 @@
+from unittest.mock import AsyncMock
+
+import pytest
+from pydantic import BaseModel
+
+from services.plugin.edge_walker import collect_teammate_connections
+
+
+class _Params(BaseModel):
+ pass
+
+
+class _Node:
+ Params = _Params
+ credentials = ()
+
+
+def node(node_id, node_type, label=None):
+ return {"id": node_id, "type": node_type, "data": {"label": label} if label is not None else {}}
+
+
+def edge(source, target, handle="input-teammates", *, legacy=False):
+ result = {"source": source, "target": target}
+ result["target_handle" if legacy else "targetHandle"] = handle
+ return result
+
+
+def patch_types(monkeypatch, nodes):
+ known = {item["type"] for item in nodes}
+ monkeypatch.setattr("services.workflow_validator.get_node_class", lambda value: _Node if value in known else None)
+
+
+async def test_custom_agents_are_label_addressable_and_collision_safe():
+ nodes = [node("lead", "orchestrator_agent"), node("custom-a", "aiAgent", "Research"), node("custom-b", "aiAgent", "Research")]
+ context = {"nodes": nodes, "edges": [edge("custom-a", "lead"), edge("custom-b", "lead", legacy=True)]}
+ database = AsyncMock()
+ database.get_node_parameters.return_value = {}
+
+ teammates = await collect_teammate_connections("lead", context, database)
+
+ names = [item["delegate_tool_name"] for item in teammates]
+ assert len(set(names)) == 2
+ assert all(name.startswith("delegate_to_research_") for name in names)
+ # Stable across repeated expansion (required for durable dispatch IDs).
+ again = await collect_teammate_connections("lead", context, database)
+ assert [item["delegate_tool_name"] for item in again] == names
+
+
+async def test_specialized_delegate_name_is_stable_and_capabilities_are_collected():
+ nodes = [node("lead", "ai_employee"), node("coder", "coding_agent", "Backend"), node("search", "duckduckgoSearch", "Search")]
+ context = {"nodes": nodes, "edges": [edge("coder", "lead"), edge("search", "coder", "input-tools")]}
+ database = AsyncMock()
+ database.get_node_parameters.return_value = {}
+
+ [teammate] = await collect_teammate_connections("lead", context, database)
+
+ assert teammate["delegate_tool_name"] == "delegate_to_coding_agent"
+ assert teammate["child_tools"] == [{"node_id": "search", "node_type": "duckduckgoSearch", "label": "Search"}]
+
+
+async def test_duplicate_specialized_type_is_blocking(monkeypatch):
+ from services.workflow_validator import validate_workflow
+
+ nodes = [node("lead", "orchestrator_agent"), node("a", "coding_agent"), node("b", "coding_agent")]
+ patch_types(monkeypatch, nodes)
+ report = await validate_workflow(nodes, [edge("a", "lead"), edge("b", "lead")])
+ issue = next(item for item in report["errors"] if item["code"] == "DUPLICATE_TEAMMATE_TYPE")
+ assert issue["nodes"] == ["a", "b"]
+
+
+async def test_ai_agent_type_may_repeat(monkeypatch):
+ from services.workflow_validator import validate_workflow
+
+ nodes = [node("lead", "orchestrator_agent"), node("a", "aiAgent", "One"), node("b", "aiAgent", "Two")]
+ patch_types(monkeypatch, nodes)
+ report = await validate_workflow(nodes, [edge("a", "lead"), edge("b", "lead")])
+ assert not [item for item in report["errors"] if item["code"].startswith("DUPLICATE_")]
+
+
+async def test_invalid_team_endpoint_cycle_and_depth_codes(monkeypatch):
+ from services.workflow_validator import validate_workflow
+
+ nodes = [
+ node("lead-a", "orchestrator_agent"), node("lead-b", "ai_employee"),
+ node("lead-c", "orchestrator_agent"), node("lead-d", "ai_employee"),
+ node("worker", "coding_agent"), node("tool", "duckduckgoSearch"),
+ ]
+ patch_types(monkeypatch, nodes)
+ edges = [
+ edge("lead-b", "lead-a"), edge("lead-a", "lead-b"),
+ edge("lead-c", "lead-b"), edge("lead-d", "lead-c"), edge("worker", "lead-d"),
+ edge("tool", "worker"),
+ ]
+ report = await validate_workflow(nodes, edges)
+ codes = {item["code"] for item in report["errors"]}
+ assert {"INVALID_TEAM_EDGE", "TEAM_DELEGATION_CYCLE", "TEAM_DEPTH_EXCEEDED"} <= codes
+
+
+def test_import_remap_normalizes_legacy_handle():
+ from services.workflow_import import remap_node_ids
+
+ nodes = [node("worker", "aiAgent"), node("lead", "orchestrator_agent")]
+ _, [remapped], _ = remap_node_ids(nodes, [edge("worker", "lead", legacy=True)])
+ assert remapped["targetHandle"] == "input-teammates"
+ assert "target_handle" not in remapped