forked from lioensky/VCPToolBox
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlugin.js
More file actions
executable file
·2564 lines (2296 loc) · 128 KB
/
Copy pathPlugin.js
File metadata and controls
executable file
·2564 lines (2296 loc) · 128 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 { sanitizeToolResult } = require('./modules/toolResultPrivacyGuard');
const toolCallRecordStore = require('./modules/toolCallRecordStore');
const PLUGIN_DIR = path.join(__dirname, 'Plugin');
const manifestFileName = 'plugin-manifest.json';
const PREPROCESSOR_ORDER_FILE = path.join(__dirname, 'preprocessor_order.json');
const SSH_MANAGER_ENV_PLUGIN_ALLOWLIST = new Set([
'LinuxShellExecutor',
'LinuxLogMonitor'
]);
const LOG_MONITOR_ENV_PLUGIN_ALLOWLIST = new Set([
'LinuxLogMonitor'
]);
const EMBEDDED_FILE_URL_REGEX = /file:\/\/[^\s"'()\]\}\>,。?!)\r\n]+/g;
function 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');
return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${milliseconds}${offsetSign}${offsetHours}:${offsetMinutes}`;
}
function filterFuzzyDiff(resultObj, timestamp) {
if (
resultObj &&
typeof resultObj === 'object' &&
resultObj.fuzzyDiff &&
typeof resultObj.fuzzyDiff === 'object'
) {
const { candidateFile, diff } = resultObj.fuzzyDiff;
resultObj.fuzzyDiff = { candidateFile, diff, timestamp };
}
}
async function resolveArgsFileUrls(obj, requestIp, debugMode = false) {
if (!obj || typeof obj !== 'object') return;
for (const key of Object.keys(obj)) {
const value = obj[key];
if (typeof value === 'string') {
if (value.startsWith('file://')) {
if (debugMode) console.log(`[PluginManager] Intercepted file URL in args: ${value}`);
obj[key] = await FileFetcherServer.resolveFileUrl(value, requestIp);
} else if (value.includes('file://')) {
const matches = value.match(EMBEDDED_FILE_URL_REGEX);
if (!matches) continue;
let resolvedValue = value;
for (const matchUrl of matches) {
if (debugMode) console.log(`[PluginManager] Intercepted embedded file URL in args: ${matchUrl}`);
const resolvedUrl = await FileFetcherServer.resolveFileUrl(matchUrl, requestIp);
resolvedValue = resolvedValue.split(matchUrl).join(resolvedUrl);
}
obj[key] = resolvedValue;
}
} else if (value && typeof value === 'object') {
await resolveArgsFileUrls(value, requestIp, debugMode);
}
}
}
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.reloadPending = false;
this.reloadChangedPaths = new Set();
this.pluginWatcher = null;
this.pluginLoadPromise = null;
this.pluginLoadRequested = false;
this.staticPluginsInitialized = false;
this.staticPluginSignatures = new Map();
this.staticPluginPlaceholderKeys = new Map();
this.vectorDBManager = null; // 修复:不再自己创建,等待注入
this.tdbKnowledgeManager = null; // 冷知识库管理器,等待 server.js 注入
this.toolApprovalManager = new ToolApprovalManager(path.join(__dirname, 'toolApprovalConfig.json'));
this.pendingApprovals = new Map(); // requestId -> { resolve, reject, timeoutId }
}
_sanitizeToolResultForAi(result) {
try {
const privacyConfig = this.toolApprovalManager?.getPrivacyProtectionConfig
? this.toolApprovalManager.getPrivacyProtectionConfig()
: { enabled: false };
return sanitizeToolResult(result, privacyConfig);
} catch (error) {
console.error(`[PluginManager] Tool result privacy protection failed, returning original result to avoid breaking tool flow: ${error.message}`);
return result;
}
}
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.');
}
setTdbKnowledgeManager(tdbManager) {
this.tdbKnowledgeManager = tdbManager;
if (this.debugMode) console.log('[PluginManager] TDBKnowledgeManager 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;
}
_shouldInjectSSHManagerEnv(pluginName) {
return SSH_MANAGER_ENV_PLUGIN_ALLOWLIST.has(pluginName);
}
_shouldInjectLogMonitorEnv(pluginName) {
return LOG_MONITOR_ENV_PLUGIN_ALLOWLIST.has(pluginName);
}
_isLinuxShellExecutorLocalUserCommand(plugin, inputData) {
if (!plugin || !inputData) return false;
let args;
try {
args = typeof inputData === 'string' ? JSON.parse(inputData) : inputData;
} catch (e) {
return false;
}
if (!args || typeof args !== 'object' || !args.command) {
return false;
}
const hostId = args.hostId;
if (!hostId) {
return true;
}
try {
const hostsPath = path.join(plugin.basePath, 'hosts.json');
delete require.cache[require.resolve(hostsPath)];
const hostsConfig = require(hostsPath);
const hostConfig = hostsConfig.hosts?.[hostId];
return hostConfig ? hostConfig.type !== 'ssh' : hostId === 'local';
} catch (e) {
return hostId === 'local';
}
}
_shouldInjectSSHManagerEnvForExecution(pluginName, plugin, inputData) {
if (!this._shouldInjectSSHManagerEnv(pluginName)) {
return false;
}
if (
pluginName === 'LinuxShellExecutor' &&
this._isLinuxShellExecutorLocalUserCommand(plugin, inputData)
) {
return false;
}
return true;
}
/**
* 跨平台进程树终止方法。
* Windows 上 shell:true 会创建 cmd.exe 包装进程,直接 kill 只杀 cmd 不杀子进程,
* 导致孤儿进程。此方法使用 taskkill /T /F 递归杀死整个进程树。
* Linux/macOS 上使用负 PID 发送信号给进程组,或回退到普通 SIGKILL。
*/
_killProcessTree(pid, pluginName) {
if (!Number.isInteger(Number(pid)) || Number(pid) <= 0) return;
const normalizedPid = Number(pid);
if (process.platform === 'win32') {
// Windows 没有 POSIX 进程组;taskkill /T 是系统原生的递归进程树终止方式。
const killer = spawn('taskkill', ['/T', '/F', '/PID', String(normalizedPid)], {
windowsHide: true,
stdio: 'ignore'
});
killer.once('error', error => {
console.warn(
`[PluginManager] taskkill failed for plugin "${pluginName}" (PID: ${normalizedPid}): ${error.message}`
);
try { process.kill(normalizedPid, 'SIGKILL'); } catch (_) { /* process already exited */ }
});
if (this.debugMode) {
console.log(`[PluginManager] Sent taskkill /T /F /PID ${normalizedPid} for plugin "${pluginName}"`);
}
return;
}
// Linux/macOS: plugin children are spawned as detached process-group leaders.
// Sending to a negative PID therefore terminates the shell wrapper and every descendant.
try {
process.kill(-normalizedPid, 'SIGKILL');
if (this.debugMode) {
console.log(`[PluginManager] Sent SIGKILL to process group -${normalizedPid} for plugin "${pluginName}"`);
}
} catch (groupError) {
try {
process.kill(normalizedPid, 'SIGKILL');
if (this.debugMode) {
console.log(`[PluginManager] Process group kill failed; killed PID ${normalizedPid} for plugin "${pluginName}"`);
}
} catch (processError) {
if (processError.code !== 'ESRCH' && this.debugMode) {
console.warn(
`[PluginManager] Failed to kill plugin "${pluginName}" (PID: ${normalizedPid}): ${processError.message}`
);
}
}
}
}
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,
detached: process.platform !== 'win32'
});
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.`);
this._killProcessTree(pluginProcess.pid, plugin.name);
// 超时不作为错误 - 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' || signal === 'SIGTERM') {
// 被强制终止(超时),已经在 timeout 回调中 resolve 了,这里直接返回
return;
}
if (code === 1 && !output.trim() && !errorOutput.trim()) {
// Windows taskkill 导致的退出码 1,且无有效输出,视为超时终止
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'.`);
}
}
});
}
}
_getStaticPluginSignature(plugin) {
return JSON.stringify({
entryPoint: plugin.entryPoint,
communication: plugin.communication,
refreshIntervalCron: plugin.refreshIntervalCron || null,
configSchema: plugin.configSchema || null,
pluginSpecificEnvConfig: plugin.pluginSpecificEnvConfig || {},
placeholders: plugin.capabilities?.systemPromptPlaceholders || []
});
}
async initializeStaticPlugins() {
const wasInitialized = this.staticPluginsInitialized;
this.staticPluginsInitialized = true;
console.log('[PluginManager] Initializing static plugins...');
const activeStaticPluginNames = new Set();
const activeLocalPlaceholderKeys = new Set();
for (const plugin of this.plugins.values()) {
if (plugin.pluginType !== 'static') continue;
activeStaticPluginNames.add(plugin.name);
const placeholderKeys = new Set(
(plugin.capabilities?.systemPromptPlaceholders || [])
.map(placeholder => placeholder.placeholder)
.filter(Boolean)
);
this.staticPluginPlaceholderKeys.set(plugin.name, placeholderKeys);
placeholderKeys.forEach(key => activeLocalPlaceholderKeys.add(key));
const signature = this._getStaticPluginSignature(plugin);
const previousSignature = this.staticPluginSignatures.get(plugin.name);
const missingPlaceholder = Array.from(placeholderKeys).some(
key => !this.staticPlaceholderValues.has(key)
);
const needsRefresh = !wasInitialized || previousSignature !== signature || missingPlaceholder;
if (needsRefresh) {
placeholderKeys.forEach(placeholderKey => {
if (!this.staticPlaceholderValues.has(placeholderKey)) {
this.staticPlaceholderValues.set(placeholderKey, {
value: `[${plugin.displayName} a-zheng-zai-jia-zai-zhong... ]`,
serverId: 'local'
});
}
});
this._updateStaticPluginValue(plugin).catch(err => {
console.error(`[PluginManager] Initial background update for ${plugin.name} failed: ${err.message}`);
});
}
const existingJob = this.scheduledJobs.get(plugin.name);
if (!plugin.refreshIntervalCron) {
if (existingJob) existingJob.cancel();
this.scheduledJobs.delete(plugin.name);
} else if (needsRefresh || !existingJob) {
if (existingJob) existingJob.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 (error) {
console.error(`[PluginManager] Invalid cron string for ${plugin.name}: ${plugin.refreshIntervalCron}. Error: ${error.message}`);
this.scheduledJobs.delete(plugin.name);
}
}
this.staticPluginSignatures.set(plugin.name, signature);
}
this._cancelObsoleteStaticPluginJobs(activeStaticPluginNames);
// 清理已删除插件或已删除 placeholder 声明留下的本地值;
// 分布式值始终由 serverId 所有权管理,不受本地重载影响。
for (const [placeholder, entry] of this.staticPlaceholderValues.entries()) {
if (entry?.serverId === 'local' && !activeLocalPlaceholderKeys.has(placeholder)) {
this.staticPlaceholderValues.delete(placeholder);
}
}
console.log('[PluginManager] Static plugins initialization process has been started (updates will run in the background).');
}
_cancelObsoleteStaticPluginJobs(activeStaticPluginNames = null) {
const activeNames = activeStaticPluginNames || new Set(
Array.from(this.plugins.values())
.filter(plugin => plugin.pluginType === 'static')
.map(plugin => plugin.name)
);
for (const [pluginName, job] of this.scheduledJobs.entries()) {
const plugin = this.plugins.get(pluginName);
if (activeNames.has(pluginName) && plugin?.refreshIntervalCron) continue;
try {
job.cancel();
} catch (error) {
if (this.debugMode) {
console.warn(`[PluginManager] Failed to cancel obsolete static job for ${pluginName}: ${error.message}`);
}
}
this.scheduledJobs.delete(pluginName);
}
for (const pluginName of this.staticPluginSignatures.keys()) {
if (!activeNames.has(pluginName)) {
this.staticPluginSignatures.delete(pluginName);
this.staticPluginPlaceholderKeys.delete(pluginName);
}
}
}
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, requestConfig = {}) {
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, ...requestConfig });
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
clearTimeout(this.reloadTimeout);
this.reloadTimeout = null;
this.reloadChangedPaths.clear();
if (this.pluginWatcher) {
try {
await this.pluginWatcher.close();
} catch (error) {
console.error('[PluginManager] Error closing plugin file watcher:', error);
} finally {
this.pluginWatcher = null;
}
}
for (const [requestId, approval] of this.pendingApprovals.entries()) {
clearTimeout(approval.timeoutId);
approval.reject(new Error(JSON.stringify({
plugin_error: 'Plugin manager is shutting down; pending manual approval was cancelled.',
error_type: 'plugin_manager_shutdown'
})));
try {
if (this.webSocketServer && typeof this.webSocketServer.cancelVcpLogApprovalCache === 'function') {
this.webSocketServer.cancelVcpLogApprovalCache(requestId);
}
} catch (error) {
if (this.debugMode) {
console.warn(`[PluginManager] Failed to clear approval cache for ${requestId}: ${error.message}`);
}
}
}
this.pendingApprovals.clear();
// VectorDBManager 是 server.js 注入并持有生命周期的外部依赖。
// 必须先让 DailyNote 等常驻服务排空自身队列,再由 server.js 统一关闭 KBD;
// 禁止在此提前/重复 shutdown 数据库。
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 _validateLocalPluginManifestsBeforeReload() {
const hasLoadedLocalPlugins = Array.from(this.plugins.values()).some(manifest => !manifest.isDistributed);
if (!hasLoadedLocalPlugins) return;
const pluginFolders = await fs.readdir(PLUGIN_DIR, { withFileTypes: true });
const validationTasks = pluginFolders
.filter(folder => folder.isDirectory())
.map(async folder => {
const manifestPath = path.join(PLUGIN_DIR, folder.name, manifestFileName);
try {
const manifestContent = await fs.readFile(manifestPath, 'utf-8');
JSON.parse(manifestContent);
} catch (error) {
if (error.code === 'ENOENT') return;
throw new Error(`Manifest pre-validation failed for ${folder.name}: ${error.message}`);
}
});
await Promise.all(validationTasks);
}
async loadPlugins() {
this.pluginLoadRequested = true;
if (!this.pluginLoadPromise) {
this.pluginLoadPromise = (async () => {
let result;
do {
this.pluginLoadRequested = false;
result = await this._loadPluginsOnce();
} while (this.pluginLoadRequested);
return result;
})().finally(() => {
this.pluginLoadPromise = null;
if (this.pluginLoadRequested) {
queueMicrotask(() => {
this.loadPlugins().catch(error => {
console.error('[PluginManager] Deferred plugin reload failed:', error);
});
});
}
});
}
return this.pluginLoadPromise;
}
async _loadPluginsOnce() {
console.log('[PluginManager] Starting plugin discovery...');
// 在关闭任何现有模块前先验证全部启用清单,避免编辑中的半截 JSON
// 将一个正常运行的插件注册表破坏为部分加载状态。
await this._validateLocalPluginManifestsBeforeReload();
// 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 {
await module.shutdown();
} catch (e) {
console.error(`[PluginManager] Error during hot-reload shutdown of a plugin:`, e.message);
}
}
}
this.plugins = distributedPlugins; // 仅保留分布式插件,本地插件将被重新发现
this.messagePreprocessors.clear();
// 占位符值在候选清单完成加载前保持可用。静态插件协调阶段会精确清理
// 已删除的本地占位符,分布式值则始终按 serverId 生命周期管理。
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(),
pluginManager: this
};
// --- 注入 VectorDBManager ---
if (
manifest.requiresKnowledgeBaseManager === true ||
manifest.name === 'RAGDiaryPlugin' ||
manifest.name === 'DailyNote' ||
manifest.name === 'DailyNoteManager'
) {
dependencies.vectorDBManager = this.vectorDBManager;
dependencies.knowledgeBaseManager = this.vectorDBManager;
}
if (manifest.name === 'RAGDiaryPlugin') {
// 🧊 注入冷知识库管理器,供 [[xx知识库]] / 《《xx知识库》》 占位符使用
if (this.tdbKnowledgeManager) {
dependencies.tdbKnowledgeManager = this.tdbKnowledgeManager;
if (this.debugMode) console.log(`[PluginManager] 🧊 Injected TDBKnowledgeManager into RAGDiaryPlugin.`);
}
}
// --- 🌟 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);
if (typeof ragPluginModule.getBatchEmbeddingsCached === 'function') {
dependencies.getBatchEmbeddings = ragPluginModule.getBatchEmbeddingsCached.bind(ragPluginModule);
} else if (typeof ragPluginModule.getBatchEmbeddings === 'function') {
dependencies.getBatchEmbeddings = ragPluginModule.getBatchEmbeddings.bind(ragPluginModule);
}
// 同时注入 ContextBridge(如果 LightMemo 未在 manifest 中声明,也主动注入)
if (!dependencies.contextBridge && typeof ragPluginModule.getContextBridge === 'function') {
dependencies.contextBridge = ragPluginModule.getContextBridge();
}
// AIMemoBridge 由 RAGDiaryPlugin 唯一持有配置、预设和缓存。
// LightMemo 只提交自身召回候选,避免重复实例化 AIMemoHandler。
if (typeof ragPluginModule.getAIMemoBridge === 'function') {
dependencies.aiMemoBridge = ragPluginModule.getAIMemoBridge();
}
if (this.debugMode) console.log(`[PluginManager] Injected VectorDBManager, embeddings, ContextBridge and AIMemoBridge into LightMemo.`);
} else {
console.error(`[PluginManager] Critical dependency failure: RAGDiaryPlugin or its components not available for LightMemo injection.`);
}
// 注入冷知识库管理器(TDBKnowledge),供 LightMemo 检索企业级知识库
if (this.tdbKnowledgeManager) {
dependencies.tdbKnowledgeManager = this.tdbKnowledgeManager;
if (this.debugMode) console.log(`[PluginManager] Injected TDBKnowledgeManager into LightMemo.`);
}
}
// --- 注入结束 ---
await module.initialize(initialConfig, dependencies);