Repository navigation
Expand file tree
/
Copy pathEvolutionSystem.ts
More file actions
executable file
·874 lines (750 loc) · 22.1 KB
/
Copy pathEvolutionSystem.ts
File metadata and controls
executable file
·874 lines (750 loc) · 22.1 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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
/**
* EvolutionSystem.ts
* 进化系统核心实现
*
* @author 昆仑框架团队
* @version 1.0.0
*/
import { EventEmitter } from 'events';
import { v4 as uuidv4 } from 'uuid';
import {
IEvolutionSystem,
EvolutionTask,
EvolutionType,
EvolutionState,
EvolutionSystemConfig,
EvolutionEvaluation,
EvolutionSystemEvent,
EvolutionOpportunity,
EvolutionTrigger
} from './core/interfaces/IEvolutionSystem';
import { SkillSystem } from './SkillSystem';
import { MemorySystem } from './MemorySystem';
import { PersonalitySystem } from './PersonalitySystem';
import { SelfAwarenessStrategy } from './evolution/strategies/SelfAwarenessStrategy';
import { SkillOptimizationStrategy } from './evolution/strategies/SkillOptimizationStrategy';
import { ModelImprovementStrategy } from './evolution/strategies/ModelImprovementStrategy';
import { PersonalityEvolutionStrategy } from './evolution/strategies/PersonalityEvolutionStrategy';
import { MemoryOptimizationStrategy } from './evolution/strategies/MemoryOptimizationStrategy';
import { EvolutionSandbox } from './evolution/sandbox/EvolutionSandbox';
/**
* 进化系统实现
*/
export class EvolutionSystem extends EventEmitter implements IEvolutionSystem {
/** 系统名称 */
public readonly name: string = 'EvolutionSystem';
/** 系统配置 */
private config: EvolutionSystemConfig;
/** 进化任务映射 */
private tasks: Map<string, EvolutionTask> = new Map();
/** 进化策略映射 */
private strategies: Map<EvolutionType, any> = new Map();
/** 进化沙箱 */
private sandbox: EvolutionSandbox;
/** 关联的系统 */
private skillSystem: SkillSystem | null = null;
private memorySystem: MemorySystem | null = null;
private personalitySystem: PersonalitySystem | null = null;
/** 自动进化定时器 */
private autoEvolutionTimer: NodeJS.Timeout | null = null;
/** 初始化状态 */
private initialized: boolean = false;
/**
* 构造函数
*/
constructor() {
super();
this.config = {
autoEvolutionInterval: 24 * 60 * 60 * 1000, // 每天一次
thresholds: {
performanceScore: 0.6,
userSatisfaction: 0.5,
errorRate: 0.3,
skillUsage: 0.1
},
sandboxConfig: {
enabled: true,
timeout: 300000, // 5分钟
resources: {
memory: '256MB',
cpu: '50%',
storage: '1GB'
}
},
rollbackConfig: {
enabled: true,
retentionDays: 7,
maxSnapshots: 10
},
auditConfig: {
enabled: true,
logLevel: 'info',
retentionDays: 30
},
strategies: {
[EvolutionType.SELF_AWARENESS]: {
enabled: true,
priority: 1,
maxIterations: 5
},
[EvolutionType.SKILL_OPTIMIZATION]: {
enabled: true,
priority: 2,
maxIterations: 10
},
[EvolutionType.MODEL_IMPROVEMENT]: {
enabled: false,
priority: 3,
maxIterations: 3
},
[EvolutionType.PERSONALITY_EVOLUTION]: {
enabled: true,
priority: 2,
maxIterations: 5
},
[EvolutionType.MEMORY_OPTIMIZATION]: {
enabled: true,
priority: 1,
maxIterations: 10
}
}
};
this.sandbox = new EvolutionSandbox();
}
/**
* 初始化进化系统
* @param config 系统配置
*/
async initialize(config: Record<string, any>): Promise<void> {
this.config = config as EvolutionSystemConfig;
// 初始化沙箱
if (this.config.sandboxConfig?.enabled) {
await this.sandbox.initialize(this.config);
}
// 注册进化策略
this.registerStrategies();
// 设置自动进化
if (this.config.autoEvolutionInterval && this.config.autoEvolutionInterval > 0) {
this.autoEvolutionTimer = setInterval(
() => this.autoEvolve(),
this.config.autoEvolutionInterval
);
}
this.initialized = true;
console.log('[EvolutionSystem] Initialized successfully');
}
/**
* 注册进化策略
*/
private registerStrategies(): void {
this.strategies.set(
EvolutionType.SELF_AWARENESS,
new SelfAwarenessStrategy()
);
this.strategies.set(
EvolutionType.SKILL_OPTIMIZATION,
new SkillOptimizationStrategy()
);
this.strategies.set(
EvolutionType.MODEL_IMPROVEMENT,
new ModelImprovementStrategy()
);
this.strategies.set(
EvolutionType.PERSONALITY_EVOLUTION,
new PersonalityEvolutionStrategy()
);
this.strategies.set(
EvolutionType.MEMORY_OPTIMIZATION,
new MemoryOptimizationStrategy()
);
}
/**
* 关联其他系统
*/
setAssociatedSystems(
skillSystem: SkillSystem,
memorySystem: MemorySystem,
personalitySystem: PersonalitySystem
): void {
this.skillSystem = skillSystem;
this.memorySystem = memorySystem;
this.personalitySystem = personalitySystem;
}
/**
* 获取进化策略
*/
private getStrategy(type: EvolutionType): any {
const strategy = this.strategies.get(type);
if (!strategy) {
throw new Error(`No evolution strategy found for type: ${type}`);
}
return strategy;
}
/**
* 确保系统已初始化
*/
private ensureInitialized(): void {
if (!this.initialized) {
throw new Error('EvolutionSystem has not been initialized. Call initialize() first.');
}
}
/**
* 创建进化任务
* @param task 进化任务
* @returns 任务ID
*/
async createTask(
task: Omit<EvolutionTask, 'id' | 'state' | 'progress'>
): Promise<string> {
this.ensureInitialized();
// 创建任务ID
const id = `evolution_${uuidv4()}`;
// 创建完整的进化任务
const evolutionTask: EvolutionTask = {
...task,
id,
state: EvolutionState.PENDING,
progress: 0,
createdAt: Date.now()
};
// 存储任务
this.tasks.set(id, evolutionTask);
// 触发事件
this.emit(EvolutionSystemEvent.TASK_CREATED, { task: evolutionTask });
return id;
}
/**
* 批量创建进化任务
* @param tasks 进化任务列表
* @returns 任务ID列表
*/
async batchCreateTasks(
tasks: Omit<EvolutionTask, 'id' | 'state' | 'progress'>[]
): Promise<string[]> {
this.ensureInitialized();
const ids: string[] = [];
const createdTasks: EvolutionTask[] = [];
for (const task of tasks) {
const id = await this.createTask(task);
ids.push(id);
const createdTask = this.tasks.get(id);
if (createdTask) {
createdTasks.push(createdTask);
}
}
// 批量触发事件
this.emit(EvolutionSystemEvent.TASK_CREATED, { tasks: createdTasks });
return ids;
}
/**
* 获取进化任务
* @param taskId 任务ID
*/
async getTask(taskId: string): Promise<EvolutionTask | null> {
this.ensureInitialized();
return this.tasks.get(taskId) || null;
}
/**
* 获取进化任务列表
* @param filter 过滤条件
*/
async getTasks(filter?: any): Promise<EvolutionTask[]> {
this.ensureInitialized();
let tasks = Array.from(this.tasks.values());
// 应用过滤条件
if (filter) {
if (filter.type) {
tasks = tasks.filter(t => t.type === filter.type);
}
if (filter.state) {
tasks = tasks.filter(t => t.state === filter.state);
}
if (filter.userId) {
tasks = tasks.filter(t => t.userId === filter.userId);
}
if (filter.tenantId) {
tasks = tasks.filter(t => t.tenantId === filter.tenantId);
}
if (filter.fromDate) {
tasks = tasks.filter(
t => t.createdAt >= new Date(filter.fromDate).getTime()
);
}
if (filter.toDate) {
tasks = tasks.filter(
t => t.createdAt <= new Date(filter.toDate).getTime()
);
}
}
// 按创建时间排序
tasks.sort((a, b) => b.createdAt - a.createdAt);
return tasks;
}
/**
* 启动进化任务
* @param taskId 任务ID
*/
async startTask(taskId: string): Promise<void> {
this.ensureInitialized();
const task = this.tasks.get(taskId);
if (!task) {
throw new Error(`Evolution task not found: ${taskId}`);
}
if (task.state !== EvolutionState.PENDING) {
throw new Error(`Cannot start task in state: ${task.state}`);
}
// 更新任务状态
task.state = EvolutionState.RUNNING;
task.startedAt = Date.now();
task.progress = 0;
this.tasks.set(taskId, task);
// 触发事件
this.emit(EvolutionSystemEvent.TASK_STARTED, { task });
// 异步执行进化任务
this.executeTask(task).then(() => {
// 任务完成
task.state = EvolutionState.COMPLETED;
task.completedAt = Date.now();
task.progress = 100;
this.tasks.set(taskId, task);
this.emit(EvolutionSystemEvent.TASK_COMPLETED, { task });
}).catch((error: unknown) => {
// 任务失败
task.state = EvolutionState.FAILED;
task.completedAt = Date.now();
task.error = error instanceof Error ? error.message : String(error);
this.tasks.set(taskId, task);
this.emit(EvolutionSystemEvent.TASK_FAILED, { task, error });
});
}
/**
* 执行进化任务
*/
private async executeTask(task: EvolutionTask): Promise<void> {
try {
// 获取进化策略
const strategy = this.getStrategy(task.type);
// 执行进化
const evaluation = await strategy.execute(task);
// 应用进化结果
if (this.config.sandboxConfig?.enabled) {
await this.applyEvolutionInSandbox(task, evaluation);
} else {
await this.applyEvolutionDirectly(task, evaluation);
}
// 记录进化结果
task.result = {
score: evaluation.score,
recommendations: evaluation.recommendations || [],
improvements: evaluation.improvements || [],
risks: evaluation.risks || [],
changes: (evaluation as any).changes,
opportunities: evaluation.opportunities || [],
rollbackData: (evaluation as any).rollbackData
};
} catch (error) {
console.error(`[EvolutionSystem] Task execution failed:`, error);
throw error;
}
}
/**
* 在沙箱中应用进化
*/
private async applyEvolutionInSandbox(
task: EvolutionTask,
evaluation: EvolutionEvaluation
): Promise<void> {
if (!this.config.sandboxConfig?.enabled) {
await this.applyEvolutionDirectly(task, evaluation);
return;
}
// 创建沙箱环境
const sandboxId = await this.sandbox.create();
try {
// 在沙箱中应用进化
const result = await this.sandbox.execute(
sandboxId,
async () => {
return this.applyEvolutionDirectly(task, evaluation);
}
);
// 验证结果
if (result) {
// 应用到生产环境
await this.applyEvolutionDirectly(task, evaluation);
this.emit(EvolutionSystemEvent.EVOLUTION_APPLIED, { task, evaluation });
} else {
throw new Error('Evolution failed in sandbox validation');
}
} finally {
// 销毁沙箱
await this.sandbox.destroy(sandboxId);
}
}
/**
* 直接应用进化(无沙箱)
*/
private async applyEvolutionDirectly(
task: EvolutionTask,
evaluation: EvolutionEvaluation
): Promise<any> {
// 根据进化类型应用不同的逻辑
switch (task.type) {
case EvolutionType.SKILL_OPTIMIZATION:
// 应用技能优化
break;
case EvolutionType.PERSONALITY_EVOLUTION:
// 应用人格进化
break;
case EvolutionType.MEMORY_OPTIMIZATION:
// 应用记忆优化
break;
case EvolutionType.SELF_AWARENESS:
// 应用自省进化
break;
}
return { success: true };
}
/**
* 停止进化任务
* @param taskId 任务ID
*/
async stopTask(taskId: string): Promise<void> {
this.ensureInitialized();
const task = this.tasks.get(taskId);
if (!task) {
throw new Error(`Evolution task not found: ${taskId}`);
}
if (task.state !== EvolutionState.RUNNING) {
throw new Error(`Cannot stop task in state: ${task.state}`);
}
task.state = EvolutionState.CANCELLED;
task.completedAt = Date.now();
this.tasks.set(taskId, task);
this.emit(EvolutionSystemEvent.TASK_COMPLETED, { task });
}
/**
* 删除进化任务
* @param taskId 任务ID
*/
async deleteTask(taskId: string): Promise<void> {
this.ensureInitialized();
const task = this.tasks.get(taskId);
if (!task) {
return;
}
// 如果任务正在运行,先停止
if (task.state === EvolutionState.RUNNING) {
await this.stopTask(taskId);
}
this.tasks.delete(taskId);
}
/**
* 执行进化
* @param type 进化类型
* @param options 进化选项
*/
async evolve(
type?: EvolutionType,
options?: {
userId?: string;
tenantId?: string;
inputData?: any;
parameters?: Record<string, any>;
}
): Promise<EvolutionEvaluation | void> {
this.ensureInitialized();
if (!type) {
// 如果没有指定类型,执行自动评估
return this.evaluateEvolutionNeeds();
}
// 创建临时任务
const now = Date.now();
const task: EvolutionTask = {
id: `temp_${uuidv4()}`,
type,
userId: options?.userId,
tenantId: options?.tenantId,
priority: 0.5,
confidence: 0.8,
createdAt: now,
startedAt: now,
completedAt: now,
state: EvolutionState.RUNNING,
progress: 100,
goal: `Evolution of type: ${type}`,
inputData: options?.inputData || {},
parameters: options?.parameters || {}
};
try {
// 获取进化策略
const strategy = this.getStrategy(type);
// 执行进化
const evaluation = await strategy.execute(task);
// 应用进化结果
await this.applyEvolutionDirectly(task, evaluation);
return evaluation;
} catch (error: unknown) {
task.state = EvolutionState.FAILED;
task.error = error instanceof Error ? error.message : String(error);
throw error;
}
}
/**
* 评估进化需求
* @param userId 用户ID
* @param tenantId 租户ID
*/
async evaluateEvolutionNeeds(
userId?: string,
tenantId?: string
): Promise<EvolutionEvaluation> {
this.ensureInitialized();
const opportunities: EvolutionOpportunity[] = [];
const recommendations: string[] = [];
// 遍历所有策略评估进化机会
for (const strategy of this.strategies.values()) {
const strategyOpportunities = await strategy.evaluate({
userId,
tenantId
});
opportunities.push(...strategyOpportunities);
}
// 按优先级排序
opportunities.sort((a, b) => b.priority - a.priority);
// 生成推荐
const topOpportunities = opportunities.slice(0, 3);
if (topOpportunities.length > 0) {
recommendations.push('建议优先实施以下进化:');
topOpportunities.forEach((opp, index) => {
recommendations.push(`${index + 1}. ${opp.description} - 预期收益: ${opp.expectedGain}`);
});
}
// 计算综合分数
const score = opportunities.length > 0
? opportunities.reduce((sum, opp) => sum + opp.expectedGain, 0) / opportunities.length
: 0;
return {
score,
recommendations,
improvements: [],
opportunities,
risks: []
};
}
/**
* 评估(IEvolutionSystem 接口实现)
*/
async evaluate(): Promise<EvolutionEvaluation> {
return this.evaluateEvolutionNeeds();
}
/**
* 获取策略列表(IEvolutionSystem 接口实现)
*/
getStrategies(): string[] {
return Array.from(this.strategies.keys());
}
/**
* 获取系统状态(IEvolutionSystem 接口实现)
*/
getState(): EvolutionState {
return this.initialized ? EvolutionState.RUNNING : EvolutionState.Idle;
}
/**
* 应用进化结果
* @param taskId 任务ID
* @param options 应用选项
*/
async applyEvolution(taskId: string, options?: {
dryRun: boolean;
rollbackOnFailure: boolean;
}): Promise<any> {
this.ensureInitialized();
const task = this.tasks.get(taskId);
if (!task) {
throw new Error(`Evolution task not found: ${taskId}`);
}
if (task.state !== EvolutionState.COMPLETED) {
throw new Error(`Task is not completed: ${task.state}`);
}
try {
if (options?.dryRun) {
// 仅模拟应用
return { success: true, dryRun: true, changes: (task.result as any)?.changes };
}
// 实际应用进化
const result = await this.applyEvolutionDirectly(task, {} as EvolutionEvaluation);
this.emit(EvolutionSystemEvent.EVOLUTION_APPLIED, { task });
return { success: true, changes: result };
} catch (error) {
if (options?.rollbackOnFailure && (task.result as any)?.rollbackData) {
await this.rollbackEvolution(taskId);
}
throw error;
}
}
/**
* 回滚进化
* @param taskId 任务ID
*/
async rollbackEvolution(taskId: string): Promise<void> {
this.ensureInitialized();
const task = this.tasks.get(taskId);
if (!task) {
throw new Error(`Evolution task not found: ${taskId}`);
}
if (!this.config.rollbackConfig?.enabled) {
throw new Error('Rollback is not enabled in configuration');
}
// 执行回滚
this.emit(EvolutionSystemEvent.ROLLBACK_TRIGGERED, { task });
// 这里应该实现具体的回滚逻辑
console.log(`[EvolutionSystem] Rolled back evolution task: ${taskId}`);
}
/**
* 触发进化
* @param trigger 进化触发器
* @param data 触发器数据
*/
async triggerEvolution(trigger: EvolutionTrigger, data?: any): Promise<EvolutionTask[]> {
this.ensureInitialized();
const evaluation = await this.evaluateEvolutionNeeds();
const tasks: EvolutionTask[] = [];
// 根据触发类型创建进化任务
if ((evaluation.opportunities || []).length > 0) {
// 为最高优先级的进化机会创建任务
const topOpportunity = evaluation.opportunities![0];
const task: EvolutionTask = {
id: `triggered_${uuidv4()}`,
type: topOpportunity.type as EvolutionType,
priority: topOpportunity.priority,
confidence: 0.8,
createdAt: Date.now(),
state: EvolutionState.PENDING,
progress: 0,
goal: topOpportunity.description,
inputData: data || {},
parameters: {}
};
this.tasks.set(task.id, task);
tasks.push(task);
// 自动启动任务
await this.startTask(task.id);
}
return tasks;
}
/**
* 获取进化统计信息
* @param options 统计选项
*/
async getStats(options?: {
type?: EvolutionType;
timeRange?: {
start: Date;
end: Date;
};
}): Promise<{
totalTasks: number;
completedTasks: number;
failedTasks: number;
averageDuration: number;
successRate: number;
byType: Record<EvolutionType, {
count: number;
successRate: number;
}>;
}> {
this.ensureInitialized();
const tasks = await this.getTasks();
const stats = {
totalTasks: tasks.length,
completedTasks: tasks.filter(t => t.state === EvolutionState.COMPLETED).length,
failedTasks: tasks.filter(t => t.state === EvolutionState.FAILED).length,
averageDuration: 0,
successRate: tasks.length > 0
? tasks.filter(t => t.state === EvolutionState.COMPLETED).length / tasks.length
: 0,
byType: {} as any
};
// 按类型统计
const types = Array.from(this.strategies.keys());
for (const type of types) {
const typeTasks = tasks.filter(t => t.type === type);
const completed = typeTasks.filter(t => t.state === EvolutionState.COMPLETED).length;
stats.byType[type] = {
count: typeTasks.length,
successRate: typeTasks.length > 0 ? completed / typeTasks.length : 0
};
}
// 计算平均执行时间
const completedTasks = tasks.filter(t => t.state === EvolutionState.COMPLETED);
if (completedTasks.length > 0) {
const totalDuration = completedTasks.reduce((sum, task) => {
const duration = (task.completedAt || 0) - (task.startedAt || 0);
return sum + duration;
}, 0);
stats.averageDuration = totalDuration / completedTasks.length;
}
return stats;
}
/**
* 自动执行进化
*/
async autoEvolve(): Promise<void> {
console.log('[EvolutionSystem] Running automatic evolution...');
try {
// 评估进化需求
const evaluation = await this.evaluateEvolutionNeeds();
// 如果有进化机会,触发进化
if (evaluation.score > 0.5 && (evaluation.opportunities || []).length > 0) {
await this.triggerEvolution(EvolutionTrigger.SCHEDULED, evaluation);
}
} catch (error) {
console.error('[EvolutionSystem] Auto-evolution failed:', error);
}
}
/**
* 关联技能系统
* @param skillSystem 技能系统实例
*/
setSkillSystem(skillSystem: SkillSystem): void {
this.skillSystem = skillSystem;
}
/**
* 关联记忆系统
* @param memorySystem 记忆系统实例
*/
setMemorySystem(memorySystem: MemorySystem): void {
this.memorySystem = memorySystem;
}
/**
* 关联人格系统
* @param personalitySystem 人格系统实例
*/
setPersonalitySystem(personalitySystem: PersonalitySystem): void {
this.personalitySystem = personalitySystem;
}
/**
* 销毁进化系统
*/
async destroy(): Promise<void> {
// 清理定时器
if (this.autoEvolutionTimer) {
clearInterval(this.autoEvolutionTimer);
}
// 停止所有运行中的任务
const runningTasks = await this.getTasks({ state: EvolutionState.RUNNING });
for (const task of runningTasks) {
await this.stopTask(task.id);
}
// 清空任务
this.tasks.clear();
// 销毁沙箱
await this.sandbox.destroy('default');
// 移除所有监听器
this.removeAllListeners();
this.initialized = false;
console.log('[EvolutionSystem] Destroyed successfully');
}
}
export default EvolutionSystem;