npm package: @latestgraviton/client
Description: Graviton MCP Client - Terminal agent for distributed task execution
Author: Graviton Team
Latest version: 1.1.0

# Graviton Terminal Agent

The Graviton Terminal Agent is a sophisticated client that connects to the Graviton MCP Server to execute distributed tasks as part of a coordinated multi-terminal AI development team.

## 🚀 Features

### Core Capabilities
- **MCP Protocol Support**: Full implementation of Model Context Protocol for Claude CLI integration
- **Advanced Connection Management**: Exponential backoff, adaptive retry strategies, network monitoring
- **Task Execution Engine**: Sandboxed execution with worker threads for parallel processing
- **Progress Reporting**: Real-time progress updates with detailed metrics
- **Specialization Profiles**: 11 pre-configured profiles for different development roles

### Specialization Profiles
- **Frontend**: React, Vue, Angular, UI/UX development
- **Backend**: Node.js, Python, Java, API development
- **Fullstack**: Complete web application development
- **DevOps**: Infrastructure, CI/CD, monitoring
- **Data**: Data engineering, analytics, machine learning
- **Testing**: QA, test automation, performance testing
- **Security**: Security analysis, penetration testing
- **Mobile**: iOS, Android, React Native development
- **AI/ML**: Machine learning, deep learning, NLP
- **Blockchain**: Smart contracts, DeFi, Web3
- **Generic**: General-purpose development tasks

## 📦 Installation

```bash
# Install dependencies
npm install

# Build the client
npm run build

# Link globally for CLI usage
npm link
```

## 🎯 Quick Start

### 1. Start the Graviton Server
First, ensure the Graviton server is running:
```bash
cd packages/server
npm run dev
```

### 2. Start a Terminal Agent

#### Using CLI
```bash
# Start with default profile
graviton-agent start

# Start with specific profile
graviton-agent start --profile frontend

# Start with custom server
graviton-agent start --server my-server.com --ws-port 8081 --api-port 8080

# Verbose mode for debugging
graviton-agent start --verbose
```

#### Programmatic Usage
```typescript
import { TerminalAgent, ProfileTemplate } from '@graviton/client';

const agent = new TerminalAgent({
  profile: ProfileTemplate.BACKEND,
  server: {
    url: 'localhost',
    wsPort: 8081,
    apiPort: 8080,
  },
  execution: {
    sandbox: true,
    workers: true,
    maxParallelTasks: 4,
  },
});

// Start the agent
await agent.start();

// Listen for events
agent.on('task:received', (task) => {
  console.log('New task:', task.taskId);
});

agent.on('task:completed', (result) => {
  console.log('Task completed:', result.taskId);
});
```

## 🛠️ CLI Commands

### Agent Management
```bash
# Start agent
graviton-agent start [options]
  -p, --profile <profile>  Agent profile
  -s, --server <url>       Server URL
  --ws-port <port>         WebSocket port
  --api-port <port>        API port
  -d, --detached          Run in background
  -v, --verbose           Verbose output

# Stop agent
graviton-agent stop

# Check status
graviton-agent status

# List tasks
graviton-agent tasks
graviton-agent tasks --all  # Include completed tasks
```

### Profile Management
```bash
# List available profiles
graviton-agent profile list

# Show profile details
graviton-agent profile show frontend
```

### Configuration
```bash
# Show configuration
graviton-agent config show

# Set configuration value
graviton-agent config set server.url my-server.com
graviton-agent config set server.wsPort 8081
graviton-agent config set profile backend
```

## 🏗️ Architecture

### Component Structure
```
Terminal Agent
├── MCP Client           # Protocol communication
├── Connection Manager   # Advanced retry logic
├── Task Executor       # Sandboxed execution
├── Progress Reporter   # Real-time updates
└── Profile Manager     # Capability management
```

### Task Execution Flow
1. **Task Reception**: Agent receives task from server
2. **Capability Matching**: Validates agent can handle the task
3. **Context Loading**: Loads required context into memory
4. **Sandboxed Execution**: Runs task in isolated environment
5. **Progress Reporting**: Sends real-time updates to server
6. **Result Submission**: Returns results and artifacts

## 🔧 Advanced Configuration

