# IDE Bridge Documentation

## Overview

The IDE Bridge enables Task-engine to work independently from external API providers by connecting directly to your IDE's built-in AI agent through a WebSocket-to-stdio bridge. This eliminates the need for external API keys while maintaining all Task-engine functionality.

## Architecture

```
┌─────────────────┐    WebSocket    ┌─────────────────┐    stdio    ┌─────────────────┐
│                 │◄───────────────►│                 │◄───────────►│                 │
│   IDE Agent     │                 │  Bridge Server  │             │  MCP Server     │
│                 │                 │                 │             │                 │
└─────────────────┘                 └─────────────────┘             └─────────────────┘
```

### Components

1. **WebSocket Bridge Server** (`src/bridge/websocket-bridge.js`)
   - Listens for WebSocket connections from IDEs
   - Spawns MCP server processes for each connection
   - Routes messages bidirectionally between WebSocket and stdio

2. **IDE Agent Interface** (`src/bridge/ide-agent-interface.js`)
   - Abstracts communication with different IDE types
   - Handles IDE-specific protocols and capabilities
   - Provides unified interface for AI operations

3. **IDE AI Provider** (`src/ai-providers/ide-provider.js`)
   - Implements BaseAIProvider interface for IDE agents
   - Integrates with existing AI service layer
   - Supports all standard operations (generateText, streamText, generateObject)

4. **Bridge Configuration** (`src/bridge/bridge-config.js`)
   - Manages bridge settings and IDE detection
   - Handles migration modes and fallback behavior
   - Auto-detects IDE type and capabilities

## Installation & Setup

### 1. Install Dependencies

```bash
npm install ws@^8.18.0
```

### 2. Enable Bridge Mode

```bash
# Interactive migration wizard
task-master migrate-to-ide

# Or enable manually
npm run bridge-enable
```

### 3. Start Bridge Server

```bash
# Start bridge server
npm run bridge-start

# Or start with custom port
node src/bridge/bridge-server.js start --config .taskmaster/bridge-config.json
```

### 4. Configure IDE Integration

The bridge will auto-detect your IDE type, but you can specify it manually:

```bash
# Auto-detect IDE
node src/bridge/bridge-server.js detect-ide

# Or set manually in .taskmaster/bridge-config.json
{
  "ide": {
    "type": "cursor",  // cursor, vscode, windsurf
    "capabilities": ["text-generation", "code-completion", "code-analysis"]
  }
}
```

## Migration Modes

### Complete Migration
- Replaces all external providers with IDE agent
- No external API keys required
- Fastest and most independent setup

```bash
task-master migrate-to-ide --mode complete
```

### Gradual Migration
- Uses IDE as primary, keeps external providers as fallback
- Provides redundancy during transition
- Recommended for production environments

```bash
task-master migrate-to-ide --mode gradual
```

### IDE-First
- Uses IDE for main role only
- Keeps research and fallback as external providers
- Good for testing IDE integration

```bash
task-master migrate-to-ide --mode ide-first
```

## Configuration

### Bridge Configuration (`.taskmaster/bridge-config.json`)

```json
{
  "bridge": {
    "enabled": true,
    "port": 8765,
    "host": "localhost",
    "maxConnections": 10,
    "timeout": 30000
  },
  "ide": {
    "type": "cursor",
    "capabilities": ["text-generation", "code-completion"],
    "fallbackToExternal": true
  },
  "migration": {
    "migrationMode": "gradual",
    "fallbackBehavior": "external-api"
  }
}
```

### Model Configuration (`.taskmaster/config.json`)

After migration, your model configuration will use the IDE provider:

```json
{
  "models": {
    "main": {
      "provider": "ide",
      "modelId": "ide-agent",
      "maxTokens": 100000,
      "temperature": 0.2
    },
    "research": {
      "provider": "ide",
      "modelId": "ide-agent",
      "maxTokens": 8700,
      "temperature": 0.1
    },
    "fallback": {
      "provider": "anthropic",
      "modelId": "claude-3-5-sonnet",
      "maxTokens": 64000,
      "temperature": 0.2
    }
  }
}
```

## IDE-Specific Setup

### Cursor IDE

Cursor integration works through the built-in AI agent:

1. Ensure Cursor is running with AI features enabled
2. Bridge will auto-detect Cursor and connect to its agent
3. No additional configuration required

**Supported Features:**
- Text generation
- Code completion
- Code analysis
- File operations
- Project context

### VS Code

VS Code integration works through extensions:

1. Install GitHub Copilot or similar AI extension
2. Bridge will detect VS Code and available AI capabilities
3. May require extension-specific configuration

