# Cline SDK - AI Technical Reference

**Technical documentation for AI systems integrating with the Cline SDK**

## Overview

The Cline SDK is a comprehensive TypeScript/JavaScript library for building AI-powered development assistants with database integration, execution control, and extensible functionality.

## Core Architecture

### Class Hierarchy
```typescript
CompleteClineSDK extends EventEmitter
├── ConfigManager: ClineConfigManager
├── AnthropicClient: API communication
├── Tools: Map<string, Tool>
├── FunctionRegistry: Custom function management
├── PostgreSQLManager: Database operations
├── TableKnowledgeManager: Business context storage
└── ExecutionMode: "ask" | "plan" | "act"
```

### Primary Interfaces

```typescript
interface ClineConfig {
    apiProvider: "anthropic"
    apiKey: string
    model?: string
    enabledTools: string[]
    executionMode?: ExecutionMode
    workingDirectory: string
    storageType: "local" | "supabase"
    enableDatabase?: boolean
    database?: PostgreSQLConfig
    enableCustomFunctions?: boolean
    customInstructions?: string
}

interface ClineTask {
    id: string
    created: number
    text: string
    images: string[]
    files: string[]
    status: "running" | "completed" | "error" | "cancelled"
    messages: ClineMessage[]
    tokensIn: number
    tokensOut: number
    totalCost: number
    costCalculations: CostCalculation[]
}

interface ClineMessage {
    ts: number
    type: "say" | "tool" | "ask"
    say?: "user" | "assistant"
    text?: string
    images?: string[]
    toolName?: string
    toolInput?: any
    toolResult?: any
    costCalculation?: CostCalculation
}
```

## Execution Modes

### Mode Definitions
```typescript
type ExecutionMode = "ask" | "plan" | "act"

const MODE_DEFINITIONS: Record<ExecutionMode, ModeConfiguration> = {
    ask: {
        allowedTools: [],
        systemPromptAddition: "IMPORTANT: You are in ASK MODE - you can only provide information...",
        autoSwitchEnabled: true
    },
    plan: {
        allowedTools: ["Read", "DatabaseSchema"],
        systemPromptAddition: "You are in PLAN MODE - you can inspect and analyze...",
        autoSwitchEnabled: true
    },
    act: {
        allowedTools: ["Write", "Read", "Bash", "DatabaseQuery", "DatabaseSchema", "DatabaseRLS", "CustomFunction"],
        systemPromptAddition: "You are in ACT MODE - you have full access...",
        autoSwitchEnabled: true
    }
}
```

### Mode Switching Logic
```typescript
function parseModeSwitch(userInput: string): ExecutionMode | null {
    const input = userInput.toLowerCase().trim()
    
    // Direct commands
    if (input === "/ask" || input.includes("switch to ask mode")) return "ask"
    if (input === "/plan" || input.includes("switch to plan mode")) return "plan"
    if (input === "/act" || input.includes("switch to act mode")) return "act"
    
    // Natural language detection
    if (input.includes("only answer questions") || input.includes("don't execute")) return "ask"
    if (input.includes("create a plan") || input.includes("analyze but don't execute")) return "plan"
    if (input.includes("execute") || input.includes("do it")) return "act"
    
    return null
}
```

## Tool System

### Tool Interface
```typescript
interface Tool {
    getDefinition(): ToolDefinition
    execute(input: any): Promise<any>
}

interface ToolDefinition {
    name: string
    description: string
    input_schema: {
        type: "object"
        properties: Record<string, any>
        required?: string[]
    }
}
```

### Available Tools

#### File Operations
- **WriteTool**: File creation and modification
- **ReadTool**: File reading and content retrieval
- **SupabaseWriteTool**: Cloud file operations
- **SupabaseReadTool**: Cloud file retrieval

#### System Operations
- **BashTool**: Command execution with safety controls

#### Database Operations
- **DatabaseQueryTool**: SQL query execution with parameterization
- **DatabaseSchemaTool**: Schema introspection and metadata
- **DatabaseRLSTool**: Row Level Security management

#### Custom Operations
- **CustomFunctionTool**: User-defined function execution

### Tool Execution Flow
```typescript
private async executeTool(task: ClineTask, toolName: string, input: any, toolId: string): Promise<void> {
    // 1. Mode restriction check
    if (!this.isToolAllowedInMode(toolName)) {
        // Return mode restriction error
        return
    }
    
    // 2. Tool existence validation
    const tool = this.tools.get(toolName)
    if (!tool) throw new Error(`Tool not found: ${toolName}`)
    
    // 3. Execute with error handling
    try {
        const result = await tool.execute(input)
        // Add success message to task
    } catch (error) {
        // Add error message to task
    }
}
```

