cline-sdk
Version:
Comprehensive SDK for Cline - AI-powered development assistant with database integration, execution modes, and custom functions
413 lines • 12.1 kB
TypeScript
/**
* 🚀 COMPLETE CLINE SDK - Full Implementation
*
* This is the complete implementation with:
* - Real Anthropic API integration
* - All tools (Write, Read, Bash)
* - Full configuration system
* - Real file operations
* - Task management
*/
import { EventEmitter } from "events";
import { ClineConfig } from "./config/cline-config";
import { FunctionDefinition } from "./functions/function-registry";
import { CostCalculation } from "./utils/cost-calculator";
import { TableKnowledge, ColumnKnowledge, TableRegistrationOptions } from "./database/table-knowledge";
import { ExecutionMode } from "./modes/execution-modes";
import { OptimizationResult } from "./utils/prompt-optimizer";
export interface ClineMessage {
ts: number;
type: "say" | "tool" | "ask";
say?: "user" | "assistant";
text?: string;
images?: string[];
toolName?: string;
toolInput?: any;
toolResult?: any;
ask?: string;
costCalculation?: CostCalculation;
}
export 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[];
}
export interface ClineState {
version: string;
currentTask?: ClineTask;
taskHistory: ClineTask[];
config: ClineConfig;
workingDirectory: string;
executionMode: ExecutionMode;
}
export interface AIThinkingEvent {
taskId: string;
phase: "analyzing" | "planning" | "reasoning" | "deciding" | "evaluating";
content: string;
timestamp: number;
context?: {
availableTools?: string[];
currentMode?: ExecutionMode;
constraints?: string[];
};
}
export interface ChatResponseEvent {
taskId: string;
type: "response" | "status_update" | "confirmation" | "error";
content: string;
formatted?: {
markdown?: string;
html?: string;
plainText?: string;
};
timestamp: number;
metadata?: {
isImportant?: boolean;
requiresUserAction?: boolean;
hasAttachments?: boolean;
};
}
export interface ExecutionStateEvent {
taskId: string;
state: "idle" | "thinking" | "tool_execution" | "waiting_user" | "error" | "completed";
details?: {
currentTool?: string;
progress?: number;
estimatedTime?: number;
errorMessage?: string;
};
timestamp: number;
}
export interface ToolExecutionEvent {
taskId: string;
toolName: string;
phase: "starting" | "executing" | "completed" | "error";
input?: any;
output?: any;
error?: string;
executionTime?: number;
timestamp: number;
}
export interface RetryEvent {
taskId: string;
attemptNumber: number;
maxAttempts: number;
waitTimeMs: number;
error: string;
errorType: "llm_error" | "api_error" | "tool_error" | "timeout_error" | "unknown_error";
timestamp: number;
nextRetryAt?: number;
}
export 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;
"ai:thinking": (event: AIThinkingEvent) => void;
"ai:reasoning": (event: AIThinkingEvent) => void;
"chat:response": (event: ChatResponseEvent) => void;
"chat:status": (event: ChatResponseEvent) => void;
"execution:state:changed": (event: ExecutionStateEvent) => void;
"prompt:optimization:started": (originalPrompt: string) => void;
"prompt:optimization:completed": (result: OptimizationResult) => void;
"execution:phase:changed": (phase: string, taskId: string) => void;
"tool:starting": (event: ToolExecutionEvent) => void;
"tool:executing": (event: ToolExecutionEvent) => void;
"tool:completed": (event: ToolExecutionEvent) => void;
"tool:error": (event: ToolExecutionEvent) => void;
"retry:attempt": (event: RetryEvent) => void;
"retry:waiting": (event: RetryEvent) => void;
"retry:failed": (event: RetryEvent) => void;
}
export declare class CompleteClineSDK extends EventEmitter {
private configManager;
private anthropicClient;
private tools;
private currentTask?;
private taskHistory;
private functionRegistry;
private customFunctionTool?;
private databaseManager?;
private tableKnowledgeManager;
private executionMode;
private promptOptimizer;
constructor(config?: Partial<ClineConfig> | string);
private initializeTools;
private initializeDatabaseTools;
private initDatabaseConnection;
/**
* Create a new task
*/
createTask(text: string, images?: string[], files?: string[]): Promise<ClineTask>;
/**
* Send a response to the current task
*/
sendResponse(text: string): Promise<void>;
/**
* Get current state
*/
getState(): ClineState;
/**
* Update configuration
*/
updateConfig(updates: Partial<ClineConfig>): void;
/**
* Cancel current task
*/
cancelCurrentTask(): void;
/**
* Register a custom function that can be called by the AI
*/
registerFunction(definition: FunctionDefinition, implementation: (...args: any[]) => Promise<any> | any): void;
/**
* Unregister a custom function
*/
unregisterFunction(name: string): boolean;
/**
* Get all registered custom functions
*/
getRegisteredFunctions(): string[];
/**
* Get custom function registry stats
*/
getFunctionStats(): {
totalFunctions: number;
totalCalls: number;
categories: Record<string, number>;
mostUsed: {
name: string;
calls: number;
} | null;
};
/**
* Clear all registered functions
*/
clearFunctions(): void;
/**
* Get database connection status
*/
getDatabaseStatus(): {
connected: boolean;
config?: any;
error?: string;
};
/**
* Test database connection
*/
testDatabaseConnection(): Promise<{
connected: boolean;
message: string;
version?: string;
}>;
/**
* Get database schema context for AI
*/
getDatabaseContext(): string;
/**
* Close database connections
*/
closeDatabaseConnections(): Promise<void>;
/**
* Register detailed business knowledge about a database table
*/
addTable(knowledge: Partial<TableKnowledge>, options?: TableRegistrationOptions): void;
/**
* Add detailed knowledge about a specific column
*/
addColumn(schemaName: string, tableName: string, columnKnowledge: ColumnKnowledge): void;
/**
* Register multiple tables at once
*/
addTables(tables: Partial<TableKnowledge>[], options?: TableRegistrationOptions): void;
/**
* Get registered knowledge for a specific table
*/
getTableKnowledge(schemaName: string, tableName: string): TableKnowledge | undefined;
/**
* Get all registered table knowledge
*/
getAllTableKnowledge(): TableKnowledge[];
/**
* Search tables by domain, tags, or keywords
*/
searchTableKnowledge(query: {
domain?: string;
tags?: string[];
keyword?: string;
businessPurpose?: string;
}): TableKnowledge[];
/**
* Export all table knowledge as JSON
*/
exportTableKnowledge(): string;
/**
* Import table knowledge from JSON
*/
importTableKnowledge(jsonData: string): void;
/**
* Clear all registered table knowledge
*/
clearTableKnowledge(): void;
/**
* Get statistics about registered table knowledge
*/
getTableKnowledgeStats(): {
totalTables: number;
totalColumns: number;
domains: string[];
securityLevels: Record<string, number>;
mostCommonTags: string[];
};
/**
* Generate AI-friendly context from registered knowledge
*/
generateKnowledgeContext(includeOnlyTables?: string[]): string;
/**
* Validate registered knowledge against actual database schema
*/
validateTableKnowledge(schemaName: string, tableName: string): Promise<{
valid: boolean;
issues: string[];
suggestions: string[];
}>;
/**
* Get current execution mode
*/
getExecutionMode(): ExecutionMode;
/**
* Set execution mode
*/
setExecutionMode(mode: ExecutionMode): void;
/**
* Get mode capabilities and restrictions
*/
getModeStatus(): string;
/**
* Check if a specific tool is allowed in current mode
*/
isToolAllowedInMode(toolName: string): boolean;
/**
* Get restrictions for current mode
*/
getCurrentModeRestrictions(): import("./modes/execution-modes").ModeRestrictions;
/**
* Parse and execute mode switch from user input
*/
handleModeSwitch(userInput: string): boolean;
private taskRetryAttempts;
/**
* Emit AI thinking event
*/
private emitThinking;
/**
* Emit chat response event
*/
private emitChatResponse;
/**
* Emit execution state change event
*/
private emitExecutionState;
/**
* Emit tool execution event
*/
private emitToolExecution;
/**
* Emit retry event
*/
private emitRetryEvent;
/**
* Check if error should be retried
*/
private shouldRetryError;
/**
* Wait for retry delay
*/
private waitForRetry;
/**
* Increment retry attempt counter
*/
private incrementRetryAttempt;
/**
* Reset retry attempts for task
*/
private resetRetryAttempts;
/**
* Classify error type for retry logic
*/
private classifyError;
/**
* Get cost information for current task
*/
getCurrentTaskCost(): CostCalculation[];
/**
* Get total cost for current task
*/
getCurrentTaskTotalCost(): number;
/**
* Get cost information for a specific task
*/
getTaskCost(taskId: string): CostCalculation[];
/**
* Get total costs for all tasks
*/
getTotalCosts(): {
totalCost: number;
taskCount: number;
totalTokensIn: number;
totalTokensOut: number;
averageCostPerTask: number;
costsByProvider: Record<string, number>;
costsByModel: Record<string, number>;
};
/**
* Get pricing information for current provider/model
*/
getCurrentPricingInfo(): {
provider: string;
model: string;
inputCostPer1k: number;
outputCostPer1k: number;
} | null;
/**
* Set custom pricing for current provider/model
*/
setCustomPricing(inputCostPer1k: number, outputCostPer1k: number): void;
private processTask;
private processAnthropicResponse;
private executeTool;
private convertToAnthropicMessages;
private getEnabledToolDefinitions;
private buildSystemPrompt;
/**
* Analyze a prompt for quality and provide optimization suggestions
*/
analyzePrompt(prompt: string): OptimizationResult;
/**
* Get formatted optimization results for display
*/
formatOptimizationResults(result: OptimizationResult): string;
/**
* Check if a prompt can be optimized (using special command syntax)
*/
checkForOptimizationRequest(userInput: string): {
shouldOptimize: boolean;
extractedPrompt?: string;
};
/**
* Process optimization request and return improved prompt
*/
handleOptimizationRequest(userInput: string): Promise<string>;
}
export default CompleteClineSDK;
//# sourceMappingURL=complete-cline-sdk.d.ts.map