cline-sdk
v1.0.3
Published
Comprehensive SDK for Cline - AI-powered development assistant with database integration, execution modes, and custom functions
Maintainers
Readme
🚀 Cline SDK
Comprehensive AI Development Assistant SDK with Database Integration and Execution Control
✨ 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
npm install cline-sdkBasic Usage
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
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
sdk.setExecutionMode("ask")
await sdk.createTask("Explain how REST APIs work")
// AI provides explanations but cannot execute toolsPLAN Mode 📋 - Analysis Only
sdk.setExecutionMode("plan")
await sdk.createTask("Analyze my code and create an improvement plan")
// AI can read files and analyze but cannot modify anythingACT Mode ⚡ - Full Execution
sdk.setExecutionMode("act")
await sdk.createTask("Implement the planned improvements")
// AI has full access to all configured toolsManual Mode Switching
// 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
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
// 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
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 suggestionsoptimize: <prompt>- Alternative syntaximprove prompt: <prompt>- Detailed syntax
🎯 Custom Functions
Extend AI capabilities with your business logic:
// 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 '[email protected]'")📚 Table Knowledge System
Register business context for your database tables:
// 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
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
// 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
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
// 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:
# 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
# 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
# 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
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
sdk.setExecutionMode("act")
await sdk.createTask("Set up a new Express.js project with TypeScript")Code Review & Analysis
sdk.setExecutionMode("plan")
await sdk.createTask("Review my code for security vulnerabilities")Database Q&A
sdk.setExecutionMode("ask")
await sdk.createTask("What's the best way to optimize this query?")Data Migration
sdk.setExecutionMode("act")
await sdk.createTask("Migrate user data from old schema to new structure")Documentation Generation
await sdk.createTask("Generate API documentation from my database schema")📚 Documentation
- Complete Documentation - Comprehensive user guide
- AI Technical Reference - Technical documentation for AI integration
- Examples - Complete example collection
- API Reference - Detailed API documentation
🤝 Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
📄 License
Apache 2.0 - see 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
🔧 Explore: Example Collection
Built with ❤️ for developers who want to harness AI for productivity without sacrificing control or security.
