Multi-Agent Collaboration System Analysis
Project: Wegent
Analysis Date: 2026-02-01
Document Version: 1.0
Table of Contents
- Executive Summary
- Architecture Overview
- Collaboration Models Deep Dive
- Agno Framework Integration
- Role System & Bot Interaction
- Prompt Composition Strategy
- Execution Flow Analysis
- Key Implementation Files
- Complex Coordination Logic
- Best Practices & Recommendations
1. Executive Summary
The Wegent Multi-Agent Collaboration system implements four distinct collaboration patterns inspired by human team dynamics:
- Pipeline: Sequential execution for structured workflows
- Route: Intelligent task routing to specialized agents
- Coordinate: Parallel task decomposition with leader coordination
- Collaborate: Shared context discussion for complex problem-solving
The system is built on a hybrid architecture supporting multiple executor backends:
- Agno Framework (primary): Full multi-agent team support with all 4 modes
- Claude Code: Supports coordinate mode via SubAgent pattern
- Dify: Single-agent external API proxy (no multi-agent support)
Key Strengths:
- Flexible role system (Leader/Member) enabling hierarchical coordination
- Session management for conversation continuity across pipeline stages
- Confirmation checkpoints in Pipeline mode for human-in-the-loop workflows
- Streaming execution with real-time progress reporting
2. Architecture Overview
2.1 High-Level Architecture
2.2 Resource Hierarchy
2.3 Data Flow Architecture
3. Collaboration Models Deep Dive
3.1 Model Selection Decision Tree
3.2 Pipeline Model (Sequential Execution)
Core Concept: Bots execute in a predefined sequence, with each bot's output becoming the next bot's input.
Key Features:
- Sequential execution: Strict order enforcement via subtask creation
- Session isolation: Each bot can have independent session (
new_sessionflag) - Confirmation checkpoints:
requireConfirmationflag enables human approval - Data passing: Output of stage N → Input of stage N+1
Agno Configuration:
# team_builder.py:200-230
# Pipeline uses default configuration (no special flags)
# Execution order is controlled by backend subtask creation
Backend Implementation (backend/app/services/adapters/pipeline_stage.py):
# Pipeline stages are created as sequential subtasks
# Each stage completion triggers next stage creation
# requireConfirmation pauses pipeline for human input
Use Cases:
- Software Development: Requirements → Design → Implementation → Review → Test → Deploy
- Content Production: Writing → Editing → SEO → Publishing
- Data Processing: Collection → Cleaning → Transformation → Analysis
3.3 Route Model (Intelligent Routing)
Core Concept: Leader bot analyzes input and routes to the most suitable specialist bot.
Agno Configuration:
# team_builder.py:221-223
"route" mode config:
{
"respond_directly": True
# Leader selects single most suitable member
}
Prompt Design Pattern:
- name: "router"
role: "leader"
prompt: |
You are a technical support router.
Analyze the user's question and route it to the appropriate specialist:
- Frontend issues → frontend-expert
- Backend issues → backend-expert
- Database issues → database-expert
- DevOps/Infrastructure issues → devops-expert
Provide a brief analysis of why you chose this specialist.
Use Cases:
- Customer Service: Route to Technical/After-Sales/Sales/Complaints
- Technical Support: Frontend/Backend/Database/DevOps experts
- Content Classification: News/Tech/Entertainment/Sports channels
3.4 Coordinate Model (Parallel Coordination)
Core Concept: Leader decomposes tasks, assigns to multiple bots in parallel, then aggregates results.
Agno Configuration:
# team_builder.py:210-214
"coordinate" mode config:
{
"reasoning": True,
# Leader reasons about task decomposition
}
Extended Configuration (agno_agent.py:915-918):
if self.mode == "coordinate":
ext_config = {
"show_full_reasoning": True,
}
Claude Code Integration:
- Generates SubAgent configuration files (
.claude/agents/*.md) - Each member bot becomes a SubAgent the Leader can invoke
- See
claude_code_agent.py:2011-2068
Prompt Design Pattern:
- name: "coordinator"
role: "leader"
prompt: |
You are a market research coordinator.
PHASE 1 - Task Decomposition:
Break down the market research task into parallel workstreams:
1. Competitor analysis
2. Customer sentiment analysis
3. Market trend analysis
Assign each workstream to the appropriate specialist.
PHASE 2 - Result Synthesis:
After receiving all reports, synthesize them into a comprehensive report.
Use Cases:
- Market Research: Competitor + Customer + Trend + Data analysis in parallel
- Code Review: Security + Performance + Quality + Test coverage review
- Content Creation: Research + Case studies + Data analysis + Expert opinions
3.5 Collaborate Model (Shared Context Discussion)
Core Concept: All bots participate in a shared conversation context, freely discussing and building on each other's ideas.
Agno Configuration:
# team_builder.py:215-220
"collaborate" mode config:
{
"delegate_task_to_all_members": True,
"reasoning": True,
# All members receive the task simultaneously
# Leader facilitates and summarizes
}
Prompt Design Pattern:
members:
- name: "architect"
role: "member"
prompt: |
Role: Technical Architect
Goal: Design scalable solution
Interaction: Build on others' ideas, raise technical concerns
- name: "product"
role: "member"
prompt: |
Role: Product Manager
Goal: Ensure user value
Interaction: Connect features to user needs, prioritize
Use Cases:
- Brainstorming: Creative ideation with multiple perspectives
- Technical Design: Architecture discussions with all stakeholders
- Incident Response: Real-time collaboration for system issues
3.6 Model Comparison Matrix
| Feature | Pipeline | Route | Coordinate | Collaborate |
|---|---|---|---|---|
| Execution Order | Fixed sequence | Dynamic single path | Parallel execution | No fixed order |
| Bot Interaction | Unidirectional | Leader → Expert | Leader coordination | Full interaction |
| Context Sharing | Partial (sequential) | Independent | Leader aggregation | Fully shared |
| Team Size | 3-6 bots | 1 Leader + N experts | 1 Leader + 3-5 experts | 3-8 bots |
| Parallelism | Low (serial) | Low (single path) | High (parallel) | High (concurrent) |
| Result Type | Linear accumulation | Single expert output | Comprehensive report | Consensus result |
| Ease of Use | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐ |
| Flexibility | ⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
4. Agno Framework Integration
4.1 Agno Team Architecture
4.2 Team Building Flow
4.3 Mode Configuration Mapping
| Wegent Mode | Agno Team Config | Behavior |
|---|---|---|
pipeline | Default (no flags) | Backend controls execution order via subtasks |
route | respond_directly=True | Leader picks one member to respond |
coordinate | reasoning=True | Leader reasons about task decomposition |
collaborate | delegate_task_to_all_members=True, reasoning=True | All members work in parallel |
Code Reference (executor/agents/agno/team_builder.py:200-230):
def _get_mode_config(self, mode: str) -> Dict[str, Any]:
if mode == "coordinate":
return {"reasoning": True}
elif mode == "collaborate":
return {
"delegate_task_to_all_members": True,
"reasoning": True,
}
elif mode == "route":
return {"respond_directly": True}
else:
return {} # Pipeline uses default
4.4 Session Management
Agno uses SQLite for session persistence:
# agno_agent.py:37
db = SqliteDb(db_file="/tmp/agno_data.db")
# Team creation with session
Team(
session_id=session_id, # Task-based session
db=self.db, # SQLite persistence
add_history_to_context=True,
num_history_runs=3,
)
Session Types:
- Continuous Session:
session_id = task_id(default) - maintains history - New Session:
session_id = subtask_id- fresh context for pipeline stages
5. Role System & Bot Interaction
5.1 Role Definitions
| Role | Responsibility | Configuration | Usage |
|---|---|---|---|
| leader | Coordinates team, makes decisions, aggregates results | "role": "leader" | Required for Route, Coordinate modes |
| member | Executes assigned tasks, provides expertise | "role": "member" | Default role for all bots |
5.2 Role Assignment in Team CRD
apiVersion: agent.wecode.io/v1
kind: Team
spec:
collaborationModel: "coordinate"
members:
- name: "coordinator"
role: "leader" # 👑 Leader role
botRef:
name: coordinator-bot
prompt: "You coordinate the team..."
- name: "analyst"
role: "member" # 🤖 Member role (default)
botRef:
name: analyst-bot
prompt: "You analyze data..."
5.3 Role-Based Team Building
Implementation (executor/agents/agno/team_builder.py:118-183):
async def _create_team_members(self, options, task_data):
team_leader = None
team_members = []
for member_config in team_members_config:
member = await self.member_builder.create_member(member_config, task_data)
if member_config.get("role") == "leader":
if team_leader is None:
team_leader = member # First leader wins
else:
logger.warning("Multiple leaders found, ignoring extra")
else:
team_members.append(member)
return {"leader": team_leader, "members": team_members}
5.4 Bot-to-Bot Interaction Patterns
| Model | Interaction Pattern | Message Flow |
|---|---|---|
| Pipeline | Linear handoff | Bot₁ → output → Bot₂ → output → Bot₃ |
| Route | Star topology | Leader → selects → One Expert → result |
| Coordinate | Hub-and-spoke | Leader → parallel → All Members → Leader aggregates |
| Collaborate | Mesh network | All ↔ All (shared context) |
5.5 Bot References and Resolution
Resolution Logic (backend/app/services/adapters/team_kinds.py:400-500):
- For personal teams: Look up by (user_id, name, namespace)
- For group teams: Look up by (name, namespace) only
- Fallback to public resources (user_id=0) if not found
6. Prompt Composition Strategy
6.1 Prompt Hierarchy
6.2 Prompt Composition Flow
6.3 Role-Specific Prompt Patterns
Leader Prompt Pattern
prompt: |
You are the team {role} responsible for {responsibility}.
Your team consists of:
{member_list_with_descriptions}
Based on the task, you should:
1. Analyze the requirements
2. {mode_specific_action: route/delegate/aggregate/facilitate}
3. Ensure quality output
Task: {task_input}
Member Prompt Pattern
prompt: |
You are a {specialty} specialist on the team.
Your expertise: {expertise_areas}
When assigned a task:
1. Focus on your domain
2. Provide detailed, actionable output
3. {interaction_instruction}
Input: {task_or_context}
6.4 Prompt Implementation Details
Backend Composition (backend/app/services/adapters/executor_kinds.py:1100-1130):
# Team member info is extracted from Team CRD
for bot_config in bot_list:
team_member_info = get_team_member_info(team, bot_config["id"])
executor_data["bot"].append({
"system_prompt": ghost_prompt + "\n" + team_member_info.prompt,
"role": team_member_info.role,
# ... other config
})
Executor Prepend (executor/agents/agno/agno_agent.py:531-538):
# Prepare prompt with runtime context
prompt = self.prompt
if self.options.get("cwd"):
prompt += "\nCurrent working directory: " + self.options.get("cwd")
if self.task_data.get("git_url"):
prompt += "\nProject URL: " + self.task_data.get("git_url")
6.5 Multi-Agent Context Management
Shared Context (Collaborate Mode):
# Agno Team configuration
Team(
share_member_interactions=True, # All members see each other's messages
add_member_tools_to_context=True, # Members can use each other's tools
)
Isolated Context (Route Mode):
# Route mode uses respond_directly
# Only selected member sees the full context
# Other members remain idle
7. Execution Flow Analysis
7.1 Task Execution Lifecycle
7.2 Pipeline Mode Execution Flow
7.3 Coordinate Mode Execution Flow
7.4 Streaming Execution Flow
8. Key Implementation Files
8.1 Backend Implementation
| File | Purpose | Key Classes/Functions |
|---|---|---|
backend/app/services/adapters/team_kinds.py | Team CRD management | TeamKindsService, create_with_user(), _convert_to_team_dict() |
backend/app/services/adapters/task_kinds/converters.py | Task creation | create_subtasks(), pipeline subtask logic |
backend/app/services/adapters/pipeline_stage.py | Pipeline execution | PipelineStageManager, handle_stage_completion() |
backend/app/services/adapters/executor_kinds.py | Executor dispatch | prepare_executor_task(), bot configuration |
backend/app/api/endpoints/adapter/teams.py | Team API | REST endpoints for team CRUD |
backend/app/schemas/team.py | Data models | TeamCreate, TeamInDB, BotInfo |
backend/app/schemas/kind.py | CRD schemas | Team, TeamMember, TeamSpec |
8.2 Executor Implementation
| File | Purpose | Key Classes/Functions |
|---|---|---|
executor/agents/agno/agno_agent.py | Main Agno execution | AgnoAgent, execute_async(), _run_team_async() |
executor/agents/agno/team_builder.py | Team construction | TeamBuilder, create_team(), _get_mode_config() |
executor/agents/agno/member_builder.py | Agent creation | MemberBuilder, create_member() |
executor/agents/agno/mcp_manager.py | Tool management | MCPManager, setup_mcp_tools() |
executor/agents/agno/model_factory.py | LLM configuration | ModelFactory, create_model() |
executor/agents/claude_code/claude_code_agent.py | Claude Code execution | ClaudeCodeAgent, _setup_coordinate_mode() |
8.3 Shared Models
| File | Purpose | Key Classes |
|---|---|---|
shared/models/task.py | Task data model | Task, Subtask, ExecutionResult |
shared/models/kind.py | CRD base models | Kind, KindMetadata, KindSpec |
9. Complex Coordination Logic
9.1 Pipeline Stage Management
Problem: Pipeline mode requires sequential execution with optional human confirmation checkpoints.
Solution: Multi-layer state management
Implementation Details (backend/app/services/adapters/pipeline_stage.py):
class PipelineStageManager:
def handle_stage_completion(self, task, subtask):
# 1. Get current stage from task labels
current_stage = self._get_current_stage(task)
# 2. Check if current stage requires confirmation
if self._should_stay_at_current_bot(task, current_stage):
# Pause and wait for user confirmation
self._mark_waiting_for_confirmation(task, current_stage)
return # Don't create next stage yet
# 3. Create next stage subtask
next_stage = current_stage + 1
if next_stage < total_stages:
self._create_next_stage_subtask(task, next_stage)
Key Complexity:
- State distributed across Task labels (current stage), Subtask status, and confirmation flags
- Requires atomic updates to prevent race conditions
- WebSocket notifications for real-time status updates
9.2 Session Isolation vs Continuity
Problem: Pipeline stages need flexible session management - sometimes isolated (fresh context), sometimes continuous (inherit context).
Solution: Configurable session ID strategy
Implementation (executor/agents/agno/agno_agent.py:100-115):
# Check if this subtask should start a new session
new_session = task_data.get("new_session", False)
if new_session:
# Use subtask_id as session_id to create fresh session
self.session_id = task_data.get("subtask_id", self.task_id)
logger.info(f"Pipeline mode: new_session=True, avoiding history inheritance")
else:
# Default: use task_id as session_id to maintain history
self.session_id = self.task_id
Key Complexity:
- Session ID determines SQLite database lookup key
- Different session = no access to previous conversation
- Used for pipeline stage isolation and privacy boundaries
9.3 Multi-Executor Backend Support
Problem: Same Team/Task model needs to work with different executors (Agno, Claude Code, Dify) with varying multi-agent capabilities.
Solution: Capability-based dispatch with mode-specific adaptations
Claude Code Coordinate Mode Setup (executor/agents/claude_code/claude_code_agent.py:2011-2070):
def _setup_coordinate_mode(self) -> None:
"""Generate .claude/agents/*.md files for SubAgent pattern"""
# Only for coordinate mode with multiple bots
if mode != "coordinate" or len(bots) <= 1:
return
# Leader is bot[0], members are bot[1:]
member_bots = bots[1:]
# Create .claude/agents directory
agents_dir = os.path.join(target_path, ".claude", "agents")
# Generate SubAgent config for each member
for bot in member_bots:
self._generate_subagent_file(agents_dir, bot)
Key Complexity:
- Each executor has different multi-agent capabilities
- Need to validate mode compatibility at task creation
- Graceful degradation (e.g., Dify ignores multi-agent config)
9.4 Confirmation Checkpoint Mechanism
Problem: Pipeline stages may require human approval before continuing.
Solution: State machine with WebSocket-driven transitions
Implementation Flow:
- Backend (
pipeline_stage.py:1728-1830):
def handle_stage_completion(self, task, completed_subtask):
# Check if just-completed stage requires confirmation
current_stage_index = self._get_current_stage_index(task)
current_member = members[current_stage_index]
require_confirmation = current_member.requireConfirmation
if require_confirmation:
# Mark as waiting, don't create next stage yet
self._set_waiting_for_confirmation(task, True)
return {"waiting_for_confirmation": True}
else:
# Auto-proceed to next stage
self._create_next_stage(task, current_stage_index + 1)
Frontend: Polls or WebSocket listens for
waiting_for_confirmationflagUser Action: Calls
POST /tasks/{id}/confirmto resumeResume (
pipeline_stage.py):
def confirm_and_proceed(self, task_id):
task = get_task(task_id)
current_stage = get_current_stage(task)
# Clear waiting flag
self._set_waiting_for_confirmation(task, False)
# Create next stage
self._create_next_stage(task, current_stage + 1)
Key Complexity:
- State persistence across API calls
- Concurrent access prevention
- Timeout handling for abandoned confirmations
10. Best Practices & Recommendations
10.1 Team Design Guidelines
Pipeline Teams
- ✅ DO: Keep stages to 3-6 bots maximum
- ✅ DO: Define clear input/output contracts between stages
- ✅ DO: Use
requireConfirmationfor critical checkpoints - ❌ DON'T: Create circular dependencies
- ❌ DON'T: Overlap responsibilities between stages
Route Teams
- ✅ DO: Make routing criteria explicit in leader prompt
- ✅ DO: Define non-overlapping expert domains
- ✅ DO: Include default routing for unknown cases
- ❌ DON'T: Create ambiguous routing rules
- ❌ DON'T: Allow expert domains to overlap
Coordinate Teams
- ✅ DO: Limit parallel bots to 3-5 for optimal performance
- ✅ DO: Define structured output formats for aggregation
- ✅ DO: Give leader strong synthesis instructions
- ❌ DON'T: Create unbalanced task decomposition
- ❌ DON'T: Skip result aggregation phase
Collaborate Teams
- ✅ DO: Set clear collaboration goals
- ✅ DO: Define distinct perspectives for each bot
- ✅ DO: Include a facilitator/leader to guide discussion
- ❌ DON'T: Allow open-ended discussions without goals
- ❌ DON'T: Create redundant roles
10.2 Prompt Engineering Best Practices
# Good Prompt Structure
team_members:
- name: "specialist"
role: "member"
prompt: |
# 1. Role Definition
You are a [specific role] specialist.
# 2. Responsibilities
Your responsibilities include:
- [Specific task 1]
- [Specific task 2]
# 3. Input Description
You will receive: [describe expected input]
# 4. Output Requirements
Provide output in the following format:
[format specification]
# 5. Quality Criteria
Ensure:
- [Quality check 1]
- [Quality check 2]
10.3 Performance Optimization
| Optimization | Impact | Implementation |
|---|---|---|
| Streaming | Real-time UX | stream=True in Agno SDK |
| Session Reuse | Reduced latency | Store team in _clients dict |
| Parallel Execution | Faster completion | Use Coordinate/Collaborate modes |
| Throttled Callbacks | Reduced overhead | 500ms interval for progress reports |
| SQLite Persistence | Conversation continuity | Agno's built-in session storage |
10.4 Debugging & Monitoring
Key Metrics to Track:
- Stage completion time (Pipeline): Identify bottlenecks
- Member response time (Coordinate): Detect slow specialists
- Routing accuracy (Route): Measure leader decision quality
- Token usage: Monitor costs per collaboration model
Debugging Tools:
- Thinking steps (
thinking_step_manager.py): Track agent reasoning - OpenTelemetry tracing: Distributed tracing across services
- Debug mode:
DEBUG_RUNenv var for verbose logging
10.5 Security Considerations
- Session Isolation: Use
new_session=truefor sensitive pipeline stages - Tool Permissions: MCP tools respect bot-specific configurations
- Data Passing: No automatic PII filtering between stages
- Confirmation Points: Use
requireConfirmationfor destructive operations
Appendix A: CRD Schema Reference
Team CRD Structure
apiVersion: agent.wecode.io/v1
kind: Team
metadata:
name: example-team
namespace: default
spec:
collaborationModel: pipeline | route | coordinate | collaborate
description: "Team description"
bind_mode: ["chat", "code"] # or empty
icon: "icon-id"
requiresWorkspace: true | false
members:
- name: "member-name"
role: "leader" | "member"
botRef:
name: "bot-name"
namespace: "default"
prompt: "Member-specific system prompt"
requireConfirmation: true | false # Pipeline only
status:
state: "Available" | "Pending" | "Error"
Bot CRD Structure
apiVersion: agent.wecode.io/v1
kind: Bot
metadata:
name: example-bot
namespace: default
spec:
ghostRef:
name: "ghost-name"
namespace: "default"
shellRef:
name: "shell-name"
namespace: "default"
modelRef: # Optional
name: "model-name"
namespace: "default"
Appendix B: Glossary
| Term | Definition |
|---|---|
| Bot | Building block component (Ghost + Shell + optional Model) |
| Team | Multi-agent group with collaboration model |
| Ghost | System prompt + MCP servers + skills |
| Shell | Runtime environment (Agno, Claude Code, Dify) |
| Task | Execution unit combining Team + Workspace |
| Subtask | Individual execution step within a Task |
| Leader | Coordination role in Route/Coordinate modes |
| Member | Execution role (all bots are members by default) |
| Pipeline | Sequential execution model |
| Coordinate | Parallel task decomposition model |
| MCP | Model Context Protocol for tool integration |
Document generated by AI analysis of Wegent Multi-Agent Collaboration system