## Database Integration

### PostgreSQL Manager
```typescript
class PostgreSQLManager {
    private pool: Pool
    private permissions: DatabasePermissions
    
    async query(sql: string, params?: any[]): Promise<QueryResult>
    async getSchemas(): Promise<string[]>
    async getTables(schema: string): Promise<TableInfo[]>
    async getTableSchema(schema: string, table: string): Promise<TableSchema>
    async testConnection(): Promise<ConnectionResult>
    async createRLSPolicy(table: string, policy: RLSPolicy): Promise<void>
    async enableRLS(table: string): Promise<void>
    getSchemaContext(): string
    close(): Promise<void>
}
```

### Permission System
```typescript
interface DatabasePermissions {
    allowRead: boolean
    allowWrite: boolean
    allowDelete: boolean
    allowSchemaChanges: boolean
    allowRLSManagement: boolean
    restrictedTables: string[]
    allowedTables: string[]
}
```

### Query Safety
- All queries use parameterized statements ($1, $2, etc.)
- SQL injection prevention through pg library
- Permission checking before query execution
- Table access validation against allow/restrict lists

## Table Knowledge System

### Knowledge Structure
```typescript
interface TableKnowledge {
    schemaName: string
    tableName: string
    businessName: string
    description: string
    businessPurpose: string
    domain?: string
    columns: ColumnKnowledge[]
    relationships?: TableRelationships
    businessRules?: BusinessRule[]
    commonUseCases?: UseCase[]
    dataLifecycle?: DataLifecycle
    performance?: PerformanceInfo
    security?: SecurityInfo
    tags?: string[]
}

interface ColumnKnowledge {
    name: string
    dataType: string
    description: string
    businessPurpose: string
    validation?: ValidationRules
    privacy?: PrivacyInfo
    businessRules?: string[]
    examples?: string[]
    relationships?: ColumnRelationships
    commonQueries?: string[]
}
```

### Knowledge Manager API
```typescript
class TableKnowledgeManager {
    private knowledgeBase: Map<string, TableKnowledge>
    private dbManager?: PostgreSQLManager
    
    addTable(knowledge: Partial<TableKnowledge>, options?: TableRegistrationOptions): void
    addColumn(schemaName: string, tableName: string, columnKnowledge: ColumnKnowledge): void
    addTables(tables: Partial<TableKnowledge>[], options?: TableRegistrationOptions): void
    getTableKnowledge(schemaName: string, tableName: string): TableKnowledge | undefined
    getAllTables(): TableKnowledge[]
    searchTables(query: SearchQuery): TableKnowledge[]
    generateKnowledgeContext(includeOnlyTables?: string[]): string
    exportKnowledge(): string
    importKnowledge(jsonData: string): void
    validateKnowledge(schemaName: string, tableName: string): Promise<ValidationResult>
    getStats(): KnowledgeStats
    clearKnowledge(): void
}
```

### AI Context Generation
The knowledge system generates structured context for AI consumption:

```
# Database Business Knowledge

## Domain: customer-management

### Customer Accounts (public.customers)
**Purpose:** Manage customer relationships, personalization, and order history
**Description:** Customer account information including personal details and preferences

**Columns:**
- **customer_id** (uuid): Unique identifier for each customer
  - Business Purpose: Primary key that connects customers to orders, reviews, and preferences
  - Business Rules: UUID v4 format; Immutable after creation

- **email** (varchar): Customer's email address for login and communication
  - Business Purpose: Primary authentication method and marketing communication channel
  - ⚠️ Contains PII (Personal Identifiable Information)
  - Business Rules: Must be unique across all customers; Required for account creation
```

## Custom Functions System

### Function Registration
```typescript
interface FunctionDefinition {
    name: string
    description: string
    category: string
    parameters: FunctionParameter[]
}

interface FunctionParameter {
    name: string
    type: "string" | "number" | "boolean" | "object" | "array"
    description: string
    required?: boolean
    optional?: boolean
    default?: any
}

class FunctionRegistry {
    register(definition: FunctionDefinition, implementation: (...args: any[]) => any): void
    unregister(name: string): boolean
    execute(name: string, args: any[]): Promise<any>
    getFunctionNames(): string[]
    getStats(): FunctionStats
    clear(): void
}
```