### Custom Profile
```typescript
import { ProfileFactory, AgentProfile } from '@graviton/client';

const customProfile: AgentProfile = {
  id: 'custom-agent',
  name: 'My Custom Agent',
  description: 'Specialized for specific tasks',
  capabilities: {
    languages: ['javascript', 'python', 'rust'],
    frameworks: ['nextjs', 'fastapi', 'actix'],
    tools: ['docker', 'kubernetes'],
    specializations: ['custom'],
    maxTokens: 200000,
    maxConcurrentTasks: 5,
    performanceScore: 90,
  },
  preferences: {
    preferredTaskTypes: ['api-development', 'optimization'],
    avoidTaskTypes: ['ui-design'],
    maxTaskDuration: 7200000, // 2 hours
    retryAttempts: 3,
    contextStrategy: ContextStrategy.COMPREHENSIVE,
    executionMode: ExecutionMode.PARALLEL,
  },
  metadata: {
    version: '1.0.0',
    environment: 'production',
    platform: process.platform,
    nodeVersion: process.version,
    created: new Date(),
    lastActive: new Date(),
    totalTasksCompleted: 0,
    totalTasksFailed: 0,
    averageCompletionTime: 0,
  },
};

const agent = new TerminalAgent({
  profile: customProfile,
  // ... other config
});
```

### Connection Strategies
```typescript
import { ConnectionManager, RetryStrategy } from '@graviton/client';

const connectionManager = new ConnectionManager({
  retryStrategy: RetryStrategy.ADAPTIVE, // Adjusts based on network
  maxRetries: 15,
  baseDelay: 500,
  maxDelay: 60000,
  jitterFactor: 0.3,
  networkMonitoring: true,
});
```

### Sandbox Configuration
```typescript
const agent = new TerminalAgent({
  // ... other config
  execution: {
    sandbox: {
      enabled: true,
      memory: 1024 * 1024 * 1024, // 1GB
      cpu: 2,
      timeout: 60000, // 60s
      allowNetwork: true,
      allowFileSystem: true,
      workingDirectory: '/workspace',
    },
    workers: {
      enabled: true,
      maxWorkers: 8,
      workerTimeout: 120000,
    },
  },
});
```

## 📊 Monitoring & Metrics

### Real-time Metrics
```typescript
agent.on('metrics', (metrics) => {
  console.log('Memory:', metrics.memory);
  console.log('CPU:', metrics.cpu);
  console.log('Active Tasks:', metrics.activeTasks);
});
```

### Progress Tracking
```typescript
agent.on('progress', (update) => {
  console.log(`Task ${update.taskId}: ${update.progress}% - ${update.message}`);
});
```

### Health Checks
```typescript
connectionManager.on('health:check', (health) => {
  console.log('Latency:', health.latency, 'ms');
  console.log('Status:', health.status);
});
```

## 🔌 Integration with Claude CLI

The Terminal Agent is designed to work seamlessly with Claude CLI instances:

1. **MCP Protocol**: Full support for Model Context Protocol
2. **Context Synchronization**: Automatic context sharing between terminals
3. **Task Distribution**: Intelligent routing based on capabilities
4. **Result Aggregation**: Automatic collection and merging of results

### Example Integration
```bash
# Terminal 1 - Frontend Specialist
graviton-agent start --profile frontend

# Terminal 2 - Backend Specialist
graviton-agent start --profile backend

# Terminal 3 - Testing Specialist
graviton-agent start --profile testing

# Master Terminal - Submit project
curl -X POST http://localhost:8080/api/tasks/submit \
  -H "Content-Type: application/json" \
  -d '{
    "plan": "Build a full-stack e-commerce application",
    "requirements": {
      "frontend": ["react", "tailwindcss"],
      "backend": ["nodejs", "postgresql"],
      "testing": ["jest", "cypress"]
    }
  }'
```

## 🧪 Testing

```bash
# Run unit tests
npm test

# Run integration tests
npm run test:integration

# Run with coverage
npm run test:coverage
```

## 🐛 Troubleshooting

### Connection Issues
```bash
# Check server connectivity
curl http://localhost:8080/api/health

# Verify WebSocket connection
wscat -c ws://localhost:8081

# Check agent logs
graviton-agent start --verbose
```

### Task Execution Issues
- Verify agent capabilities match task requirements
- Check available memory and CPU resources
- Review sandbox permissions for file/network access
- Examine task logs in verbose mode

### Performance Optimization
- Adjust `maxConcurrentTasks` based on system resources
- Configure appropriate `maxTokens` for context management
- Use specialized profiles for better task routing
- Enable worker threads for CPU-intensive tasks

## 📄 License

MIT

## 🤝 Contributing

Contributions are welcome! Please read our contributing guidelines and submit pull requests to our repository.

## 📚 Additional Resources

- [Graviton Server Documentation](../server/README.md)
- [MCP Protocol Specification](../protocol/README.md)
- [API Reference](../../docs/api.md)
- [Architecture Overview](../../docs/architecture.md)