-
Notifications
You must be signed in to change notification settings - Fork 312
Expand file tree
/
Copy pathPlugin.js
More file actions
executable file
·1510 lines (1344 loc) · 80.5 KB
/
Plugin.js
File metadata and controls
executable file
·1510 lines (1344 loc) · 80.5 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
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Plugin.js
const fs = require('fs').promises;
const EventEmitter = require('events');
const path = require('path');
const { spawn } = require('child_process');
const schedule = require('node-schedule');
const dotenv = require('dotenv'); // Ensures dotenv is available
const FileFetcherServer = require('./FileFetcherServer.js');
const express = require('express'); // For plugin API routing
const chokidar = require('chokidar');
const { getAuthCode } = require('./modules/captchaDecoder'); // 导入统一的解码函数
const ToolApprovalManager = require('./modules/toolApprovalManager');
const { hasFoldMarkers, buildDynamicFoldObject } = require('./modules/foldProtocol');
const PLUGIN_DIR = path.join(__dirname, 'Plugin');
const manifestFileName = 'plugin-manifest.json';
const PREPROCESSOR_ORDER_FILE = path.join(__dirname, 'preprocessor_order.json');
class PluginManager extends EventEmitter {
constructor() {
super();
this.plugins = new Map(); // 存储所有插件(本地和分布式)
this.staticPlaceholderValues = new Map();
this.scheduledJobs = new Map();
this.messagePreprocessors = new Map();
this.preprocessorOrder = []; // 新增:用于存储预处理器的最终加载顺序
this.serviceModules = new Map();
this.projectBasePath = null;
this.individualPluginDescriptions = new Map(); // New map for individual descriptions
this.debugMode = (process.env.DebugMode || "False").toLowerCase() === "true";
this.webSocketServer = null; // 为 WebSocketServer 实例占位
this.isReloading = false;
this.reloadTimeout = null;
this.vectorDBManager = null; // 修复:不再自己创建,等待注入
this.toolApprovalManager = new ToolApprovalManager(path.join(__dirname, 'toolApprovalConfig.json'));
this.pendingApprovals = new Map(); // requestId -> { resolve, reject, timeoutId }
}
setWebSocketServer(wss) {
this.webSocketServer = wss;
if (this.debugMode) console.log('[PluginManager] WebSocketServer instance has been set.');
}
setVectorDBManager(vdbManager) {
this.vectorDBManager = vdbManager;
if (this.debugMode) console.log('[PluginManager] VectorDBManager instance has been set.');
}
async _getDecryptedAuthCode() {
try {
const authCodePath = path.join(__dirname, 'Plugin', 'UserAuth', 'code.bin');
// 使用正确的 getAuthCode 函数,并传递文件路径
return await getAuthCode(authCodePath);
} catch (error) {
if (this.debugMode) {
console.error('[PluginManager] Failed to read or decrypt auth code for plugin execution:', error.message);
}
return null; // Return null if code cannot be obtained
}
}
setProjectBasePath(basePath) {
this.projectBasePath = basePath;
if (this.debugMode) console.log(`[PluginManager] Project base path set to: ${this.projectBasePath}`);
}
_getPluginConfig(pluginManifest) {
const config = {};
const globalEnv = process.env;
const pluginSpecificEnv = pluginManifest.pluginSpecificEnvConfig || {};
if (pluginManifest.configSchema) {
for (const key in pluginManifest.configSchema) {
const schemaEntry = pluginManifest.configSchema[key];
// 兼容两种格式:对象格式 { type: "string", ... } 和简单字符串格式 "string"
const expectedType = (typeof schemaEntry === 'object' && schemaEntry !== null)
? schemaEntry.type
: schemaEntry;
let rawValue;
if (pluginSpecificEnv.hasOwnProperty(key)) {
rawValue = pluginSpecificEnv[key];
} else if (globalEnv.hasOwnProperty(key)) {
rawValue = globalEnv[key];
} else {
continue;
}
let value = rawValue;
if (expectedType === 'integer') {
value = parseInt(value, 10);
if (isNaN(value)) {
if (this.debugMode) console.warn(`[PluginManager] Config key '${key}' for ${pluginManifest.name} expected integer, got NaN from raw value '${rawValue}'. Using undefined.`);
value = undefined;
}
} else if (expectedType === 'boolean') {
value = String(value).toLowerCase() === 'true';
}
config[key] = value;
}
}
if (pluginSpecificEnv.hasOwnProperty('DebugMode')) {
config.DebugMode = String(pluginSpecificEnv.DebugMode).toLowerCase() === 'true';
} else if (globalEnv.hasOwnProperty('DebugMode')) {
config.DebugMode = String(globalEnv.DebugMode).toLowerCase() === 'true';
} else if (!config.hasOwnProperty('DebugMode')) {
config.DebugMode = false;
}
return config;
}
getResolvedPluginConfigValue(pluginName, configKey) {
const pluginManifest = this.plugins.get(pluginName);
if (!pluginManifest) {
return undefined;
}
const effectiveConfig = this._getPluginConfig(pluginManifest);
return effectiveConfig ? effectiveConfig[configKey] : undefined;
}
async _executeStaticPluginCommand(plugin) {
if (!plugin || plugin.pluginType !== 'static' || !plugin.entryPoint || !plugin.entryPoint.command) {
console.error(`[PluginManager] Invalid static plugin or command for execution: ${plugin ? plugin.name : 'Unknown'}`);
return Promise.reject(new Error(`Invalid static plugin or command for ${plugin ? plugin.name : 'Unknown'}`));
}
return new Promise((resolve, reject) => {
const pluginConfig = this._getPluginConfig(plugin);
const envForProcess = { ...process.env };
for (const key in pluginConfig) {
if (pluginConfig.hasOwnProperty(key) && pluginConfig[key] !== undefined) {
envForProcess[key] = String(pluginConfig[key]);
}
}
if (this.projectBasePath) { // Add projectBasePath for static plugins too if needed
envForProcess.PROJECT_BASE_PATH = this.projectBasePath;
}
const [command, ...args] = plugin.entryPoint.command.split(' ');
const pluginProcess = spawn(command, args, { cwd: plugin.basePath, shell: true, env: envForProcess, windowsHide: true });
let output = '';
let errorOutput = '';
let processExited = false;
const timeoutDuration = plugin.communication?.timeout || 60000; // 增加默认超时时间到 1 分钟
const timeoutId = setTimeout(() => {
if (!processExited) {
console.log(`[PluginManager] Static plugin "${plugin.name}" has completed its work cycle (${timeoutDuration}ms), terminating background process.`);
pluginProcess.kill('SIGKILL');
// 超时不作为错误 - static 插件完成工作周期后返回已收集的输出
resolve(output.trim());
}
}, timeoutDuration);
pluginProcess.stdout.on('data', (data) => { output += data.toString(); });
pluginProcess.stderr.on('data', (data) => { errorOutput += data.toString(); });
pluginProcess.on('error', (err) => {
processExited = true;
clearTimeout(timeoutId);
console.error(`[PluginManager] Failed to start static plugin ${plugin.name}: ${err.message}`);
reject(err);
});
pluginProcess.on('exit', (code, signal) => {
processExited = true;
clearTimeout(timeoutId);
if (signal === 'SIGKILL') {
// 被 SIGKILL 终止(超时),已经在 timeout 回调中 resolve 了,这里直接返回
return;
}
if (code !== 0) {
const errMsg = `Static plugin ${plugin.name} exited with code ${code}. Stderr: ${errorOutput.trim()}`;
console.error(`[PluginManager] ${errMsg}`);
reject(new Error(errMsg));
} else {
if (errorOutput.trim() && this.debugMode) {
console.warn(`[PluginManager] Static plugin ${plugin.name} produced stderr output: ${errorOutput.trim()}`);
}
resolve(output.trim());
}
});
});
}
async _updateStaticPluginValue(plugin) {
let newValue = null;
let executionError = null;
try {
if (this.debugMode) console.log(`[PluginManager] Updating static plugin: ${plugin.name}`);
newValue = await this._executeStaticPluginCommand(plugin);
} catch (error) {
console.error(`[PluginManager] Error executing static plugin ${plugin.name} script:`, error.message);
executionError = error;
}
if (plugin.capabilities && plugin.capabilities.systemPromptPlaceholders) {
plugin.capabilities.systemPromptPlaceholders.forEach(ph => {
const placeholderKey = ph.placeholder;
const currentValueEntry = this.staticPlaceholderValues.get(placeholderKey);
const currentValue = currentValueEntry ? currentValueEntry.value : undefined;
let parsedValue = newValue;
if (newValue !== null) {
const trimmedValue = newValue.trim();
parsedValue = trimmedValue;
try {
// 优先兼容原有 JSON dynamic fold 协议
if (trimmedValue.startsWith('{')) {
const jsonObj = JSON.parse(trimmedValue);
if (jsonObj && jsonObj.vcp_dynamic_fold) {
parsedValue = jsonObj; // 保持对象形式以供折叠处理
}
} else if (hasFoldMarkers(trimmedValue)) {
// 兼容共享的文本折叠协议,支持 [===vcp_fold: x ::desc: ...===]
parsedValue = buildDynamicFoldObject({
content: trimmedValue,
pluginDescription: plugin.description || plugin.displayName || plugin.name,
strategy: 'toolbox_block_similarity'
});
}
} catch (e) {
if (hasFoldMarkers(trimmedValue)) {
parsedValue = buildDynamicFoldObject({
content: trimmedValue,
pluginDescription: plugin.description || plugin.displayName || plugin.name,
strategy: 'toolbox_block_similarity'
});
} else {
parsedValue = trimmedValue;
}
}
}
if (parsedValue !== null && parsedValue !== "") {
this.staticPlaceholderValues.set(placeholderKey, { value: parsedValue, serverId: 'local' });
if (this.debugMode) {
const logVal = typeof parsedValue === 'object' ? JSON.stringify(parsedValue) : parsedValue;
console.log(`[PluginManager] Placeholder ${placeholderKey} for ${plugin.name} updated with value: "${logVal.substring(0, 70)}..."`);
}
} else if (executionError) {
const errorMessage = `[Error updating ${plugin.name}: ${executionError.message.substring(0, 100)}...]`;
if (!currentValue || (typeof currentValue === 'string' && currentValue.startsWith("[Error"))) {
this.staticPlaceholderValues.set(placeholderKey, { value: errorMessage, serverId: 'local' });
if (this.debugMode) console.warn(`[PluginManager] Placeholder ${placeholderKey} for ${plugin.name} set to error state: ${errorMessage}`);
} else {
if (this.debugMode) console.warn(`[PluginManager] Placeholder ${placeholderKey} for ${plugin.name} failed to update. Keeping stale value: "${(typeof currentValue === 'string' ? currentValue : JSON.stringify(currentValue)).substring(0, 70)}..."`);
}
} else {
if (this.debugMode) console.warn(`[PluginManager] Static plugin ${plugin.name} produced no new output for ${placeholderKey}. Keeping stale value (if any).`);
if (!currentValueEntry) {
this.staticPlaceholderValues.set(placeholderKey, { value: `[${plugin.name} data currently unavailable]`, serverId: 'local' });
if (this.debugMode) console.log(`[PluginManager] Placeholder ${placeholderKey} for ${plugin.name} set to 'unavailable'.`);
}
}
});
}
}
async initializeStaticPlugins() {
console.log('[PluginManager] Initializing static plugins...');
for (const plugin of this.plugins.values()) {
if (plugin.pluginType === 'static') {
// Immediately set a "loading" state for the placeholder.
if (plugin.capabilities && plugin.capabilities.systemPromptPlaceholders) {
plugin.capabilities.systemPromptPlaceholders.forEach(ph => {
this.staticPlaceholderValues.set(ph.placeholder, { value: `[${plugin.displayName} a-zheng-zai-jia-zai-zhong... ]`, serverId: 'local' });
});
}
// Trigger the first update in the background (fire and forget).
this._updateStaticPluginValue(plugin).catch(err => {
console.error(`[PluginManager] Initial background update for ${plugin.name} failed: ${err.message}`);
});
// Set up the scheduled recurring updates.
if (plugin.refreshIntervalCron) {
if (this.scheduledJobs.has(plugin.name)) {
this.scheduledJobs.get(plugin.name).cancel();
}
try {
const job = schedule.scheduleJob(plugin.refreshIntervalCron, () => {
if (this.debugMode) console.log(`[PluginManager] Scheduled update for static plugin: ${plugin.name}`);
this._updateStaticPluginValue(plugin).catch(err => {
console.error(`[PluginManager] Scheduled background update for ${plugin.name} failed: ${err.message}`);
});
});
this.scheduledJobs.set(plugin.name, job);
if (this.debugMode) console.log(`[PluginManager] Scheduled ${plugin.name} with cron: ${plugin.refreshIntervalCron}`);
} catch (e) {
console.error(`[PluginManager] Invalid cron string for ${plugin.name}: ${plugin.refreshIntervalCron}. Error: ${e.message}`);
}
}
}
}
console.log('[PluginManager] Static plugins initialization process has been started (updates will run in the background).');
}
async prewarmPythonPlugins() {
console.log('[PluginManager] Checking for Python plugins to pre-warm...');
if (this.plugins.has('SciCalculator')) {
console.log('[PluginManager] SciCalculator found. Starting pre-warming of Python scientific libraries in the background.');
try {
const command = 'python';
const args = ['-c', 'import sympy, scipy.stats, scipy.integrate, numpy'];
const prewarmProcess = spawn(command, args, {
// 移除 shell: true
windowsHide: true
});
prewarmProcess.on('error', (err) => {
console.warn(`[PluginManager] Python pre-warming process failed to start. Is Python installed and in the system's PATH? Error: ${err.message}`);
});
prewarmProcess.stderr.on('data', (data) => {
console.warn(`[PluginManager] Python pre-warming process stderr: ${data.toString().trim()}`);
});
prewarmProcess.on('exit', (code) => {
if (code === 0) {
console.log('[PluginManager] Python scientific libraries pre-warmed successfully.');
} else {
console.warn(`[PluginManager] Python pre-warming process exited with code ${code}. Please ensure required libraries are installed (pip install sympy scipy numpy).`);
}
});
} catch (e) {
console.error(`[PluginManager] An exception occurred while spawning the Python pre-warming process: ${e.message}`);
}
} else {
if (this.debugMode) console.log('[PluginManager] SciCalculator not found, skipping Python pre-warming.');
}
}
getPlaceholderValue(placeholder) {
// First, try the modern, clean key (e.g., "VCPChromePageInfo")
let entry = this.staticPlaceholderValues.get(placeholder);
// If not found, try the legacy key with brackets (e.g., "{{VCPChromePageInfo}}")
if (entry === undefined) {
entry = this.staticPlaceholderValues.get(`{{${placeholder}}}`);
}
// If still not found, return the "not found" message
if (entry === undefined) {
return `[Placeholder ${placeholder} not found]`;
}
// Now, handle the value format
// Modern format: { value: "...", serverId: "..." }
if (typeof entry === 'object' && entry !== null && entry.hasOwnProperty('value')) {
return entry.value;
}
// Legacy format: raw string
if (typeof entry === 'string') {
return entry;
}
// Fallback for unexpected formats
return `[Invalid value format for placeholder ${placeholder}]`;
}
async executeMessagePreprocessor(pluginName, messages) {
const processorModule = this.messagePreprocessors.get(pluginName);
const pluginManifest = this.plugins.get(pluginName);
if (!processorModule || !pluginManifest) {
console.error(`[PluginManager] Message preprocessor plugin "${pluginName}" not found.`);
return messages;
}
if (typeof processorModule.processMessages !== 'function') {
console.error(`[PluginManager] Plugin "${pluginName}" does not have 'processMessages' function.`);
return messages;
}
try {
if (this.debugMode) console.log(`[PluginManager] Executing message preprocessor: ${pluginName}`);
const pluginSpecificConfig = this._getPluginConfig(pluginManifest);
const processedMessages = await processorModule.processMessages(messages, pluginSpecificConfig);
if (this.debugMode) console.log(`[PluginManager] Message preprocessor ${pluginName} finished.`);
return processedMessages;
} catch (error) {
console.error(`[PluginManager] Error in message preprocessor ${pluginName}:`, error);
return messages;
}
}
async shutdownAllPlugins() {
console.log('[PluginManager] Shutting down all plugins...'); // Keep
// --- Shutdown VectorDBManager first to stop background processing ---
if (this.vectorDBManager && typeof this.vectorDBManager.shutdown === 'function') {
try {
if (this.debugMode) console.log('[PluginManager] Calling shutdown for VectorDBManager...');
await this.vectorDBManager.shutdown();
} catch (error) {
console.error('[PluginManager] Error during shutdown of VectorDBManager:', error);
}
}
for (const [name, pluginModuleData] of this.messagePreprocessors) {
const pluginModule = pluginModuleData.module || pluginModuleData;
if (pluginModule && typeof pluginModule.shutdown === 'function') {
try {
if (this.debugMode) console.log(`[PluginManager] Calling shutdown for ${name}...`);
await pluginModule.shutdown();
} catch (error) {
console.error(`[PluginManager] Error during shutdown of plugin ${name}:`, error); // Keep error
}
}
}
for (const [name, serviceData] of this.serviceModules) {
if (serviceData.module && typeof serviceData.module.shutdown === 'function') {
try {
if (this.debugMode) console.log(`[PluginManager] Calling shutdown for service plugin ${name}...`);
await serviceData.module.shutdown();
} catch (error) {
console.error(`[PluginManager] Error during shutdown of service plugin ${name}:`, error); // Keep error
}
}
}
for (const job of this.scheduledJobs.values()) {
job.cancel();
}
this.scheduledJobs.clear();
console.log('[PluginManager] All plugin shutdown processes initiated and scheduled jobs cancelled.'); // Keep
}
async loadPlugins() {
console.log('[PluginManager] Starting plugin discovery...');
// 1. 清理现有插件状态
// 1.1 识别并关闭本地插件,保留分布式插件
const distributedPlugins = new Map();
const localModulesToShutdown = new Set();
for (const [name, manifest] of this.plugins.entries()) {
if (manifest.isDistributed) {
distributedPlugins.set(name, manifest);
} else {
// 收集本地插件模块以进行清理
const preprocessor = this.messagePreprocessors.get(name);
if (preprocessor) localModulesToShutdown.add(preprocessor);
const service = this.serviceModules.get(name)?.module;
if (service) localModulesToShutdown.add(service);
}
}
// 执行清理:在重新加载前关闭旧的本地插件实例,释放资源
for (const module of localModulesToShutdown) {
if (typeof module.shutdown === 'function') {
try {
module.shutdown();
} catch (e) {
console.error(`[PluginManager] Error during hot-reload shutdown of a plugin:`, e.message);
}
}
}
this.plugins = distributedPlugins; // 仅保留分布式插件,本地插件将被重新发现
this.messagePreprocessors.clear();
this.staticPlaceholderValues.clear();
this.serviceModules.clear();
const discoveredPreprocessors = new Map();
const modulesToInitialize = [];
try {
// 2. 发现并加载所有插件模块,但不初始化
const pluginFolders = await fs.readdir(PLUGIN_DIR, { withFileTypes: true });
for (const folder of pluginFolders) {
if (folder.isDirectory()) {
const pluginPath = path.join(PLUGIN_DIR, folder.name);
const manifestPath = path.join(pluginPath, manifestFileName);
try {
const manifestContent = await fs.readFile(manifestPath, 'utf-8');
const manifest = JSON.parse(manifestContent);
if (!manifest.name || !manifest.pluginType || !manifest.entryPoint) continue;
if (this.plugins.has(manifest.name)) continue;
manifest.basePath = pluginPath;
manifest.pluginSpecificEnvConfig = {};
try {
const pluginEnvContent = await fs.readFile(path.join(pluginPath, 'config.env'), 'utf-8');
manifest.pluginSpecificEnvConfig = dotenv.parse(pluginEnvContent);
} catch (envError) {
if (envError.code !== 'ENOENT') console.warn(`[PluginManager] Error reading config.env for ${manifest.name}:`, envError.message);
}
this.plugins.set(manifest.name, manifest);
console.log(`[PluginManager] Loaded manifest: ${manifest.displayName} (${manifest.name}, Type: ${manifest.pluginType})`);
const isPreprocessor = manifest.pluginType === 'messagePreprocessor' || manifest.pluginType === 'hybridservice';
const isService = manifest.pluginType === 'service' || manifest.pluginType === 'hybridservice';
if ((isPreprocessor || isService) && manifest.entryPoint.script && manifest.communication?.protocol === 'direct') {
try {
const scriptPath = path.join(pluginPath, manifest.entryPoint.script);
const module = require(scriptPath);
modulesToInitialize.push({ manifest, module });
if (isPreprocessor && typeof module.processMessages === 'function') {
discoveredPreprocessors.set(manifest.name, module);
}
if (isService) {
this.serviceModules.set(manifest.name, { manifest, module });
}
} catch (e) {
console.error(`[PluginManager] Error loading module for ${manifest.name}:`, e);
}
}
} catch (error) {
if (error.code !== 'ENOENT' && !(error instanceof SyntaxError)) {
console.error(`[PluginManager] Error loading plugin from ${folder.name}:`, error);
}
}
}
}
// 3. 确定预处理器加载顺序
const availablePlugins = new Set(discoveredPreprocessors.keys());
let finalOrder = [];
try {
const orderContent = await fs.readFile(PREPROCESSOR_ORDER_FILE, 'utf-8');
const savedOrder = JSON.parse(orderContent);
if (Array.isArray(savedOrder)) {
savedOrder.forEach(pluginName => {
if (availablePlugins.has(pluginName)) {
finalOrder.push(pluginName);
availablePlugins.delete(pluginName);
}
});
}
} catch (error) {
if (error.code !== 'ENOENT') console.error(`[PluginManager] Error reading existing ${PREPROCESSOR_ORDER_FILE}:`, error);
}
finalOrder.push(...Array.from(availablePlugins).sort());
// 4. 注册预处理器
for (const pluginName of finalOrder) {
this.messagePreprocessors.set(pluginName, discoveredPreprocessors.get(pluginName));
}
this.preprocessorOrder = finalOrder;
if (finalOrder.length > 0) console.log('[PluginManager] Final message preprocessor order: ' + finalOrder.join(' -> '));
// 5. VectorDBManager 应该已经由 server.js 初始化,这里不再重复初始化
if (!this.vectorDBManager) {
console.warn('[PluginManager] VectorDBManager not set! Plugins requiring it may fail.');
}
// 6. 按顺序初始化所有模块
const allModulesMap = new Map(modulesToInitialize.map(m => [m.manifest.name, m]));
const initializationOrder = [...this.preprocessorOrder];
allModulesMap.forEach((_, name) => {
if (!initializationOrder.includes(name)) {
initializationOrder.push(name);
}
});
for (const pluginName of initializationOrder) {
const item = allModulesMap.get(pluginName);
if (!item || typeof item.module.initialize !== 'function') continue;
const { manifest, module } = item;
try {
const initialConfig = this._getPluginConfig(manifest);
initialConfig.PORT = process.env.PORT;
initialConfig.Key = process.env.Key;
initialConfig.PROJECT_BASE_PATH = this.projectBasePath;
const dependencies = { vcpLogFunctions: this.getVCPLogFunctions() };
// --- 注入 VectorDBManager ---
if (manifest.name === 'RAGDiaryPlugin') {
dependencies.vectorDBManager = this.vectorDBManager;
}
// --- 🌟 ContextBridge 通用依赖注入 ---
// 任何在 manifest 中声明 "requiresContextBridge": true 的插件都能获得 RAG 上下文向量接口
if (manifest.requiresContextBridge) {
const ragPluginModule = this.messagePreprocessors.get('RAGDiaryPlugin');
if (ragPluginModule && typeof ragPluginModule.getContextBridge === 'function') {
dependencies.contextBridge = ragPluginModule.getContextBridge();
if (this.debugMode) console.log(`[PluginManager] 🌟 Injected ContextBridge into ${manifest.name}.`);
} else {
console.warn(`[PluginManager] Plugin "${manifest.name}" requires ContextBridge, but RAGDiaryPlugin is not available.`);
}
}
// --- LightMemo 特殊依赖注入(向后兼容 + ContextBridge) ---
if (manifest.name === 'LightMemo') {
const ragPluginModule = this.messagePreprocessors.get('RAGDiaryPlugin');
if (ragPluginModule && ragPluginModule.vectorDBManager && typeof ragPluginModule.getSingleEmbedding === 'function') {
dependencies.vectorDBManager = ragPluginModule.vectorDBManager;
dependencies.getSingleEmbedding = ragPluginModule.getSingleEmbedding.bind(ragPluginModule);
// 同时注入 ContextBridge(如果 LightMemo 未在 manifest 中声明,也主动注入)
if (!dependencies.contextBridge && typeof ragPluginModule.getContextBridge === 'function') {
dependencies.contextBridge = ragPluginModule.getContextBridge();
}
if (this.debugMode) console.log(`[PluginManager] Injected VectorDBManager, getSingleEmbedding and ContextBridge into LightMemo.`);
} else {
console.error(`[PluginManager] Critical dependency failure: RAGDiaryPlugin or its components not available for LightMemo injection.`);
}
}
// --- 注入结束 ---
await module.initialize(initialConfig, dependencies);
} catch (e) {
console.error(`[PluginManager] Error initializing module for ${manifest.name}:`, e instanceof Error ? e.message : JSON.stringify(e));
if (e instanceof Error && e.stack) {
console.error(`[PluginManager] Stack trace for ${manifest.name}:`, e.stack);
}
}
}
this.buildVCPDescription();
this.emit('tools_changed', { reason: 'local_reload' });
console.log(`[PluginManager] Plugin discovery finished. Loaded ${this.plugins.size} plugins.`);
} catch (error) {
if (error.code === 'ENOENT') console.error(`[PluginManager] Plugin directory ${PLUGIN_DIR} not found.`);
else console.error('[PluginManager] Error reading plugin directory:', error);
}
}
buildVCPDescription() {
this.individualPluginDescriptions.clear(); // Clear previous descriptions
let overallLog = ['[PluginManager] Building individual VCP descriptions:'];
for (const plugin of this.plugins.values()) {
if (plugin.capabilities && plugin.capabilities.invocationCommands && plugin.capabilities.invocationCommands.length > 0) {
let pluginSpecificDescriptions = [];
plugin.capabilities.invocationCommands.forEach(cmd => {
if (cmd.description) {
let commandDescription = `- ${plugin.displayName} (${plugin.name}) - 命令: ${cmd.command || 'N/A'}:\n`; // Assuming cmd might have a 'command' field or similar identifier
const indentedCmdDescription = cmd.description.split('\n').map(line => ` ${line}`).join('\n');
commandDescription += `${indentedCmdDescription}`;
if (cmd.example) {
const exampleHeader = `\n 调用示例:\n`;
const indentedExample = cmd.example.split('\n').map(line => ` ${line}`).join('\n');
commandDescription += exampleHeader + indentedExample;
}
pluginSpecificDescriptions.push(commandDescription);
}
});
if (pluginSpecificDescriptions.length > 0) {
const placeholderKey = `VCP${plugin.name}`;
const fullDescriptionForPlugin = pluginSpecificDescriptions.join('\n\n');
this.individualPluginDescriptions.set(placeholderKey, fullDescriptionForPlugin);
overallLog.push(` - Generated description for {{${placeholderKey}}} (Length: ${fullDescriptionForPlugin.length})`);
}
}
}
if (this.individualPluginDescriptions.size === 0) {
overallLog.push(" - No VCP plugins with invocation commands found to generate descriptions for.");
}
if (this.debugMode) console.log(overallLog.join('\n'));
}
// New method to get all individual descriptions
getIndividualPluginDescriptions() {
return this.individualPluginDescriptions;
}
getAllPlaceholderValues() {
return this.staticPlaceholderValues;
}
// getVCPDescription() { // This method is no longer needed as VCPDescription is deprecated
// return this.vcpDescription;
// }
getPlugin(name) {
return this.plugins.get(name);
}
getServiceModule(name) {
return this.serviceModules.get(name)?.module;
}
// 新增:获取 VCPLog 插件的推送函数,供其他插件依赖注入
getVCPLogFunctions() {
const vcpLogModule = this.getServiceModule('VCPLog');
const self = this;
return {
pushVcpLog: (data) => {
if (vcpLogModule && typeof vcpLogModule.pushVcpLog === 'function') {
vcpLogModule.pushVcpLog(data);
}
self.emit('vcp_log', data);
},
pushVcpInfo: (data) => {
if (vcpLogModule && typeof vcpLogModule.pushVcpInfo === 'function') {
vcpLogModule.pushVcpInfo(data);
}
self.emit('vcp_info', data);
}
};
}
async processToolCall(toolName, toolArgs, requestIp = null) {
const plugin = this.plugins.get(toolName);
if (!plugin) {
throw new Error(`[PluginManager] Plugin "${toolName}" not found for tool call.`);
}
// Helper function to generate a timestamp string
const _getFormattedLocalTimestamp = () => {
const date = new Date();
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
const seconds = date.getSeconds().toString().padStart(2, '0');
const milliseconds = date.getMilliseconds().toString().padStart(3, '0');
const timezoneOffsetMinutes = date.getTimezoneOffset();
const offsetSign = timezoneOffsetMinutes > 0 ? "-" : "+";
const offsetHours = Math.abs(Math.floor(timezoneOffsetMinutes / 60)).toString().padStart(2, '0');
const offsetMinutes = Math.abs(timezoneOffsetMinutes % 60).toString().padStart(2, '0');
const timezoneString = `${offsetSign}${offsetHours}:${offsetMinutes}`;
return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${milliseconds}${timezoneString}`;
};
const maidNameFromArgs = toolArgs && toolArgs.maid ? toolArgs.maid : null;
const pluginSpecificArgs = { ...toolArgs };
if (maidNameFromArgs) {
// The 'maid' parameter is intentionally passed through for plugins like DeepMemo.
// delete pluginSpecificArgs.maid;
}
// --- 预先拉取所有的异地文件,将其透明化 ---
// 逻辑漏洞修复:如果是分布式插件,则不进行预拉取,直接透传 file:// 协议,由分布式端自行处理
if (!plugin.isDistributed) {
const resolveArgsUrls = async (obj) => {
if (!obj || typeof obj !== 'object') return;
for (const key of Object.keys(obj)) {
const val = obj[key];
if (typeof val === 'string') {
if (val.startsWith('file://')) {
if (this.debugMode) console.log(`[PluginManager] Intercepted file URL in args: ${val}`);
obj[key] = await FileFetcherServer.resolveFileUrl(val, requestIp);
} else if (val.includes('file://')) {
// 优化正则表达式:增加对中文标点(),。?!)和换行符的排除,防止匹配过长导致解析失败
const fileRegex = /file:\/\/[^\s"'()\]\}\>,。?!)\r\n]+/g;
const matches = val.match(fileRegex);
if (matches) {
let newVal = val;
for (const matchUrl of matches) {
if (this.debugMode) console.log(`[PluginManager] Intercepted embedded file URL in args: ${matchUrl}`);
const resolvedUrl = await FileFetcherServer.resolveFileUrl(matchUrl, requestIp);
newVal = newVal.split(matchUrl).join(resolvedUrl); // replaceAll fallback
}
obj[key] = newVal;
}
}
} else if (typeof val === 'object' && val !== null) {
await resolveArgsUrls(val);
}
}
};
try {
await resolveArgsUrls(pluginSpecificArgs);
} catch (resolveError) {
throw new Error(JSON.stringify({ plugin_error: `Failed to pre-fetch files: ${resolveError.message}` }));
}
}
// --- 透明化处理结束 ---
// --- 人工审核逻辑 (新增) ---
const approvalDecision = this.toolApprovalManager.getApprovalDecision(toolName, pluginSpecificArgs);
if (approvalDecision.requiresApproval) {
const requestId = `approve-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
if (this.debugMode) {
console.log(
`[PluginManager] Tool call for "${toolName}" requires manual approval. Request ID: ${requestId}. notifyAiOnReject=${approvalDecision.notifyAiOnReject !== false}`
);
}
const approvalPromise = new Promise((resolve, reject) => {
const timeoutDuration = this.toolApprovalManager.getTimeoutMs();
const timeoutId = setTimeout(() => {
if (this.pendingApprovals.has(requestId)) {
this.pendingApprovals.delete(requestId);
reject(new Error(JSON.stringify({ plugin_error: `Manual approval for "${toolName}" timed out after ${timeoutDuration / 60000} minutes.` })));
}
}, timeoutDuration);
this.pendingApprovals.set(requestId, {
resolve,
reject,
timeoutId,
notifyAiOnReject: approvalDecision.notifyAiOnReject !== false
});
});
// 发送审核请求到管理面板
if (this.webSocketServer) {
const approvalRequest = {
type: 'tool_approval_request',
data: {
requestId,
toolName,
maid: maidNameFromArgs,
args: pluginSpecificArgs,
timestamp: _getFormattedLocalTimestamp()
}
};
this.webSocketServer.broadcast(approvalRequest, 'VCPLog');
console.log(`[PluginManager] 🔔 正在等待工具调用人工审核: ${toolName} (ID: ${requestId})`);
} else {
this.pendingApprovals.delete(requestId);
throw new Error(JSON.stringify({ plugin_error: 'WebSocketServer not initialized, cannot request manual approval.' }));
}
try {
const approvalResult = await approvalPromise;
if (approvalResult && approvalResult.silentRejected === true) {
if (this.debugMode) {
console.log(`[PluginManager] Tool call for "${toolName}" (ID: ${requestId}) was rejected silently. Returning empty result to AI.`);
}
return undefined;
}
if (this.debugMode) console.log(`[PluginManager] Tool call for "${toolName}" (ID: ${requestId}) approved.`);
} catch (error) {
if (this.debugMode) console.warn(`[PluginManager] Tool call for "${toolName}" (ID: ${requestId}) rejected: ${error.message}`);
throw error;
}
}
// --- 人工审核逻辑结束 ---
try {
let resultFromPlugin;
if (plugin.isDistributed) {
// --- 分布式插件调用逻辑 ---
if (!this.webSocketServer) {
throw new Error('[PluginManager] WebSocketServer is not initialized. Cannot call distributed tool.');
}
if (this.debugMode) console.log(`[PluginManager] Processing distributed tool call for: ${toolName} on server ${plugin.serverId}`);
resultFromPlugin = await this.webSocketServer.executeDistributedTool(plugin.serverId, toolName, pluginSpecificArgs);
// 分布式工具的返回结果应该已经是JS对象了
} else if (toolName === 'ChromeControl' && plugin.communication?.protocol === 'direct') {
// --- ChromeControl 特殊处理逻辑 ---
if (!this.webSocketServer) {
throw new Error('[PluginManager] WebSocketServer is not initialized. Cannot call ChromeControl tool.');
}
if (this.debugMode) console.log(`[PluginManager] Processing direct WebSocket tool call for: ${toolName}`);
const command = pluginSpecificArgs.command;
delete pluginSpecificArgs.command;
resultFromPlugin = await this.webSocketServer.forwardCommandToChrome(command, pluginSpecificArgs);
} else if (plugin.pluginType === 'hybridservice' && plugin.communication?.protocol === 'direct') {
// --- 混合服务插件直接调用逻辑 ---
if (this.debugMode) console.log(`[PluginManager] Processing direct tool call for hybrid service: ${toolName}`);
const serviceModule = this.getServiceModule(toolName);
if (!serviceModule) {
throw new Error(`[PluginManager] Hybrid service plugin "${toolName}" module not found. It may have failed to load or initialize during hot-reload.`);
}
if (typeof serviceModule.processToolCall !== 'function') {
throw new Error(`[PluginManager] Hybrid service plugin "${toolName}" does not have a processToolCall function.`);
}
resultFromPlugin = await serviceModule.processToolCall(pluginSpecificArgs);
} else {
// --- 本地插件调用逻辑 (现有逻辑) ---
if (!((plugin.pluginType === 'synchronous' || plugin.pluginType === 'asynchronous') && plugin.communication?.protocol === 'stdio')) {
throw new Error(`[PluginManager] Local plugin "${toolName}" (type: ${plugin.pluginType}) is not a supported stdio plugin for direct tool call.`);
}
let executionParam = null;
if (Object.keys(pluginSpecificArgs).length > 0) {
executionParam = JSON.stringify(pluginSpecificArgs);
}
const logParam = executionParam ? (executionParam.length > 100 ? executionParam.substring(0, 100) + '...' : executionParam) : null;
if (this.debugMode) console.log(`[PluginManager] Calling local executePlugin for: ${toolName} with prepared param:`, logParam);
const pluginOutput = await this.executePlugin(toolName, executionParam, requestIp); // Returns {status, result/error}
if (pluginOutput.status === "success") {
if (typeof pluginOutput.result === 'string') {
try {
// If the result is a string, try to parse it as JSON.
resultFromPlugin = JSON.parse(pluginOutput.result);
} catch (parseError) {
// If parsing fails, wrap it. This is for plugins that return plain text.
if (this.debugMode) console.warn(`[PluginManager] Local plugin ${toolName} result string was not valid JSON. Original: "${pluginOutput.result.substring(0, 100)}"`);
resultFromPlugin = { original_plugin_output: pluginOutput.result };
}
} else {
// If the result is already an object (as with our new image plugins), use it directly.
resultFromPlugin = pluginOutput.result;
}
} else {
throw new Error(JSON.stringify({ plugin_error: pluginOutput.error || `Plugin "${toolName}" reported an unspecified error.` }));
}
}
// --- 通用结果处理 ---
let finalResultObject = (typeof resultFromPlugin === 'object' && resultFromPlugin !== null) ? resultFromPlugin : { original_plugin_output: resultFromPlugin };
if (maidNameFromArgs) {
finalResultObject.MaidName = maidNameFromArgs;
}
finalResultObject.timestamp = _getFormattedLocalTimestamp();
return finalResultObject;
} catch (e) {
console.error(`[PluginManager processToolCall] Error during execution for plugin ${toolName}:`, e.message);
let errorObject;
try {
errorObject = JSON.parse(e.message);
} catch (jsonParseError) {
errorObject = { plugin_execution_error: e.message || 'Unknown plugin execution error' };
}
if (maidNameFromArgs && !errorObject.MaidName) {
errorObject.MaidName = maidNameFromArgs;
}
if (!errorObject.timestamp) {
errorObject.timestamp = _getFormattedLocalTimestamp();
}
throw new Error(JSON.stringify(errorObject));
}
}
async executePlugin(pluginName, inputData, requestIp = null) {
const plugin = this.plugins.get(pluginName);
if (!plugin) {
// This case should ideally be caught by processToolCall before calling executePlugin
throw new Error(`[PluginManager executePlugin] Plugin "${pluginName}" not found.`);
}
// Validations for pluginType, communication, entryPoint remain important
if (!((plugin.pluginType === 'synchronous' || plugin.pluginType === 'asynchronous') && plugin.communication?.protocol === 'stdio')) {
throw new Error(`[PluginManager executePlugin] Plugin "${pluginName}" (type: ${plugin.pluginType}, protocol: ${plugin.communication?.protocol}) is not a supported stdio plugin. Expected synchronous or asynchronous stdio plugin.`);
}
if (!plugin.entryPoint || !plugin.entryPoint.command) {
throw new Error(`[PluginManager executePlugin] Entry point command undefined for plugin "${pluginName}".`);
}
const pluginConfig = this._getPluginConfig(plugin);
const envForProcess = { ...process.env };
for (const key in pluginConfig) {
if (pluginConfig.hasOwnProperty(key) && pluginConfig[key] !== undefined) {
envForProcess[key] = String(pluginConfig[key]);
}
}
const additionalEnv = {};
if (this.projectBasePath) {
additionalEnv.PROJECT_BASE_PATH = this.projectBasePath;
} else {
if (this.debugMode) console.warn("[PluginManager executePlugin] projectBasePath not set, PROJECT_BASE_PATH will not be available to plugins.");
}
// 如果插件需要管理员权限,则获取解密后的验证码并注入环境变量
if (plugin.requiresAdmin) {
const decryptedCode = await this._getDecryptedAuthCode();
if (decryptedCode) {
additionalEnv.DECRYPTED_AUTH_CODE = decryptedCode;
if (this.debugMode) console.log(`[PluginManager] Injected DECRYPTED_AUTH_CODE for admin-required plugin: ${pluginName}`);
} else {
if (this.debugMode) console.warn(`[PluginManager] Could not get decrypted auth code for admin-required plugin: ${pluginName}. Execution will proceed without it.`);
}
}
// 将 requestIp 添加到环境变量
if (requestIp) {
additionalEnv.VCP_REQUEST_IP = requestIp;
}
if (process.env.PORT) {
additionalEnv.SERVER_PORT = process.env.PORT;
}
const imageServerKey = this.getResolvedPluginConfigValue('ImageServer', 'Image_Key');
if (imageServerKey) {
additionalEnv.IMAGESERVER_IMAGE_KEY = imageServerKey;
}
const fileServerKey = this.getResolvedPluginConfigValue('ImageServer', 'File_Key');
if (fileServerKey) {
additionalEnv.IMAGESERVER_FILE_KEY = fileServerKey;
}
// Pass CALLBACK_BASE_URL and PLUGIN_NAME to asynchronous plugins
if (plugin.pluginType === 'asynchronous') {
const callbackBaseUrl = pluginConfig.CALLBACK_BASE_URL || process.env.CALLBACK_BASE_URL; // Prefer plugin-specific, then global
if (callbackBaseUrl) {
additionalEnv.CALLBACK_BASE_URL = callbackBaseUrl;
} else {
if (this.debugMode) console.warn(`[PluginManager executePlugin] CALLBACK_BASE_URL not configured for asynchronous plugin ${pluginName}. Callback functionality might be impaired.`);
}
additionalEnv.PLUGIN_NAME_FOR_CALLBACK = pluginName; // Pass the plugin's name
}
// Force Python stdio encoding to UTF-8