### Function Execution
```typescript
// Custom function tool execution
async execute(input: { functionName: string, parameters: any[] }): Promise<any> {
    try {
        const result = await this.registry.execute(input.functionName, input.parameters)
        return {
            success: true,
            result,
            functionName: input.functionName,
            executedAt: new Date().toISOString()
        }
    } catch (error) {
        return {
            success: false,
            error: error.message,
            functionName: input.functionName
        }
    }
}
```

## Event System

### Event Types
```typescript
interface ClineEvents {
    "task:created": (task: ClineTask) => void
    "task:updated": (task: ClineTask) => void
    "task:completed": (task: ClineTask) => void
    "task:error": (task: ClineTask, error: Error) => void
    "message:added": (message: ClineMessage) => void
    "state:changed": (state: ClineState) => void
    "mode:changed": (mode: ExecutionMode, previousMode: ExecutionMode) => void
}
```

### Event Flow
1. Task creation → `task:created`
2. AI processing → `message:added` for each response
3. Tool execution → `message:added` for each tool result
4. Task completion → `task:completed`
5. State changes → `state:changed`

## API Integration

### Anthropic Claude Integration
```typescript
class AnthropicClient {
    private config: ClineConfig
    
    async sendMessage(
        messages: AnthropicMessage[], 
        tools: ToolDefinition[], 
        systemPrompt: string
    ): Promise<AnthropicResponse>
}

interface AnthropicMessage {
    role: "user" | "assistant"
    content: string
}

interface AnthropicResponse {
    content: ContentBlock[]
    usage: TokenUsage
}
```

### System Prompt Construction
The SDK dynamically builds system prompts incorporating:
1. Base Cline identity and capabilities
2. Current execution mode instructions
3. Working directory information
4. Database connection details and permissions
5. Registered table knowledge context
6. Available tools list
7. Custom instructions

```typescript
private buildSystemPrompt(): string {
    const config = this.configManager.getConfig()
    const modeConfig = MODE_DEFINITIONS[this.executionMode]
    
    let prompt = `You are Cline, an AI assistant...
Current working directory: ${config.workingDirectory}
${modeConfig.systemPromptAddition}`
    
    // Add database context
    if (config.enableDatabase && this.databaseManager) {
        prompt += `\nDatabase Connection: ${config.database.host}:${config.database.port}/${config.database.database}`
        const knowledgeContext = this.tableKnowledgeManager.generateKnowledgeContext()
        if (knowledgeContext.length > 100) {
            prompt += `\n\n${knowledgeContext}`
        }
    }
    
    // Add available tools
    prompt += `\nYou have access to the following tools:\n`
    for (const toolName of config.enabledTools) {
        if (this.isToolAllowedInMode(toolName)) {
            const tool = this.tools.get(toolName)
            if (tool?.getDefinition) {
                const def = tool.getDefinition()
                prompt += `- ${def.name}: ${def.description}\n`
            }
        }
    }
    
    return prompt
}
```

## Cost Tracking

### Cost Calculation
```typescript
interface CostCalculation {
    provider: string
    model: string
    input_tokens: number
    output_tokens: number
    total_tokens: number
    input_cost_usd: number
    output_cost_usd: number
    total_cost_usd: number
    timestamp: string
    cost_per_1k_input: number
    cost_per_1k_output: number
}

class CostCalculator {
    static calculateCost(provider: string, model: string, usage: TokenUsage): CostCalculation
    static getPricingInfo(provider: string, model: string): PricingInfo | null
    static setCustomPricing(provider: string, model: string, pricing: PricingInfo): void
    static formatCost(calculation: CostCalculation): string
}
```

## Storage Abstraction

### Storage Interface
```typescript
interface StorageBackend {
    write(path: string, content: string): Promise<StorageResult>
    read(path: string): Promise<StorageResult>
    exists(path: string): Promise<boolean>
    delete(path: string): Promise<StorageResult>
    list(path: string): Promise<string[]>
}
```

### Implementations
- **LocalStorage**: File system operations
- **SupabaseStorage**: Cloud storage with public URLs

## Error Handling

### Error Types
```typescript
class ClineError extends Error {
    constructor(message: string, public code: string, public details?: any) {
        super(message)
    }
}

// Common error codes
const ERROR_CODES = {
    INVALID_CONFIG: "INVALID_CONFIG",
    API_ERROR: "API_ERROR", 
    TOOL_ERROR: "TOOL_ERROR",
    DATABASE_ERROR: "DATABASE_ERROR",
    PERMISSION_DENIED: "PERMISSION_DENIED",
    MODE_RESTRICTION: "MODE_RESTRICTION"
}
```

