@jimmy2822/claude-code-sub-agents-mode
Version:
TypeScript Clean Architecture Multi-Agent Framework for Claude Code CLI Integration
231 lines (187 loc) ⢠7.63 kB
Markdown
# Claude Code Multi-Agent System
## š Quick Start
```bash
# Start the enhanced lead agent system
node bin/enhanced-lead-agent.js # Port 3011
```
**Web Interface**: http://localhost:3011
**API Dashboard**: http://localhost:3011/api/usage
**WebSocket**: ws://localhost:3011/ws
## šÆ System Overview
### What This System Does
A sophisticated multi-agent framework that coordinates specialized AI agents to execute complex development tasks using real Claude Code CLI. The system intelligently manages sessions, tracks usage, and provides real-time monitoring.
### Core Innovation: Intelligent Session Management š„
**Problem Solved**: Previously created new Claude session for EVERY task ā rapidly hit 20x usage limits
**Solution**: Smart session pooling with `claude --resume` ā 90% reduction in new sessions
## š Key Components
### 1. Enhanced Lead Agent (Port 3011)
- Intelligent requirement analysis and breakdown
- Multi-agent coordination and task distribution
- Real-time WebSocket updates
- Auto-approval workflows
### 2. Specialized Agents (7 Types)
| Agent | Pool Size | Specialization | Tools |
|-------|-----------|----------------|-------|
| **Backend Specialist** | 3 sessions | APIs, databases, server logic | Read, Write, Edit, Bash |
| **Frontend Specialist** | 3 sessions | UI/UX, responsive design | Read, Write, Edit, Bash |
| **Solution Architect** | 2 sessions | System design, architecture | Read, Grep, WebSearch |
| **Senior Full-Stack** | 2 sessions | End-to-end implementation | All tools |
| **QA Engineer** | 2 sessions | Testing, quality assurance | Read, Bash, Grep |
| **DevOps Engineer** | 2 sessions | Deployment, infrastructure | All tools |
| **Requirements Analyst** | 2 sessions | Stakeholder analysis | Read, Grep, WebSearch |
### 3. Session Manager (`lib/session-manager.js`)
```javascript
// Intelligent session reuse configuration
{
maxSessionAge: 30 * 60 * 1000, // 30 minutes
maxTokensPerSession: 100000, // Conservative limit
maxRequestsPerSession: 50, // Per session
dailyTokenLimit: 200000 // Daily total
}
```
**Key Features:**
- Automatic session pooling per agent type
- Health monitoring (age, tokens, requests)
- Smart selection based on task complexity
- Auto-cleanup every 5 minutes
- Uses `claude --resume <sessionId>` for continuation
### 4. Usage Dashboard
Real-time monitoring showing:
- š **Token Usage**: Daily consumption with progress bar
- š **Active Sessions**: Healthy session count
- š **Total Requests**: Cumulative API calls
- ā° **Reset Timer**: Minutes to daily reset
- š¤ **Per-Agent Metrics**: Individual session health
## š ļø Technical Architecture
### Session Management Flow
```
1. Task Request ā Session Manager
2. Check existing session pool for agent type
3. Evaluate session health (tokens, age, requests)
4. If healthy session exists ā `claude --resume <sessionId>`
5. If no healthy session ā Create new with `claude --print`
6. Track usage and update metrics
7. Auto-cleanup unhealthy sessions
```
### Ideal Performance Metrics
- **Session reuse rate**: > 80%
- **Average tokens/session**: < 50,000
- **Sessions per agent**: 1-3 active
- **Daily token usage**: < 150,000
### Monitor Effectiveness
```javascript
// Check session reuse rate
const usage = await fetch('http://localhost:3011/api/usage').then(r => r.json());
const reuseRate = (usage.global.totalRequests - usage.global.totalSessions) / usage.global.totalRequests * 100;
console.log(`Session reuse rate: ${reuseRate.toFixed(2)}%`);
```
## š Project Structure
### Core Files
- `lib/enhanced-lead-agent.js` - Main coordination system
- `lib/session-manager.js` - Intelligent session management
- `lib/git-worktree-manager.js` - Git worktree handling
### Workspace Directories
```
enhanced-workspace/
āāā projects/ # Historical project data
ā āāā project_[id]/
ā āāā analysis.json # Requirements analysis
ā āāā agent-discussion.json
āāā claude-instructions/ # Task instructions
ā āāā prompt_task_*.txt
āāā claude-results/ # Execution results
āāā result_task_*.json
```
## š§ Configuration & Settings
### Auto-Approval Modes
- **Manual**: Full user control
- **Semi-Auto**: Auto-approve, manual execute
- **Full-Auto**: Complete automation
- **Batch-Auto**: Queue and batch process
### Session Pool Tuning
Edit `lib/session-manager.js` to adjust:
```javascript
agentSessionPool: {
'backend-specialist': 3, // Increase for heavy backend work
'frontend-specialist': 3, // Increase for UI-intensive projects
// ... adjust as needed
}
```
## šØ Troubleshooting
### Common Issues & Solutions
#### Session Management
```bash
# Check active Claude sessions
claude --sessions
# Resume specific session manually
claude --resume <sessionId>
# Force new sessions (emergency reset)
rm -rf ~/.claude/sessions/
# Monitor real-time usage
curl http://localhost:3011/api/usage | jq
```
#### Usage Limits
- **"Claude AI usage limit reached"**: System auto-tries new session
- **High token usage**: Reduce session pool sizes
- **Sessions timing out**: Increase timeout in session-manager.js
#### System Issues
- **Port conflicts**: Check port 3011 (agent system)
- **WebSocket issues**: Check browser console
- **Claude Code CLI**: Verify authentication
## š Best Practices
### Session Management
1. **Monitor regularly**: Check dashboard at http://localhost:3011
2. **Adjust pools**: Increase for frequently used agents
3. **Complex tasks**: System auto-assigns fresh sessions
4. **Manual cleanup**: `sessionManager.cleanupSessions()` if needed
### Performance Optimization
- Enable parallel agent execution
- Use auto-approval for known workflows
- Monitor token usage patterns
- Adjust session pools based on workload
## š Security & Requirements
### System Requirements
- Node.js 18+
- Python 3.11+
- Claude Code CLI (authenticated)
- pnpm package manager
### Security Considerations
- Never commit API keys
- Use environment variables for secrets
- Regular dependency updates
- Proper workspace permissions
- Complete audit trail
## š For AI Assistants
### Critical Information
- **Primary system**: `bin/enhanced-lead-agent.js`
- **Session manager**: `lib/session-manager.js`
- **Real execution**: Uses actual Claude Code CLI, not simulation
- **Session reuse**: Automatic with `--resume` command
- **7 agent types**: Each with dedicated session pools
- **Token limits**: 100K/session, 200K/day
- **Health checks**: Auto-cleanup every 5 minutes
- **Dashboard**: Real-time at http://localhost:3011
### Key Commands
```bash
# Start system
node bin/enhanced-lead-agent.js
# Check usage
curl http://localhost:3011/api/usage | jq
# Manual session operations
claude --sessions
claude --resume <sessionId>
```
## š Additional Resources
- `PROJECT_STRUCTURE.md` - Detailed directory organization
- `enhanced-workspace/projects/` - Historical project data
- WebSocket API for real-time updates
- Auto-approval workflow documentation
## š Important Instructions
### Core Principles
- **Do what has been asked**: Nothing more, nothing less
- **Prefer editing over creating**: ALWAYS edit existing files when possible
- **No unnecessary files**: NEVER create files unless absolutely necessary
- **No proactive documentation**: Only create documentation when explicitly requested
- **Clean focused code**: Remove demos, tests, and legacy code not essential to core functionality
---
*Version 2.3.0 - NerdTree Dashboard & Streamlined Multi-Agent System*