UNPKG

@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
# 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*