### Error Recovery
- Automatic retry for transient failures
- Graceful degradation for missing features
- Detailed error context in responses
- Event emission for error monitoring

## Performance Considerations

### Connection Pooling
```typescript
// PostgreSQL connection pool configuration
const poolConfig = {
    host: config.host,
    port: config.port,
    database: config.database,
    user: config.username,
    password: config.password,
    max: config.maxConnections || 10,
    idleTimeoutMillis: config.idleTimeoutMillis || 30000,
    connectionTimeoutMillis: config.connectionTimeoutMillis || 5000
}
```

### Memory Management
- Automatic cleanup of completed tasks
- Bounded message history
- Efficient knowledge storage with Map structures
- Connection pooling to prevent resource leaks

### Optimization Strategies
- Lazy loading of optional components
- Efficient tool filtering by mode
- Minimal API calls through batching
- Caching of database schema information

## Security Model

### Multi-layered Security
1. **API Key Protection**: Secure credential storage
2. **Database Permissions**: Granular access control
3. **Mode Restrictions**: Tool availability by execution mode
4. **SQL Injection Prevention**: Parameterized queries
5. **Table Access Control**: Allow/deny lists
6. **PII Handling**: Privacy-aware data processing

### Row Level Security (RLS)
```typescript
// RLS policy creation
await dbManager.createRLSPolicy("users", {
    name: "user_isolation",
    command: "SELECT",
    using: "auth.uid() = user_id"
})

// RLS enabling
await dbManager.enableRLS("sensitive_table")
```

## Integration Patterns

### Middleware Pattern
```typescript
class MiddlewareManager {
    private middlewares: Middleware[] = []
    
    use(middleware: Middleware): void
    async execute(context: ExecutionContext): Promise<void>
}
```

### Plugin Architecture
```typescript
interface Plugin {
    name: string
    version: string
    install(sdk: CompleteClineSDK): void
    uninstall(sdk: CompleteClineSDK): void
}
```

### Event-Driven Architecture
```typescript
// Event bus for loose coupling
class EventBus extends EventEmitter {
    emit(event: string, ...args: any[]): boolean
    on(event: string, listener: (...args: any[]) => void): this
    off(event: string, listener: (...args: any[]) => void): this
}
```

## Testing Framework

### Unit Testing
```typescript
// Mock implementations for testing
class MockPostgreSQLManager extends PostgreSQLManager {
    async query(sql: string, params?: any[]): Promise<QueryResult> {
        return { success: true, rows: [], rowCount: 0 }
    }
}

// Test utilities
class TestUtils {
    static createMockSDK(config?: Partial<ClineConfig>): CompleteClineSDK
    static createMockTask(options?: Partial<ClineTask>): ClineTask
    static waitForTaskCompletion(sdk: CompleteClineSDK): Promise<ClineTask>
}
```

### Integration Testing
```typescript
// Database test setup
async function setupTestDatabase(): Promise<void> {
    const client = new Client(testDbConfig)
    await client.connect()
    await client.query(`
        CREATE TABLE IF NOT EXISTS test_users (
            id UUID PRIMARY KEY,
            email VARCHAR(255) UNIQUE,
            created_at TIMESTAMP DEFAULT NOW()
        )
    `)
    await client.end()
}
```

## Deployment Considerations

### Environment Configuration
```typescript
// Production configuration
const productionConfig: ClineConfig = {
    apiProvider: "anthropic",
    apiKey: process.env.ANTHROPIC_API_KEY!,
    enabledTools: ["Write", "Read", "DatabaseQuery"],
    executionMode: "act",
    database: {
        host: process.env.DB_HOST!,
        port: parseInt(process.env.DB_PORT!),
        database: process.env.DB_NAME!,
        username: process.env.DB_USER!,
        password: process.env.DB_PASSWORD!,
        ssl: true,
        maxConnections: 20,
        permissions: {
            allowRead: true,
            allowWrite: true,
            allowDelete: false,
            allowSchemaChanges: false,
            allowRLSManagement: false,
            restrictedTables: ["admin_users", "audit_logs"]
        }
    }
}
```

### Monitoring Integration
```typescript
// Telemetry and monitoring
interface TelemetryProvider {
    trackEvent(event: string, properties: Record<string, any>): void
    trackError(error: Error, context: Record<string, any>): void
    trackPerformance(metric: string, value: number): void
}

class PostHogTelemetry implements TelemetryProvider {
    // Implementation for PostHog analytics
}
```

---

*This technical reference provides comprehensive details for AI systems integrating with the Cline SDK, covering architecture, APIs, security, and best practices for production deployment.*