# 🚀 Cline SDK

**Comprehensive AI Development Assistant SDK with Database Integration and Execution Control**

[![npm version](https://badge.fury.io/js/cline-sdk.svg)](https://badge.fury.io/js/cline-sdk)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)

## ✨ Features

- **🤖 AI Integration**: Anthropic Claude API with full tool support
- **🔄 Execution Modes**: Ask/Plan/Act modes for different use cases
- **🔧 Prompt Optimization**: World's first built-in prompt analysis and improvement system
- **🐘 PostgreSQL Support**: Complete database integration with Row Level Security
- **📚 Table Knowledge**: Register business context for AI-powered database understanding
- **🎯 Custom Functions**: Extend AI capabilities with your own business logic
- **☁️ Cloud Storage**: Supabase integration for distributed file operations
- **📡 Event System**: Real-time events for AI thinking, chat responses, and execution states
- **🔄 Auto-Retry**: Intelligent retry mechanism with configurable delays
- **🛡️ Security**: Comprehensive permissions and access controls
- **💰 Cost Tracking**: Built-in API cost monitoring and optimization

## 🚀 Quick Start

### Installation

```bash
npm install cline-sdk
```

### Basic Usage

```javascript
const { CompleteClineSDK } = require('cline-sdk')

const sdk = new CompleteClineSDK({
    apiProvider: "anthropic",
    apiKey: process.env.ANTHROPIC_API_KEY,
    enabledTools: ["Write", "Read", "Bash"],
    workingDirectory: process.cwd()
})

// Create a simple task
await sdk.createTask("Create a README.md file for my project")
```

### With Database

```javascript
const sdk = new CompleteClineSDK({
    apiProvider: "anthropic",
    apiKey: process.env.ANTHROPIC_API_KEY,
    enableDatabase: true,
    database: {
        host: "localhost",
        port: 5432,
        database: "myapp",
        username: "user",
        password: "password",
        permissions: {
            allowRead: true,
            allowWrite: true,
            allowDelete: false
        }
    }
})

await sdk.createTask("Analyze my database schema and suggest optimizations")

// Use prompt optimization
const optimization = sdk.analyzePrompt("help me fix this")
console.log(sdk.formatOptimizationResults(optimization))
```

## 🔄 Execution Modes

Control AI capabilities with three distinct modes:

### ASK Mode ❓ - Questions Only
```javascript
sdk.setExecutionMode("ask")
await sdk.createTask("Explain how REST APIs work")
// AI provides explanations but cannot execute tools
```

### PLAN Mode 📋 - Analysis Only  
```javascript
sdk.setExecutionMode("plan")
await sdk.createTask("Analyze my code and create an improvement plan")
// AI can read files and analyze but cannot modify anything
```

### ACT Mode ⚡ - Full Execution
```javascript
sdk.setExecutionMode("act")
await sdk.createTask("Implement the planned improvements")
// AI has full access to all configured tools
```

### Manual Mode Switching
```javascript
// Direct mode switching via SDK
sdk.setExecutionMode("plan")
await sdk.createTask("Analyze this database schema")

// Via explicit commands in task text
await sdk.createTask("/plan - Analyze this database schema")
await sdk.createTask("/ask - Explain this code")
await sdk.createTask("/act - Execute the plan")

// Programmatic mode switching
sdk.setExecutionMode("ask")  // Question-only mode
sdk.setExecutionMode("plan") // Analysis mode  
sdk.setExecutionMode("act")  // Full execution mode
```

## 🔧 Prompt Optimization

**World's first SDK with built-in prompt optimization!**

### Analyze and Improve Prompts
```javascript
const { PromptOptimizer } = require('cline-sdk')

const optimizer = new PromptOptimizer()
const result = optimizer.optimizePrompt("help me fix this")

console.log(`Clarity: ${result.analysis.clarity}/10`)
console.log(`Overall Score: ${result.analysis.overall}/10`)
console.log(`Improved: ${result.improvedPrompt}`)
```

### SDK Integration
```javascript
// Direct analysis
const optimization = sdk.analyzePrompt("make a website")
console.log(sdk.formatOptimizationResults(optimization))

// Using commands
await sdk.createTask("/optimize create a REST API")
await sdk.createTask("/improve help me code")
```

### Event-Driven Optimization
```javascript
sdk.on('prompt:optimization:started', (prompt) => {
    console.log(`Analyzing: ${prompt}`)
})

sdk.on('prompt:optimization:completed', (result) => {
    console.log(`Score improved from ${result.analysis.overall}/10`)
})
```

### Optimization Commands
- **`/optimize <prompt>`** - Analyze and improve prompt
- **`/improve <prompt>`** - Get improvement suggestions  
- **`optimize: <prompt>`** - Alternative syntax
- **`improve prompt: <prompt>`** - Detailed syntax

## 🎯 Custom Functions

Extend AI capabilities with your business logic:

```javascript
// Register a custom function
sdk.registerFunction(
    {
        name: "validateEmail",
        description: "Validate email addresses with business rules",
        category: "validation",
        parameters: [
            { name: "email", type: "string", required: true },
            { name: "checkDomain", type: "boolean", optional: true }
        ]
    },
    async (email, checkDomain = false) => {
        // Your validation logic
        const isValid = /^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$/.test(email)
        return { email, isValid, timestamp: new Date().toISOString() }
    }
)

// AI can now use the function
await sdk.createTask("Validate the email 'user@example.com'")
```

## 📚 Table Knowledge System

Register business context for your database tables:

```javascript
// Register table knowledge
sdk.addTable({
    schemaName: "public",
    tableName: "users",
    businessName: "User Accounts",
    description: "Core user authentication and profile data",
    businessPurpose: "Manages user login, permissions, and profile information",
    domain: "user-management",
    
    columns: [
        {
            name: "email",
            dataType: "varchar",
            description: "User's email address for login",
            businessPurpose: "Primary authentication method",
            privacy: { isPII: true, gdprRelevant: true },
            businessRules: ["Must be unique", "Required for login"]
        }
    ],
    
    security: { requiresRLS: true, auditingRequired: true },
    tags: ["core", "authentication", "pii"]
})

// AI now understands your business context
await sdk.createTask("Analyze our user management system for GDPR compliance")
```

## 🐘 PostgreSQL Integration

### Database Configuration

```javascript
const sdk = new CompleteClineSDK({
    enableDatabase: true,
    database: {
        host: "localhost",
        port: 5432,
        database: "myapp",
        username: "app_user", 
        password: "secure_password",
        ssl: true,
        permissions: {
            allowRead: true,
            allowWrite: true,
            allowDelete: false,
            allowSchemaChanges: false,
            allowRLSManagement: true,
            restrictedTables: ["admin_logs", "sensitive_data"],
            allowedTables: [] // Empty = all tables except restricted
        }
    }
})
```

### Database Operations

```javascript
// Schema exploration
await sdk.createTask("Show me all tables and their relationships")

// Safe queries with parameterization
await sdk.createTask("Find all users with more than 5 orders")

// Row Level Security
await sdk.createTask("Create RLS policies for the users table")
```

## ☁️ Supabase Cloud Storage

```javascript
const sdk = new CompleteClineSDK({
    storageType: "supabase",
    supabase: {
        url: process.env.SUPABASE_URL,
        anonKey: process.env.SUPABASE_ANON_KEY,
        bucketName: "my-files",
        projectPath: "sdk-uploads/"
    }
})

// Files are automatically uploaded to cloud storage
await sdk.createTask("Create a configuration file and upload it")
```

## 📊 Event System & Monitoring

```javascript
// Task events
sdk.on("task:created", (task) => {
    console.log(`New task: ${task.id}`)
})

sdk.on("task:completed", (task) => {
    console.log(`Task completed: ${task.id}`)
    console.log(`Cost: $${task.totalCost}`)
})

// AI Thinking Events (like original Cline)
sdk.on("ai:thinking", (event) => {
    console.log(`AI: ${event.stage} - ${event.content}`)
})

sdk.on("chat:response", (event) => {
    console.log(`Response: ${event.content}`)
})

// Execution State Events
sdk.on("execution:state:changed", (event) => {
    console.log(`State: ${event.state}`)
})

// Tool Execution Events
sdk.on("tool:starting", (event) => {
    console.log(`Starting: ${event.toolName}`)
})

sdk.on("tool:completed", (event) => {
    console.log(`Completed: ${event.toolName} (${event.executionTime}ms)`)
})

// Retry Events
sdk.on("retry:attempt", (event) => {
    console.log(`Retry ${event.attemptNumber}: ${event.error}`)
})

// Mode changes
sdk.on("mode:changed", (newMode, oldMode) => {
    console.log(`Mode: ${oldMode} → ${newMode}`)
})

// Cost tracking
const costs = sdk.getTotalCosts()
console.log(`Total cost: $${costs.totalCost}`)
console.log(`Average per task: $${costs.averageCostPerTask}`)
```

## 🛡️ Security & Permissions

### Database Security
- **Row Level Security (RLS)**: Automatic policy management
- **Parameterized Queries**: SQL injection prevention
- **Table Restrictions**: Fine-grained access control
- **Permission Levels**: Read/Write/Delete/Schema control

### Execution Control
- **Mode Restrictions**: Tool availability by execution mode
- **Tool Filtering**: Automatic tool blocking in restricted modes
- **API Key Protection**: Secure credential management
- **Audit Logging**: Comprehensive operation tracking

## 📖 Examples

Run comprehensive examples to explore all features:

```bash
# Basic SDK usage
npm run example:basic

# Execution modes (Ask/Plan/Act)
npm run example:modes

# Custom functions
npm run example:functions

# Database integration
npm run example:database

# Table knowledge system
npm run example:knowledge

# Supabase cloud storage
npm run example:supabase

# Complete workflow
npm run example:workflow

# Event monitoring (AI thinking, chat responses, etc.)
npm run example:events

# Retry system with automatic error recovery
npm run example:retry

# Prompt optimization and analysis
npm run example:optimization
```

## 🧪 Testing

```bash
# PostgreSQL integration tests
npm run test:postgres

# Database integration tests
npm run test:integration

# Set up test database
npm run db:setup
npm run db:cleanup
npm run db:reset
```

## 📋 Configuration

### Environment Variables
```bash
# API Configuration
ANTHROPIC_API_KEY=sk-ant-...

# Database Configuration
DB_HOST=localhost
DB_PORT=5432
DB_NAME=myapp
DB_USER=user
DB_PASSWORD=password

# Supabase Configuration (optional)
SUPABASE_URL=https://xyz.supabase.co
SUPABASE_ANON_KEY=eyJ...
SUPABASE_SERVICE_KEY=eyJ... # Optional: Service role key for admin access
SUPABASE_BUCKET=cline-files
SUPABASE_PROJECT_PATH=sdk-files/
```

### Full Configuration
```javascript
const config = {
    // API
    apiProvider: "anthropic",
    apiKey: process.env.ANTHROPIC_API_KEY,
    model: "claude-3-5-sonnet-20241022",
    
    // Execution
    executionMode: "act", // "ask", "plan", "act"
    enabledTools: ["Write", "Read", "Bash", "CustomFunction"],
    workingDirectory: process.cwd(),
    
    // Storage
    storageType: "local", // "local" or "supabase"
    
    // Database (optional)
    enableDatabase: true,
    database: { /* ... */ },
    
    // Functions (optional)
    enableCustomFunctions: true,
    
    // Advanced
    customInstructions: "Additional AI instructions...",
    maxRetries: 3,
    timeoutMs: 30000
}
```

## 🔍 Use Cases

### Development Automation
```javascript
sdk.setExecutionMode("act")
await sdk.createTask("Set up a new Express.js project with TypeScript")
```

### Code Review & Analysis
```javascript
sdk.setExecutionMode("plan")
await sdk.createTask("Review my code for security vulnerabilities")
```

### Database Q&A
```javascript
sdk.setExecutionMode("ask")
await sdk.createTask("What's the best way to optimize this query?")
```

### Data Migration
```javascript
sdk.setExecutionMode("act")
await sdk.createTask("Migrate user data from old schema to new structure")
```

### Documentation Generation
```javascript
await sdk.createTask("Generate API documentation from my database schema")
```

## 📚 Documentation

- **[Complete Documentation](./DOCUMENTATION.md)** - Comprehensive user guide
- **[AI Technical Reference](./AI_TECHNICAL_REFERENCE.md)** - Technical documentation for AI integration
- **[Examples](./examples/)** - Complete example collection
- **[API Reference](./API_REFERENCE.md)** - Detailed API documentation

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request

## 📄 License

Apache 2.0 - see [LICENSE](./LICENSE) file for details.

## 🆘 Support

- **Documentation**: Check the comprehensive docs
- **Examples**: Run the example scripts
- **Issues**: Create a GitHub issue
- **Tests**: Verify with test suite

---

**Transform your development workflow with AI-powered automation that grows with your needs.**

🚀 **Get started**: `npm install cline-sdk`  
📖 **Learn more**: [Full Documentation](./DOCUMENTATION.md)  
🔧 **Explore**: [Example Collection](./examples/)  

*Built with ❤️ for developers who want to harness AI for productivity without sacrificing control or security.*