# API Reference Comprehensive programmatic API documentation for Claude-Flow's multi-agent orchestration system. ## Overview Claude-Flow provides a rich TypeScript/JavaScript API for programmatic control of the multi-agent system. This API enables deep integration with existing applications and custom workflow automation. ## Installation and Setup ### Package Installation ```bash # Install Claude-Flow as a dependency npm install claude-flow # Or for Deno import { ClaudeFlow } from 'https://deno.land/x/claude_flow@latest/mod.ts'; ``` ### Basic Initialization ```typescript import { ClaudeFlow, ClaudeFlowConfig } from 'claude-flow'; // Basic configuration const config: ClaudeFlowConfig = { orchestrator: { maxConcurrentAgents: 10, taskQueueSize: 100 }, memory: { backend: 'sqlite', cacheSizeMB: 100 }, terminal: { type: 'auto', poolSize: 5 } }; // Create and start Claude-Flow instance const claudeFlow = new ClaudeFlow(config); await claudeFlow.initialize(); ``` ## Core API Classes ### ClaudeFlow (Main Orchestrator) The primary class for orchestrating the multi-agent system. ```typescript class ClaudeFlow { constructor(config?: ClaudeFlowConfig) // Lifecycle management async initialize(): Promise async start(): Promise async stop(graceful?: boolean): Promise async restart(): Promise // Agent management async spawnAgent(config: AgentConfig): Promise async getAgent(id: string): Promise async listAgents(filter?: AgentFilter): Promise async terminateAgent(id: string, force?: boolean): Promise // Task management async createTask(config: TaskConfig): Promise async getTask(id: string): Promise async listTasks(filter?: TaskFilter): Promise async cancelTask(id: string): Promise async waitForCompletion(taskId: string, timeout?: number): Promise // Workflow management async executeWorkflow(workflow: WorkflowDefinition): Promise async getWorkflow(id: string): Promise async listWorkflows(filter?: WorkflowFilter): Promise // Memory operations async storeMemory(item: MemoryItem): Promise async retrieveMemory(id: string): Promise async queryMemory(query: MemoryQuery): Promise async searchMemory(text: string, options?: SearchOptions): Promise // System operations async getStatus(): Promise async getMetrics(): Promise async exportDiagnostics(): Promise } ``` ### Agent Management API ```typescript interface AgentConfig { type: 'researcher' | 'analyst' | 'implementer' | 'coordinator' | 'custom'; name: string; description?: string; capabilities?: string[]; memoryNamespace?: string; maxConcurrentTasks?: number; timeout?: number; config?: Record; } interface Agent { readonly id: string; readonly name: string; readonly type: string; readonly status: AgentStatus; readonly capabilities: string[]; readonly currentTasks: Task[]; readonly createdAt: Date; readonly lastActiveAt: Date; // Agent operations async assignTask(task: Task): Promise async executeTask(task: Task): Promise async getMemory(query?: MemoryQuery): Promise async storeMemory(item: MemoryItem): Promise async sendMessage(targetAgentId: string, message: Message): Promise async getMetrics(): Promise async terminate(force?: boolean): Promise } type AgentStatus = 'initializing' | 'idle' | 'busy' | 'overloaded' | 'error' | 'terminated'; interface AgentMetrics { tasksCompleted: number; tasksSuccessful: number; tasksFailed: number; averageTaskTime: number; memoryUsage: number; cpuUsage: number; uptime: number; } ``` ### Task Management API ```typescript interface TaskConfig { type: string; description: string; assignTo?: string; priority?: TaskPriority; timeout?: number; retryCount?: number; dependencies?: string[]; metadata?: Record; input?: any; outputDir?: string; } type TaskPriority = 'low' | 'normal' | 'high' | 'urgent'; interface Task { readonly id: string; readonly type: string; readonly description: string; readonly priority: TaskPriority; readonly status: TaskStatus; readonly assignedTo?: string; readonly dependencies: string[]; readonly createdAt: Date; readonly startedAt?: Date; readonly completedAt?: Date; readonly result?: TaskResult; // Task operations async cancel(): Promise async retry(): Promise async updatePriority(priority: TaskPriority): Promise async addDependency(taskId: string): Promise async removeDependency(taskId: string): Promise async getProgress(): Promise async waitForCompletion(timeout?: number): Promise } type TaskStatus = 'pending' | 'assigned' | 'running' | 'completed' | 'failed' | 'cancelled'; interface TaskResult { success: boolean; data?: any; error?: Error; metadata: { executionTime: number; agentId: string; timestamp: Date; }; } ``` ### Memory System API ```typescript interface MemoryManager { // Storage operations async store(item: Partial): Promise async retrieve(id: string): Promise async update(id: string, updates: Partial): Promise async delete(id: string): Promise // Query operations async query(query: MemoryQuery): Promise async fullTextSearch(text: string, options?: SearchOptions): Promise async vectorSearch(options: VectorSearchOptions): Promise // Batch operations async storeBatch(items: Partial[]): Promise async retrieveBatch(ids: string[]): Promise<(MemoryItem | null)[]> async deleteBatch(ids: string[]): Promise // Management operations async getStatistics(): Promise async optimize(): Promise async backup(destination: string): Promise async restore(source: string): Promise } interface MemoryItem { id: string; category: string; content: string; tags: string[]; namespace?: string; metadata?: Record; embedding?: number[]; version: number; vectorClock: VectorClock; created: number; updated: number; checksum: string; } interface MemoryQuery { categories?: string[]; tags?: string[]; tagsAny?: string[]; fullText?: string; namespace?: string; namespaces?: string[]; dateRange?: { start?: Date; end?: Date; field: 'created' | 'updated'; }; metadata?: Record; limit?: number; offset?: number; sortBy?: string; sortOrder?: 'asc' | 'desc'; } ``` ### Terminal Integration API ```typescript interface TerminalManager { // Terminal creation and management async createTerminal(config?: TerminalConfig): Promise async getTerminal(id: string): Promise async listTerminals(): Promise async destroyTerminal(id: string): Promise // Pool management async getPoolStatus(): Promise async resizePool(size: number): Promise async optimizePool(): Promise // Session management async createSession(name: string, config?: SessionConfig): Promise async getSession(name: string): Promise async listSessions(): Promise async saveSession(name: string): Promise async restoreSession(name: string): Promise } interface Terminal { readonly id: string; readonly type: TerminalType; readonly status: TerminalStatus; readonly shell: string; readonly workingDirectory: string; readonly environment: Record; // Command execution async execute(command: string, options?: ExecutionOptions): Promise async executeBatch(commands: string[], options?: BatchOptions): Promise async executeStream(command: string, options?: StreamOptions): Promise // State management async getWorkingDirectory(): Promise async changeDirectory(path: string): Promise async setEnvironment(env: Record): Promise async getHistory(): Promise // Lifecycle async reset(): Promise async dispose(): Promise } type TerminalType = 'vscode' | 'native' | 'ssh' | 'container'; type TerminalStatus = 'initializing' | 'ready' | 'busy' | 'error' | 'disposed'; ``` ### MCP Integration API ```typescript interface MCPServer { // Server management async start(): Promise async stop(): Promise async restart(): Promise async getStatus(): Promise // Tool management async registerTool(tool: Tool): Promise async unregisterTool(name: string): Promise async listTools(): Promise async getTool(name: string): Promise // Tool execution async executeTool(name: string, input: any, options?: ToolOptions): Promise async executeToolAsync(name: string, input: any): Promise async getExecutionResult(executionId: string): Promise async getExecutionStatus(executionId: string): Promise // Client management async listClients(): Promise async authenticateClient(credentials: any): Promise async revokeClient(clientId: string): Promise } interface Tool { name: string; description: string; inputSchema: JSONSchema; outputSchema?: JSONSchema; execute(input: any, context?: ToolContext): Promise; } interface ToolResult { success: boolean; data?: any; error?: ToolError; metadata?: Record; } ``` ## Event System API ### Event Subscription ```typescript interface EventEmitter { // Event subscription on(event: string, listener: (data: T) => void): void once(event: string, listener: (data: T) => void): void off(event: string, listener?: Function): void // Event emission emit(event: string, data?: T): void // Event utilities listenerCount(event: string): number eventNames(): string[] } // System events interface SystemEvents { 'system.started': { timestamp: Date }; 'system.stopped': { timestamp: Date, reason?: string }; 'system.error': { error: Error, component: string }; 'agent.spawned': { agent: Agent }; 'agent.terminated': { agentId: string, reason?: string }; 'agent.error': { agentId: string, error: Error }; 'task.created': { task: Task }; 'task.assigned': { taskId: string, agentId: string }; 'task.started': { taskId: string, agentId: string }; 'task.completed': { taskId: string, result: TaskResult }; 'task.failed': { taskId: string, error: Error }; 'task.cancelled': { taskId: string, reason?: string }; 'memory.stored': { item: MemoryItem }; 'memory.updated': { itemId: string, changes: Partial }; 'memory.deleted': { itemId: string }; 'terminal.created': { terminal: Terminal }; 'terminal.command.executed': { terminalId: string, command: string, result: ExecutionResult }; 'terminal.error': { terminalId: string, error: Error }; } ``` ### Event Usage Examples ```typescript // Subscribe to system events claudeFlow.on('agent.spawned', (event) => { console.log(`New agent spawned: ${event.agent.name}`); }); claudeFlow.on('task.completed', (event) => { console.log(`Task ${event.taskId} completed successfully`); // Process task results }); claudeFlow.on('system.error', (event) => { console.error(`System error in ${event.component}:`, event.error); // Handle system errors }); // One-time event subscription claudeFlow.once('system.started', () => { console.log('Claude-Flow system is ready'); }); ``` ## Workflow API ### Workflow Definition ```typescript interface WorkflowDefinition { name: string; description?: string; version?: string; parameters?: Record; tasks: TaskDefinition[]; completion?: CompletionCriteria; errorHandling?: ErrorHandlingStrategy; } interface TaskDefinition { id: string; type: string; description: string; dependencies?: string[]; assignTo?: string; timeout?: number; retry?: RetryConfig; conditions?: ConditionalConfig[]; parallel?: boolean; parameters?: Record; } interface WorkflowExecution { readonly id: string; readonly definition: WorkflowDefinition; readonly status: WorkflowStatus; readonly progress: number; readonly currentTasks: string[]; readonly completedTasks: string[]; readonly failedTasks: string[]; readonly results: TaskResult[]; readonly startedAt: Date; readonly completedAt?: Date; // Workflow control async pause(): Promise async resume(): Promise async cancel(): Promise async getProgress(): Promise async waitForCompletion(timeout?: number): Promise } type WorkflowStatus = 'pending' | 'running' | 'paused' | 'completed' | 'failed' | 'cancelled'; ``` ## Configuration API ### Configuration Management ```typescript interface ConfigManager { // Configuration loading async load(path?: string): Promise async loadFromString(config: string): Promise async loadDefault(): Promise // Configuration manipulation get(path: string): T set(path: string, value: T): void merge(config: Partial): void // Configuration persistence async save(path?: string): Promise async export(format?: 'json' | 'yaml'): Promise // Configuration validation async validate(): Promise async validateSection(section: string): Promise // Profile management async loadProfile(name: string): Promise async saveProfile(name: string): Promise async listProfiles(): Promise } interface ClaudeFlowConfig { orchestrator?: OrchestratorConfig; agents?: AgentsConfig; tasks?: TasksConfig; memory?: MemoryConfig; terminal?: TerminalConfig; mcp?: MCPConfig; security?: SecurityConfig; logging?: LoggingConfig; monitoring?: MonitoringConfig; } ``` ## Monitoring and Metrics API ### Performance Monitoring ```typescript interface MetricsCollector { // Metrics collection async collect(): Promise async getAgentMetrics(agentId?: string): Promise async getTaskMetrics(timeframe?: TimeFrame): Promise async getMemoryMetrics(): Promise async getTerminalMetrics(): Promise // Historical data async getHistoricalMetrics(timeframe: TimeFrame): Promise async exportMetrics(format: 'json' | 'csv' | 'prometheus'): Promise // Alerting async setAlert(name: string, condition: AlertCondition): Promise async removeAlert(name: string): Promise async listAlerts(): Promise } interface SystemMetrics { timestamp: Date; system: { uptime: number; memoryUsage: MemoryUsage; cpuUsage: number; loadAverage: number[]; }; orchestrator: { totalAgents: number; activeAgents: number; totalTasks: number; queuedTasks: number; completedTasks: number; failedTasks: number; }; performance: { averageTaskTime: number; tasksPerSecond: number; memoryThroughput: number; terminalUtilization: number; }; } ``` ## Error Handling API ### Exception Types ```typescript class ClaudeFlowError extends Error { constructor( message: string, public readonly code: string, public readonly details?: any, public readonly cause?: Error ) } class AgentError extends ClaudeFlowError { constructor( message: string, public readonly agentId: string, code?: string, details?: any ) } class TaskError extends ClaudeFlowError { constructor( message: string, public readonly taskId: string, code?: string, details?: any ) } class MemoryError extends ClaudeFlowError { constructor( message: string, public readonly operation: string, code?: string, details?: any ) } class TerminalError extends ClaudeFlowError { constructor( message: string, public readonly terminalId: string, code?: string, details?: any ) } ``` ## Testing Utilities ### Test Helpers ```typescript interface TestingUtils { // Mock implementations createMockAgent(config?: Partial): MockAgent createMockTask(config?: Partial): MockTask createMockTerminal(config?: Partial): MockTerminal // Test data generation generateTestData(type: 'agents' | 'tasks' | 'memory', count: number): any[] createTestWorkflow(complexity?: 'simple' | 'medium' | 'complex'): WorkflowDefinition // Assertions assertAgentState(agent: Agent, expectedState: AgentStatus): void assertTaskCompletion(task: Task, timeout?: number): Promise assertMemoryConsistency(items: MemoryItem[]): void // Environment setup async setupTestEnvironment(config?: Partial): Promise async cleanupTestEnvironment(instance: ClaudeFlow): Promise } ``` ## Integration Examples ### Express.js Integration ```typescript import express from 'express'; import { ClaudeFlow } from 'claude-flow'; const app = express(); const claudeFlow = new ClaudeFlow(); // Middleware to inject Claude-Flow instance app.use((req, res, next) => { req.claudeFlow = claudeFlow; next(); }); // API endpoints app.post('/api/tasks', async (req, res) => { try { const task = await req.claudeFlow.createTask(req.body); res.json({ success: true, taskId: task.id }); } catch (error) { res.status(500).json({ success: false, error: error.message }); } }); app.get('/api/tasks/:id', async (req, res) => { const task = await req.claudeFlow.getTask(req.params.id); if (!task) { return res.status(404).json({ error: 'Task not found' }); } res.json(task); }); await claudeFlow.start(); app.listen(3000); ``` ### React Integration ```typescript import React, { useEffect, useState } from 'react'; import { ClaudeFlow } from 'claude-flow'; export const ClaudeFlowProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { const [claudeFlow, setClaudeFlow] = useState(null); const [isReady, setIsReady] = useState(false); useEffect(() => { const initializeClaudeFlow = async () => { const instance = new ClaudeFlow({ // Configuration }); await instance.start(); setClaudeFlow(instance); setIsReady(true); }; initializeClaudeFlow(); return () => { claudeFlow?.stop(); }; }, []); if (!isReady) { return
Initializing Claude-Flow...
; } return ( {children} ); }; export const useClaudeFlow = () => { const context = useContext(ClaudeFlowContext); if (!context) { throw new Error('useClaudeFlow must be used within ClaudeFlowProvider'); } return context; }; ``` This comprehensive API reference provides complete documentation for programmatic integration with Claude-Flow, enabling developers to build sophisticated multi-agent applications and custom workflows.