-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodified_intent_handler.js.txt
More file actions
609 lines (536 loc) · 19.2 KB
/
modified_intent_handler.js.txt
File metadata and controls
609 lines (536 loc) · 19.2 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
/**
* 🌟 UnifiedIntentHandler - 統一Intent処理システム
*
* 🔧 大工事Phase3: Intent処理統合完了版
*
* 🎯 統合対象:
* - VoidCore._processIntent()
* - VoidCore._handleSystemBootIntent()
* - VoidCore._handlePluginManagementIntent()
* - IntentHandler クラス全体
*
* 🚀 設計思想:
* - 統一されたIntent処理フロー (1対1および1対多対応)
* - 効率的な並行処理制御
* - 統一された統計収集
*
* Created: 2025-07-08 (大工事Phase3)
* Modified for 1-to-many handlers: 2025-07-14
*/
import { Message } from '../messaging/message.js'
import { debugLogger } from '../../charmflow/js/debug-file-logger.js'
export class UnifiedIntentHandler {
constructor(config = {}) {
this.coreId = config.coreId || 'unified-intent-handler'
this.core = config.core || null
this.pluginManager = config.pluginManager || null
// 🎯 統一Intent処理統計
this.stats = {
totalIntents: 0,
systemIntents: 0,
pluginIntents: 0,
bootIntents: 0,
fusionIntents: 0,
customIntents: 0,
successfulIntents: 0,
failedIntents: 0,
totalProcessingTime: 0,
startTime: Date.now()
}
// 🔧 統一Intent処理履歴
this.intentHistory = []
this.maxHistorySize = 200
// 🌟 統一Intent処理ルール
this.intentRules = new Map()
this.middleware = []
// 🚀 統一並行処理制御
this.pendingIntents = new Map() // correlationId -> Promise
this.maxConcurrentIntents = config.maxConcurrentIntents || 100
// 🎯 統一Intent処理ハンドラー (値は Function[] に)
this.intentHandlers = new Map()
this.initializeHandlers()
this.log('🌟 UnifiedIntentHandler initialized for 1-to-many intents')
}
// =========================================
// 統一Intent処理ハンドラー初期化・登録
// =========================================
/**
* Intent処理ハンドラー初期化
*/
initializeHandlers() {
// 🔧 システム起動Intent
this.registerIntentHandler('system.boot.ready', this.handleSystemBootReady.bind(this))
this.registerIntentHandler('system.boot.status', this.handleSystemBootStatus.bind(this))
this.registerIntentHandler('system.boot.restart', this.handleSystemBootRestart.bind(this))
// 🎯 プラグイン管理Intent
this.registerIntentHandler('system.plugin.create', this.handlePluginCreate.bind(this))
this.registerIntentHandler('system.plugin.destroy', this.handlePluginDestroy.bind(this))
this.registerIntentHandler('system.plugin.list', this.handlePluginList.bind(this))
this.registerIntentHandler('system.plugin.status', this.handlePluginStatus.bind(this))
// 🌟 CoreFusion Intent
this.registerIntentHandler('system.fusion.fuse', this.handleFusionFuse.bind(this))
this.registerIntentHandler('system.fusion.status', this.handleFusionStatus.bind(this))
// 🚀 システム管理Intent
this.registerIntentHandler('system.stats', this.handleSystemStats.bind(this))
this.registerIntentHandler('system.clear', this.handleSystemClear.bind(this))
this.registerIntentHandler('system.connect', this.handleSystemConnect.bind(this))
this.registerIntentHandler('system.reparent', this.handleSystemReparent.bind(this))
}
/**
* Intent処理ハンドラー登録 (1対多対応)
* @param {string} action - Intent アクション
* @param {Function} handler - ハンドラー関数
*/
registerIntentHandler(action, handler) {
if (!this.intentHandlers.has(action)) {
this.intentHandlers.set(action, []);
}
this.intentHandlers.get(action).push(handler);
this.log(`🎯 Intent handler registered for: ${action}. Total handlers: ${this.intentHandlers.get(action).length}`);
}
// =========================================
// 統一Intent処理メインシステム
// =========================================
/**
* 統一Intent処理メイン関数
* @param {Object} intentMessage - Intent メッセージ
* @returns {Promise<Object>} 処理結果
*/
async processIntent(intentMessage) {
const startTime = Date.now()
const correlationId = intentMessage.correlationId || `intent_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`
try {
// 🔧 並行処理制御
if (this.pendingIntents.size >= this.maxConcurrentIntents) {
this.log(`⚠️ Intent queue full, rejecting: ${intentMessage.action}`)
return { status: 'rejected', reason: 'Queue full' }
}
// 🎯 Intent処理Promise作成
const intentPromise = this._executeIntent(intentMessage, correlationId)
this.pendingIntents.set(correlationId, intentPromise)
// 🌟 Intent処理実行
const result = await intentPromise
// 🚀 統計更新
this.updateIntentStats(intentMessage, result, startTime)
return result
} catch (error) {
this.log(`❌ Intent processing failed: ${error.message}`)
this.updateIntentStats(intentMessage, { status: 'failed', error: error.message }, startTime)
return { status: 'failed', error: error.message }
} finally {
this.pendingIntents.delete(correlationId)
}
}
/**
* Intent処理実行 (1対多対応)
* @param {Object} intentMessage - Intent メッセージ
* @param {string} correlationId - 相関ID
* @returns {Promise<Object>} 処理結果
*/
async _executeIntent(intentMessage, correlationId) {
const { action, payload } = intentMessage
// 🔧 前処理ミドルウェア
let processedPayload = payload
for (const middleware of this.middleware) {
if (middleware.preProcess) {
processedPayload = await middleware.preProcess(processedPayload, action)
}
}
// 🎯 Intent処理ハンドラー実行 (1対多対応)
const handlers = this.intentHandlers.get(action)
let finalResult
if (handlers && handlers.length > 0) {
// 複数のハンドラを並列実行し、個々のエラーをキャッチ
const promises = handlers.map(handler =>
Promise.resolve(handler(processedPayload, correlationId))
.catch(e => ({ status: 'failed', error: e.message }))
);
const results = await Promise.all(promises);
// 全てのハンドラが成功した場合のみ 'success' とする
const allSuccess = results.every(r => r && r.status && r.status !== 'failed' && r.status !== 'rejected');
finalResult = {
status: allSuccess ? 'success' : 'partial_failure',
results: results
};
} else {
// 🌟 カスタムIntent処理 (フォールバック)
finalResult = await this.handleCustomIntent(action, processedPayload, correlationId)
}
// 🚀 後処理ミドルウェア
let processedResult = finalResult
for (const middleware of this.middleware) {
if (middleware.postProcess) {
processedResult = await middleware.postProcess(processedResult, action)
}
}
return processedResult
}
// =========================================
// システム起動Intent処理
// =========================================
/**
* system.boot.ready Intent処理
* @param {Object} payload - ペイロード
* @param {string} correlationId - 相関ID
* @returns {Promise<Object>} 処理結果
*/
async handleSystemBootReady(payload, correlationId) {
this.log('🚀 System boot ready acknowledged')
return {
status: 'acknowledged',
message: 'System boot ready acknowledged',
timestamp: Date.now()
}
}
/**
* system.boot.status Intent処理
* @param {Object} payload - ペイロード
* @param {string} correlationId - 相関ID
* @returns {Promise<Object>} 処理結果
*/
async handleSystemBootStatus(payload, correlationId) {
if (this.core && this.core.systemBootManager) {
return {
status: 'success',
systemStatus: this.core.systemBootManager.systemStatus,
isBootComplete: this.core.systemBootManager.isBootComplete,
bootSequence: this.core.systemBootManager.bootSequence
}
}
return { status: 'failed', reason: 'SystemBootManager not available' }
}
/**
* system.boot.restart Intent処理
* @param {Object} payload - ペイロード
* @param {string} correlationId - 相関ID
* @returns {Promise<Object>} 処理結果
*/
async handleSystemBootRestart(payload, correlationId) {
this.log('🔄 System restart requested')
if (this.core && this.core.systemBootManager) {
this.core.systemBootManager.systemStatus = 'restarting'
// 再起動処理(実装は後で)
return { status: 'restarting', message: 'System restart initiated' }
}
return { status: 'failed', reason: 'SystemBootManager not available' }
}
// =========================================
// プラグイン管理Intent処理
// =========================================
/**
* system.plugin.create Intent処理
* @param {Object} payload - ペイロード
* @param {string} correlationId - 相関ID
* @returns {Promise<Object>} 処理結果
*/
async handlePluginCreate(payload, correlationId) {
if (this.pluginManager) {
return await this.pluginManager.handleCreatePluginIntent(payload)
}
// 🔧 後方互換性のためのフォールバック
this.log(`🔧 Creating plugin via Intent: ${payload.type}`)
return {
status: 'created',
pluginId: `plugin_${Date.now()}`,
message: 'Plugin created via Intent system'
}
}
/**
* system.plugin.destroy Intent処理
* @param {Object} payload - ペイロード
* @param {string} correlationId - 相関ID
* @returns {Promise<Object>} 処理結果
*/
async handlePluginDestroy(payload, correlationId) {
if (this.pluginManager) {
return await this.pluginManager.handleDestroyPluginIntent(payload)
}
// 🔧 後方互換性のためのフォールバック
const pluginId = payload.pluginId
this.log(`🔧 Destroying plugin via Intent: ${pluginId}`)
return {
status: 'destroyed',
pluginId: payload.pluginId,
message: 'Plugin destroyed via Intent system'
}
}
/**
* system.plugin.list Intent処理
* @param {Object} payload - ペイロード
* @param {string} correlationId - 相関ID
* @returns {Promise<Object>} 処理結果
*/
async handlePluginList(payload, correlationId) {
if (this.pluginManager) {
const plugins = this.pluginManager.getAllPlugins()
return {
status: 'success',
plugins: plugins.map(p => ({ id: p.id, type: p.type, status: p.status })),
count: plugins.length
}
}
return { status: 'failed', reason: 'PluginManager not available' }
}
/**
* system.plugin.status Intent処理
* @param {Object} payload - ペイロード
* @param {string} correlationId - 相関ID
* @returns {Promise<Object>} 処理結果
*/
async handlePluginStatus(payload, correlationId) {
if (this.pluginManager) {
const plugin = this.pluginManager.getPlugin(payload.pluginId)
if (plugin) {
return {
status: 'success',
plugin: { id: plugin.id, type: plugin.type, status: plugin.status }
}
}
}
return { status: 'failed', reason: 'Plugin not found' }
}
// =========================================
// CoreFusion Intent処理
// =========================================
/**
* system.fusion.fuse Intent処理
* @param {Object} payload - ペイロード
* @param {string} correlationId - 相関ID
* @returns {Promise<Object>} 処理結果
*/
async handleFusionFuse(payload, correlationId) {
if (this.core && this.core.coreFusion) {
const result = await this.core.fuseWith(payload.targetCore, payload.config)
return {
status: result.success ? 'success' : 'failed',
...result
}
}
return { status: 'failed', reason: 'CoreFusion not available' }
}
/**
* system.fusion.status Intent処理
* @param {Object} payload - ペイロード
* @param {string} correlationId - 相関ID
* @returns {Promise<Object>} 処理結果
*/
async handleFusionStatus(payload, correlationId) {
if (this.core && this.core.coreFusion) {
const history = this.core.coreFusion.getFusionHistory()
return {
status: 'success',
fusionHistory: history,
fusionCount: history.length
}
}
return { status: 'failed', reason: 'CoreFusion not available' }
}
// =========================================
// システム管理Intent処理
// =========================================
/**
* system.stats Intent処理
* @param {Object} payload - ペイロード
* @param {string} correlationId - 相関ID
* @returns {Promise<Object>} 処理結果
*/
async handleSystemStats(payload, correlationId) {
const stats = {
intentHandler: this.getStats(),
pluginManager: this.pluginManager ? this.pluginManager.getStats() : null,
core: this.core ? this.core.getStats() : null
}
return { status: 'success', stats }
}
/**
* system.clear Intent処理
* @param {Object} payload - ペイロード
* @param {string} correlationId - 相関ID
* @returns {Promise<Object>} 処理結果
*/
async handleSystemClear(payload, correlationId) {
this.log('🧹 System clear requested')
if (this.core && this.core.clear) {
await this.core.clear()
return { status: 'cleared', message: 'System cleared successfully' }
}
return { status: 'failed', reason: 'Core not available' }
}
/**
* system.connect Intent処理
* @param {Object} payload - ペイロード
* @param {string} correlationId - 相関ID
* @returns {Promise<Object>} 処理結果
*/
async handleSystemConnect(payload, correlationId) {
this.log(`🔗 System connect: ${payload.source} -> ${payload.target}`)
return {
status: 'connected',
source: payload.source,
target: payload.target,
timestamp: Date.now()
}
}
/**
* system.reparent Intent処理
* @param {Object} payload - ペイロード
* @param {string} correlationId - 相関ID
* @returns {Promise<Object>} 処理結果
*/
async handleSystemReparent(payload, correlationId) {
this.log(`🔄 System reparent: ${payload.pluginId} -> ${payload.newParent}`)
return {
status: 'reparented',
pluginId: payload.pluginId,
newParent: payload.newParent,
timestamp: Date.now()
}
}
// =========================================
// カスタムIntent処理
// =========================================
/**
* カスタムIntent処理
* @param {string} action - Intent アクション
* @param {Object} payload - ペイロード
* @param {string} correlationId - 相関ID
* @returns {Promise<Object>} 処理結果
*/
async handleCustomIntent(action, payload, correlationId) {
this.log(`🎯 Custom intent (unhandled): ${action}`)
return {
status: 'unhandled',
intent: action,
message: 'No specific handler registered for this custom intent.',
timestamp: Date.now()
}
}
// =========================================
// 統一統計システム
// =========================================
/**
* 統一統計取得
* @returns {Object} 統計情報
*/
getStats() {
const handlerCounts = {};
for (const [action, handlers] of this.intentHandlers.entries()) {
handlerCounts[action] = handlers.length;
}
return {
...this.stats,
runtime: Date.now() - this.stats.startTime,
pendingIntents: this.pendingIntents.size,
registeredHandlerActions: this.intentHandlers.size,
handlerCounts: handlerCounts,
recentIntents: this.intentHistory.slice(-10)
}
}
/**
* Intent統計更新 (1対多対応)
* @param {Object} intentMessage - Intent メッセージ
* @param {Object} result - 処理結果
* @param {number} startTime - 開始時間
*/
updateIntentStats(intentMessage, result, startTime) {
const processingTime = Date.now() - startTime
const { action } = intentMessage
this.stats.totalIntents++
this.stats.totalProcessingTime += processingTime
// 🔧 Intent種別統計
if (action.startsWith('system.boot.')) {
this.stats.bootIntents++
} else if (action.startsWith('system.plugin.')) {
this.stats.pluginIntents++
} else if (action.startsWith('system.fusion.')) {
this.stats.fusionIntents++
} else if (action.startsWith('system.')) {
this.stats.systemIntents++
} else {
this.stats.customIntents++
}
// 🎯 成功・失敗統計 (1対多対応)
// 'success' のみ成功とみなす
if (result.status === 'success') {
this.stats.successfulIntents++
} else {
this.stats.failedIntents++
}
// 🌟 履歴記録
this.recordIntentHistory(intentMessage, result, processingTime)
}
/**
* Intent履歴記録
* @param {Object} intentMessage - Intent メッセージ
* @param {Object} result - 処理結果
* @param {number} processingTime - 処理時間
*/
recordIntentHistory(intentMessage, result, processingTime) {
this.intentHistory.push({
timestamp: Date.now(),
action: intentMessage.action,
status: result.status,
// 結果が配列の場合は、個々のステータスも記録するとデバッグに役立つ
results: result.results ? result.results.map(r => r.status || 'unknown') : null,
processingTime,
correlationId: intentMessage.correlationId
})
// 履歴サイズ制限
if (this.intentHistory.length > this.maxHistorySize) {
this.intentHistory.shift()
}
}
// =========================================
// ミドルウェア管理
// =========================================
/**
* ミドルウェア追加
* @param {Object} middleware - ミドルウェア
*/
addMiddleware(middleware) {
this.middleware.push(middleware)
this.log(`🔧 Middleware added: ${middleware.name || 'unnamed'}`)
}
// =========================================
// ユーティリティ
// =========================================
/**
* ログ出力
* @param {string} message - ログメッセージ
*/
log(message) {
if (this.core && this.core.log) {
this.core.log(message)
} else {
debugLogger.log('system', 'info', `[${this.coreId}] ${message}`)
}
}
/**
* クリーンアップ
*/
async clear() {
// 待機中のIntent処理をクリア
this.pendingIntents.clear()
// 履歴とミドルウェアをクリア
this.intentHistory = []
this.middleware = []
// ハンドラをクリア
this.intentHandlers.clear()
this.initializeHandlers() // 必要であれば、デフォルトハンドラを再登録
// 統計リセット
this.stats = {
totalIntents: 0,
systemIntents: 0,
pluginIntents: 0,
bootIntents: 0,
fusionIntents: 0,
customIntents: 0,
successfulIntents: 0,
failedIntents: 0,
totalProcessingTime: 0,
startTime: Date.now()
}
this.log('🧹 UnifiedIntentHandler cleared')
}
}
export default UnifiedIntentHandler