**Supported Features:**
- Text generation (via extensions)
- Code completion
- Extension API access

### Windsurf IDE

Windsurf integration supports multi-agent workflows:

1. Ensure Windsurf is running with AI features enabled
2. Bridge will auto-detect and connect to Windsurf agents
3. Supports advanced workflow automation

**Supported Features:**
- Text generation
- Code completion
- Multi-agent workflows
- Workflow automation

## Commands

### Bridge Management

```bash
# Start bridge server
npm run bridge-start
task-master-bridge start

# Check bridge status
npm run bridge-status
task-master-bridge status

# Enable/disable bridge
npm run bridge-enable
task-master-bridge enable

# Stop bridge server
task-master-bridge stop
```

### Migration Commands

```bash
# Interactive migration wizard
task-master migrate-to-ide

# Force migration without prompts
task-master migrate-to-ide --force

# Check migration status
task-master migrate-to-ide --status

# Rollback migration
task-master migrate-to-ide --rollback
```

## Troubleshooting

### Bridge Server Won't Start

1. Check if port is already in use:
   ```bash
   lsof -i :8765
   ```

2. Try different port:
   ```bash
   task-master-bridge start --config .taskmaster/bridge-config.json
   # Edit config to change port
   ```

3. Check bridge configuration:
   ```bash
   task-master-bridge status
   ```

### IDE Not Detected

1. Ensure IDE is running
2. Check IDE-specific processes:
   ```bash
   # For Cursor
   ps aux | grep -i cursor
   
   # For VS Code
   ps aux | grep -i code
   ```

3. Manually set IDE type:
   ```bash
   # Edit .taskmaster/bridge-config.json
   {
     "ide": {
       "type": "cursor"  // or vscode, windsurf
     }
   }
   ```

### Connection Issues

1. Check WebSocket connection:
   ```bash
   # Test WebSocket endpoint
   wscat -c ws://localhost:8765
   ```

2. Verify MCP server is running:
   ```bash
   npm run mcp-server
   ```

3. Check bridge logs for errors

### Fallback to External APIs

If IDE connection fails, Task-engine can fallback to external APIs:

1. Ensure fallback is enabled:
   ```json
   {
     "ide": {
       "fallbackToExternal": true
     },
     "migration": {
       "fallbackBehavior": "external-api"
     }
   }
   ```

2. Verify external API keys are still configured
3. Check fallback model configuration

## Performance Considerations

### Bridge Server
- Lightweight WebSocket server with minimal overhead
- Spawns separate MCP processes per connection
- Automatic cleanup of disconnected sessions

### IDE Integration
- Direct communication with IDE agent (no network latency)
- Leverages IDE's existing AI infrastructure
- No token limits or rate limiting from external APIs

### Memory Usage
- Bridge server: ~10-20MB base memory
- Per-connection MCP process: ~30-50MB
- IDE agent interface: ~5-10MB

## Security

### Local Communication
- All communication happens locally (no external network calls)
- WebSocket server binds to localhost only
- No API keys transmitted over network

### Process Isolation
- Each IDE connection gets isolated MCP process
- Bridge server runs with minimal privileges
- Automatic cleanup prevents resource leaks

### Configuration Security
- Bridge configuration stored locally
- No sensitive data in configuration files
- IDE agent access controlled by IDE's security model

## Advanced Configuration

### Custom IDE Integration

To add support for a new IDE:

1. Extend `IDEAgentInterface` class
2. Add detection logic to `BridgeConfig`
3. Implement IDE-specific communication protocol
4. Update supported IDE list in configuration

### Bridge Clustering

For high-availability setups:

1. Run multiple bridge servers on different ports
2. Use load balancer to distribute connections
3. Share configuration across bridge instances
4. Implement health checks for automatic failover

### Monitoring

Enable detailed logging and monitoring:

```json
{
  "logging": {
    "level": "debug",
    "bridgeEvents": true,
    "agentCommunication": true,
    "performance": true
  }
}
```

## Migration from External APIs

### Backup Strategy

Before migration:
1. Backup current configuration
2. Test IDE integration in development
3. Plan rollback procedure
4. Document current API usage

### Gradual Migration Steps

1. **Phase 1**: Enable bridge, keep external APIs
2. **Phase 2**: Switch main model to IDE agent
3. **Phase 3**: Switch research model to IDE agent
4. **Phase 4**: Remove external API dependencies

### Rollback Procedure

If migration needs to be reversed:

```bash
# Automatic rollback
task-master migrate-to-ide --rollback

# Manual rollback
# 1. Restore backup configuration
# 2. Disable bridge server
# 3. Verify external API keys
# 4. Test external provider functionality
```
