# Agency-X: AI-Powered Development Team

🚀 **Transform feature requests into production-ready code in seconds**

Agency-X is an intelligent orchestration system that simulates a complete software development team using 16 specialized AI agents. From a simple feature prompt, it generates comprehensive project specifications, code, tests, documentation, and deployment plans.

[![npm version](https://badge.fury.io/js/@oliverpople/agency-x.svg)](https://badge.fury.io/js/@oliverpople/agency-x)
[![License: ISC](https://img.shields.io/badge/License-ISC-blue.svg)](https://opensource.org/licenses/ISC)

## ✨ Features

- 🎯 **Complete Project Generation**: From requirements to deployment in under 30 seconds
- 🤖 **16 Specialized Agents**: Product Manager, Frontend/Backend Developers, QA Engineer, Security Analyst, and more
- 🎙️ **Voice Narration**: Optional text-to-speech progress updates
- 📊 **Comprehensive Output**: Code, tests, documentation, security reports, release plans
- 🔄 **Resume Capability**: Continue interrupted sessions
- 🏗️ **SaaS Integration Ready**: Perfect for embedding in your applications
- 🎨 **AI Assistant Compatible**: Works seamlessly with Cursor, Claude Codebase, and Warp AI
- ⚡ **Smart LLM Routing**: Automatic fallback between Anthropic Claude and OpenAI
- 🛡️ **Robust Error Recovery**: Graceful handling of agent failures with detailed reporting
- 📈 **Progress Tracking**: Real-time completion rates and success statistics

## 🏢 The AI Development Team

**Phase 1 - Requirements & Architecture:**

- 👔 **Product Manager**: Defines specifications, user stories, acceptance criteria
- 🎨 **UX Designer**: Creates wireframes and user experience guidelines
- ✍️ **Copywriter**: Generates user-facing content and microcopy

**Phase 2 - Development:**

- 💻 **Frontend Developer**: React/Vue/Angular components and interfaces
- ⚡ **Backend Developer**: APIs, databases, server logic
- 🔧 **Fullstack Integrator**: Ensures seamless frontend-backend integration

**Phase 3 - Quality & Security:**

- 🧪 **QA Engineer**: Comprehensive test suites and quality assurance
- 🔒 **Security Engineer**: Security audits and vulnerability assessments
- 🏗️ **Infrastructure Engineer**: Docker, deployment configurations
- 📚 **Documentation Agent**: Technical documentation and guides

**Phase 4 - Intelligence & Analytics:**

- 🤖 **AI Prompt Engineer**: AI integration and prompt optimization
- 📊 **Data Engineer**: Analytics, data pipelines, and insights

**Phase 5 - Review & Validation:**

- 🔍 **Code Reviewer**: Code quality and best practices analysis
- 🤔 **Assumption Challenger**: Critical thinking and edge case identification
- ❤️ **User Empathy Agent**: User experience and accessibility insights

**Phase 6 - Release:**

- 🚀 **Release Manager**: Deployment strategy and release planning

## 🚀 Quick Start

### Installation

**Option 1: NPM Package (Recommended)**
```bash
# Install the package
npm install @oliverpople/agency-x

# Use directly with npx
npx subagents --feature "Your feature description"
```

**Option 2: Clone and Build**
```bash
# Clone the repository
git clone https://github.com/oliverpople/agency-x.git
cd agency-x

# Install dependencies
npm install

# Build the project
npm run build
```

### Environment Setup

Create a `.env` file:

```bash
# Required: LLM API Keys
ANTHROPIC_API_KEY=your-anthropic-api-key
OPENAI_API_KEY=your-openai-api-key

# Optional: Configuration
DEBUG=false
```

### Basic Usage

**Using NPM Package:**
```bash
# Generate a complete feature
npx subagents --feature "Build a user authentication system"

# Use OpenAI instead of Claude (default)
npx subagents --feature "Create a payment system" --llm openai

# OpenAI with reliable execution (recommended)
npx subagents --feature "Create a BI dashboard" --llm openai --concurrent 1

# With voice narration
npx subagents --feature "Create a dashboard with analytics" --voice

# Resume a previous session
npx subagents --resume SPEC-20250807-ABC123

# Verbose output for debugging
npx subagents --feature "Build an API" --verbose
```

**Using Local Build:**
```bash
# Generate a complete feature
node dist/cli/index.js --feature "Build a user authentication system"

# With voice narration
node dist/cli/index.js --feature "Create a dashboard with analytics" --voice
```

## 📖 CLI Options

| Flag           | Description                      | Example                     |
| -------------- | -------------------------------- | --------------------------- |
| `--feature`    | Feature description to build     | `"Create a payment system"` |
| `--resume`     | Resume from session ID           | `SPEC-20250807-ABC123`      |
| `--voice`      | Enable audio narration           | `--voice`                   |
| `--concurrent` | Max parallel agents (default: 5) | `--concurrent 3`            |
| `--verbose`    | Show detailed logs               | `--verbose`                 |
| `--llm`        | LLM provider (claude or openai, default: claude) | `--llm openai`  |
| `--help`       | Show help information            | `--help`                    |

## 🤖 LLM Provider Guidelines

### **Anthropic Claude (Default)**
- **Recommended Concurrency**: `--concurrent 3-5` (default: 5)
- **Best For**: Comprehensive analysis, detailed outputs, complex reasoning
- **Performance**: ~20-30 seconds with high reliability

### **OpenAI GPT**
- **Recommended Concurrency**: `--concurrent 1-2` for best reliability
- **Best For**: Code generation, structured outputs, faster responses
- **Performance**: ~40-60 seconds with sequential execution

**For Maximum Reliability with OpenAI:**
```bash
# 100% success rate (recommended)
npx subagents --llm openai --feature "your feature" --concurrent 1

# Faster with good reliability
npx subagents --llm openai --feature "your feature" --concurrent 2
```

**Why Different Concurrency?**
OpenAI's API architecture handles concurrent requests differently than Claude. Using `--concurrent 1` with OpenAI ensures all 16 agents complete successfully by avoiding race conditions and rate limiting issues.

## 📁 Output Structure

Each session generates a comprehensive JSON file in `./sessions/`:

```json
{
  "specId": "SPEC-20250807-ABC123",
  "featurePrompt": "Build a user authentication system",
  "spec": {
    "title": "User Authentication System",
    "userStories": [...],
    "acceptanceCriteria": [...]
  },
  "agents": {
    "productManager": { "output": "...", "completed": true },
    "frontendDeveloper": { "output": "React components...", "completed": true },
    "backendDeveloper": { "output": "API endpoints...", "completed": true },
    "qaEngineer": { "output": "Test suites...", "completed": true },
    // ... 12 more agents
  },
  "metadata": {
    "createdAt": "2025-08-07T08:00:00.000Z",
    "version": "1.0.0"
  }
}
```

## 💻 Programmatic Usage

```javascript
import { runOrchestrator } from "@oliverpople/agency-x";

const result = await runOrchestrator({
  feature: "Build a user dashboard",
  voice: false,
  maxConcurrent: 3,
  onProgress: (status) => {
    console.log(`Progress: ${status.completed}/${status.total}`);
  },
});

console.log("Generated session:", result.specId);
```

## 🎨 AI Assistant Integration

Agency-X outputs are designed to work seamlessly with AI coding assistants:

**Cursor AI:**
1. Generate project specs with Agency-X
2. Import the session JSON into your Cursor project
3. Use Cursor's AI to refine and enhance the generated code

**Claude Codebase:**
1. Run Agency-X to generate comprehensive specifications
2. Upload the session file to Claude for context
3. Ask Claude to adapt or extend the generated code

**Warp AI Terminal:**
1. Generate features using Agency-X CLI
2. Use Warp's AI to help implement deployment steps
3. Get terminal assistance for debugging and optimization

## 🧪 Testing

```bash
# Run all tests
npm test

# Run voice functionality tests
npm test -- src/__tests__/voice-simple.test.ts

# Test with voice activation (you'll hear audio)
npx jest src/__tests__/voice-simple.test.ts --verbose
```

## 🏗️ Architecture

### Agent Orchestration

Agents run in **dependency-based phases**:

```
Phase 1: Product Manager (defines requirements)
    ↓
Phase 2: Frontend & Backend Developers (parallel)
    ↓
Phase 3: Fullstack Integrator + UX + Copy (parallel)
    ↓
Phase 4: QA + Security + Infrastructure + Docs (parallel)
    ↓
Phase 5: AI + Data Engineers (parallel)
    ↓
Phase 6: Review + Validation Agents (parallel)
    ↓
Phase 7: Release Manager (final output)
```

### Error Recovery

- **Retry Logic**: Configurable retry attempts with exponential backoff
- **Critical Agents**: System fails fast if critical agents (Product, Dev, QA, Release) fail
- **Non-Critical Agents**: Continue execution if supporting agents fail
- **Session Persistence**: All progress saved automatically

### LLM Routing

- **Anthropic Claude**: Primary for most agents
- **OpenAI GPT**: Fallback and specialized tasks
- **Automatic Failover**: Seamless switching on rate limits/errors

## 📚 Documentation

- [API Documentation](docs/api.md)
- [Changelog](CHANGELOG.md)

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch: `git checkout -b feature-name`
3. Make your changes and add tests
4. Run tests: `npm test`
5. Commit your changes: `git commit -am 'Add feature'`
6. Push to the branch: `git push origin feature-name`
7. Submit a pull request

## 🐛 Troubleshooting

**Common Issues:**

- **Voice not working**: Install system TTS dependencies (`brew install espeak` on macOS)
- **API rate limits**: Reduce `--concurrent` flag or add delays
- **OpenAI agents failing**: Use `--concurrent 1` for 100% reliability with OpenAI
- **Memory issues**: Lower concurrency for large features
- **Network timeouts**: Check API keys and internet connection
- **Some agents not completing**: Try sequential execution with `--concurrent 1`

**Debug Mode:**

```bash
# Enable verbose logging
node dist/cli/index.js --feature "test" --verbose

# Check session files
ls -la sessions/
cat sessions/SPEC-*.json | jq '.metadata'
```

## 📈 Performance

- **Average Generation Time**: 20-30 seconds for complete features
- **Agent Success Rate**: 75-95% depending on complexity and API availability
- **Concurrent Agents**: Up to 10 parallel (recommended: 3-5)
- **Session File Size**: 10-50KB depending on feature complexity
- **Memory Usage**: ~100MB during peak orchestration
- **LLM Fallback**: Automatic provider switching for maximum reliability

## 🛠️ Roadmap

- [x] NPM package publication (@oliverpople/agency-x@6.0.5)
- [x] Smart LLM routing with automatic fallback
- [x] Robust error recovery and progress tracking
- [ ] Web dashboard for session management
- [ ] Additional LLM providers (Gemini, Cohere)
- [ ] Custom agent definitions
- [ ] Template library for common patterns
- [ ] Integration with popular IDEs (VS Code extension)
- [ ] Real-time collaboration features
- [ ] GitHub Actions for CI/CD workflows

## 📄 License

ISC © Oliver Pople

## 🙏 Acknowledgments

- Anthropic for Claude API
- OpenAI for GPT API
- The open-source community for inspiration and tools

---

**⚡ Transform your ideas into production-ready code with Agency-X**

Get started today and experience the future of AI-powered development!
