-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathclaude-flow-core.js
More file actions
554 lines (425 loc) · 13.3 KB
/
Copy pathclaude-flow-core.js
File metadata and controls
554 lines (425 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
#!/usr/bin/env node
/**
* Claude Flow Core Integration
* Main module that integrates all components
*/
import ClaudeFlowInitializer from './claude-flow-init.js';
import MemoryPersistence from './memory-persistence.js';
import AgentCoordinator from './agent-coordination.js';
import SessionManager from './session-manager.js';
import { readFile } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
import { EventEmitter } from 'events';
export class ClaudeFlowCore extends EventEmitter {
constructor() {
super();
this.initialized = false;
this.config = null;
this.initializer = new ClaudeFlowInitializer();
this.memory = null;
this.coordinator = null;
this.sessionManager = null;
this.activeSwarmId = null;
}
/**
* Initialize Claude Flow
*/
async initialize() {
if (this.initialized) {
return { already_initialized: true };
}
try {
console.log('🚀 Initializing Claude Flow Core...');
// 1. Run initialization
this.config = await this.initializer.initialize();
// 2. Initialize memory persistence
this.memory = new MemoryPersistence({
basePath: this.config.memory.location,
maxSize: this.parseSize(this.config.memory.maxSize),
compression: this.config.memory.compression,
encryption: this.config.memory.encryption
});
await this.memory.initialize();
// 3. Initialize agent coordinator
this.coordinator = new AgentCoordinator({
topology: this.config.swarm.defaultTopology,
maxAgents: this.config.swarm.maxAgents,
strategies: this.config.swarm.strategies
});
// 4. Initialize session manager
this.sessionManager = new SessionManager({
sessionPath: join(this.config.memory.location, 'sessions'),
autoSave: true
});
await this.sessionManager.initialize();
// 5. Setup event listeners
this.setupEventListeners();
// 6. Create default session
const session = await this.sessionManager.createSession({
type: 'claude-flow',
metadata: {
version: this.config.version,
features: this.config.features
}
});
this.initialized = true;
console.log('✅ Claude Flow Core initialized successfully!');
return {
initialized: true,
sessionId: session.sessionId,
version: this.config.version
};
} catch (error) {
console.error('❌ Initialization failed:', error.message);
throw error;
}
}
/**
* High-level API methods
*/
async initSwarm(options = {}) {
this.ensureInitialized();
const result = await this.coordinator.initSwarm(options);
this.activeSwarmId = result.swarmId;
// Update session
await this.sessionManager.addSwarm(result.swarmId, {
topology: result.topology,
maxAgents: result.maxAgents
});
// Store in memory
await this.memory.store(`swarm:${result.swarmId}`, {
...result,
created: Date.now()
}, { namespace: 'swarms' });
return result;
}
async spawnAgent(options = {}) {
this.ensureInitialized();
// Use active swarm if not specified
if (!options.swarmId && this.activeSwarmId) {
options.swarmId = this.activeSwarmId;
}
const result = await this.coordinator.spawnAgent(options);
// Update session
await this.sessionManager.addAgent(result.agentId, {
type: result.type,
name: result.name,
swarmId: options.swarmId
});
// Store in memory
await this.memory.store(`agent:${result.agentId}`, {
...result,
created: Date.now()
}, { namespace: 'agents' });
return result;
}
async orchestrateTask(options = {}) {
this.ensureInitialized();
// Use active swarm if not specified
if (!options.swarmId && this.activeSwarmId) {
options.swarmId = this.activeSwarmId;
}
const result = await this.coordinator.orchestrateTask(options);
// Update session
await this.sessionManager.addTask(result.taskId, {
description: options.task,
strategy: options.strategy,
swarmId: options.swarmId
});
// Store in memory
await this.memory.store(`task:${result.taskId}`, {
...options,
taskId: result.taskId,
created: Date.now()
}, { namespace: 'tasks' });
return result;
}
async getSwarmStatus(swarmId) {
this.ensureInitialized();
swarmId = swarmId || this.activeSwarmId;
if (!swarmId) {
throw new Error('No active swarm');
}
return this.coordinator.getSwarmStatus(swarmId);
}
async getTaskStatus(taskId) {
this.ensureInitialized();
const task = this.coordinator.tasks.get(taskId);
if (!task) {
throw new Error(`Task ${taskId} not found`);
}
return {
id: task.id,
status: task.status,
progress: task.subtasks.filter(st => st.completed).length / task.subtasks.length,
created: task.created,
started: task.started,
completed: task.completed
};
}
async destroySwarm(swarmId) {
this.ensureInitialized();
swarmId = swarmId || this.activeSwarmId;
if (!swarmId) {
throw new Error('No active swarm');
}
const result = await this.coordinator.destroySwarm(swarmId);
if (swarmId === this.activeSwarmId) {
this.activeSwarmId = null;
}
return result;
}
/**
* Memory operations
*/
async storeMemory(key, value, options = {}) {
this.ensureInitialized();
const result = await this.memory.store(key, value, options);
// Update session memory
await this.sessionManager.updateMemory(key, value);
return result;
}
async retrieveMemory(key, namespace = 'default') {
this.ensureInitialized();
return this.memory.retrieve(key, namespace);
}
async searchMemory(pattern, options = {}) {
this.ensureInitialized();
return this.memory.search(pattern, options);
}
async listMemory(pattern = '*', namespace = 'default') {
this.ensureInitialized();
return this.memory.list(pattern, namespace);
}
/**
* Session operations
*/
async createCheckpoint(name, description) {
this.ensureInitialized();
return this.sessionManager.createCheckpoint(name, description);
}
async restoreCheckpoint(checkpointId) {
this.ensureInitialized();
return this.sessionManager.restoreCheckpoint(checkpointId);
}
async generateSummary() {
this.ensureInitialized();
return this.sessionManager.generateSummary();
}
async exportSession(format = 'json') {
this.ensureInitialized();
return this.sessionManager.exportSession(format);
}
async endSession() {
this.ensureInitialized();
const summary = await this.sessionManager.endSession();
// Backup memory
if (this.config.memory.persistent) {
await this.memory.backup();
}
return summary;
}
/**
* Utility methods
*/
async getMetrics() {
this.ensureInitialized();
return {
coordinator: this.coordinator.metrics,
memory: {
namespaces: Array.from(this.memory.namespaces.keys()),
cacheSize: this.memory.cache.size
},
session: this.sessionManager.currentSession?.state.metrics
};
}
async performanceReport(options = {}) {
this.ensureInitialized();
const metrics = await this.getMetrics();
const summary = await this.sessionManager.generateSummary();
return {
metrics,
summary,
recommendations: this.generateRecommendations(metrics)
};
}
/**
* Helper methods
*/
ensureInitialized() {
if (!this.initialized) {
throw new Error('Claude Flow not initialized. Call initialize() first.');
}
}
parseSize(sizeStr) {
const match = sizeStr.match(/^(\d+)(MB|GB|KB)?$/i);
if (!match) return 100 * 1024 * 1024; // Default 100MB
const size = parseInt(match[1]);
const unit = (match[2] || 'MB').toUpperCase();
switch (unit) {
case 'KB': return size * 1024;
case 'MB': return size * 1024 * 1024;
case 'GB': return size * 1024 * 1024 * 1024;
default: return size;
}
}
setupEventListeners() {
// Coordinator events
this.coordinator.on('swarm:initialized', async (data) => {
this.emit('swarm:initialized', data);
});
this.coordinator.on('agent:spawned', async (data) => {
this.emit('agent:spawned', data);
});
this.coordinator.on('task:orchestrated', async (data) => {
this.emit('task:orchestrated', data);
});
// Update metrics on task completion
this.coordinator.on('task:completed', async (data) => {
await this.sessionManager.updateMetrics({
tasksCompleted: this.coordinator.metrics.tasksCompleted
});
});
}
generateRecommendations(metrics) {
const recommendations = [];
// Check coordinator metrics
if (metrics.coordinator.avgCompletionTime > 10000) {
recommendations.push({
type: 'performance',
message: 'Consider using parallel execution strategy for faster task completion'
});
}
if (metrics.coordinator.tasksFailed > metrics.coordinator.tasksCompleted * 0.2) {
recommendations.push({
type: 'reliability',
message: 'High failure rate detected. Review task complexity and agent capabilities'
});
}
// Check memory usage
if (metrics.memory.cacheSize > 1000) {
recommendations.push({
type: 'memory',
message: 'Large cache size. Consider clearing old entries to improve performance'
});
}
return recommendations;
}
/**
* CLI Commands
*/
async handleCommand(command, args = []) {
switch (command) {
case 'init':
return this.initialize();
case 'swarm':
return this.handleSwarmCommand(args);
case 'agent':
return this.handleAgentCommand(args);
case 'task':
return this.handleTaskCommand(args);
case 'memory':
return this.handleMemoryCommand(args);
case 'session':
return this.handleSessionCommand(args);
case 'status':
return this.getSwarmStatus();
case 'metrics':
return this.getMetrics();
case 'report':
return this.performanceReport();
default:
throw new Error(`Unknown command: ${command}`);
}
}
async handleSwarmCommand(args) {
const subcommand = args[0];
switch (subcommand) {
case 'init':
const topology = args[1] || 'hierarchical';
return this.initSwarm({ topology });
case 'status':
return this.getSwarmStatus(args[1]);
case 'destroy':
return this.destroySwarm(args[1]);
default:
throw new Error(`Unknown swarm command: ${subcommand}`);
}
}
async handleAgentCommand(args) {
const subcommand = args[0];
switch (subcommand) {
case 'spawn':
const type = args[1] || 'specialist';
return this.spawnAgent({ type });
case 'list':
const swarmId = args[1] || this.activeSwarmId;
const status = await this.getSwarmStatus(swarmId);
return status.agents;
default:
throw new Error(`Unknown agent command: ${subcommand}`);
}
}
async handleTaskCommand(args) {
const subcommand = args[0];
switch (subcommand) {
case 'run':
const task = args.slice(1).join(' ');
return this.orchestrateTask({ task });
case 'status':
return this.getTaskStatus(args[1]);
default:
throw new Error(`Unknown task command: ${subcommand}`);
}
}
async handleMemoryCommand(args) {
const subcommand = args[0];
switch (subcommand) {
case 'store':
return this.storeMemory(args[1], args[2]);
case 'get':
return this.retrieveMemory(args[1]);
case 'search':
return this.searchMemory(args[1]);
case 'list':
return this.listMemory(args[1]);
default:
throw new Error(`Unknown memory command: ${subcommand}`);
}
}
async handleSessionCommand(args) {
const subcommand = args[0];
switch (subcommand) {
case 'checkpoint':
return this.createCheckpoint(args[1], args[2]);
case 'restore':
return this.restoreCheckpoint(args[1]);
case 'summary':
return this.generateSummary();
case 'export':
return this.exportSession(args[1]);
case 'end':
return this.endSession();
default:
throw new Error(`Unknown session command: ${subcommand}`);
}
}
}
// CLI Interface
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const core = new ClaudeFlowCore();
const command = process.argv[2];
const args = process.argv.slice(3);
core.initialize()
.then(() => core.handleCommand(command, args))
.then(result => {
console.log(JSON.stringify(result, null, 2));
process.exit(0);
})
.catch(error => {
console.error('Error:', error.message);
process.exit(1);
});
}
export default ClaudeFlowCore;