-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathVCPDistributedServer.js
More file actions
723 lines (629 loc) · 31.9 KB
/
Copy pathVCPDistributedServer.js
File metadata and controls
723 lines (629 loc) · 31.9 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
// VCPDistributedServer.js
const WebSocket = require('ws');
const express = require('express');
const http = require('http');
const path = require('path');
const fs = require('fs').promises;
const fsSync = require('fs');
const dotenv = require('dotenv');
const os = require('os');
const mime = require('mime-types');
// const { ipcMain } = require('electron'); // This was incorrect. ipcMain should be injected.
const pluginManager = require('./Plugin.js');
const GENERATED_LISTS_CONFIG_PATH = path.join(__dirname, '..', 'AppData', 'generated_lists', 'config.env');
// DEBUG_MODE is now passed in config
// const DEBUG_MODE = (process.env.DebugMode || "False").toLowerCase() === "true";
function loadGeneratedListsConfig() {
try {
if (!fsSync.existsSync(GENERATED_LISTS_CONFIG_PATH)) {
return {};
}
return dotenv.parse(fsSync.readFileSync(GENERATED_LISTS_CONFIG_PATH));
} catch (error) {
console.error('[DistributedServer] Failed to read generated_lists/config.env:', error.message);
return {};
}
}
function getRequestRemoteAddress(req) {
return req.socket?.remoteAddress || req.ip || '';
}
function isLoopbackAddress(address) {
if (!address) return false;
const normalized = String(address).trim().toLowerCase();
return normalized === '127.0.0.1'
|| normalized === '::1'
|| normalized === '::ffff:127.0.0.1';
}
class DistributedServer {
constructor(config = {}) {
this.mainServerUrl = config.mainServerUrl;
this.vcpKey = config.vcpKey;
this.serverName = config.serverName || 'Unnamed-Distributed-Server';
this.port = config.port || 0; // 0 表示随机选择一个可用端口
this.debugMode = config.debugMode || false;
this.rendererProcess = config.rendererProcess; // To communicate with the renderer
this.handleMusicControl = config.handleMusicControl; // Inject the music control handler
this.handleDiceControl = config.handleDiceControl; // Inject the dice control handler
this.handleCanvasControl = config.handleCanvasControl; // Inject the canvas control handler
this.handleFlowlockControl = config.handleFlowlockControl; // Inject the flowlock control handler
this.handleDesktopRemoteControl = config.handleDesktopRemoteControl; // Inject the desktop remote control handler
this.ws = null;
this.app = express(); // 创建 Express 应用
this.server = http.createServer(this.app); // 创建 HTTP 服务器
this.reconnectInterval = 5000;
this.app.use(express.json({ limit: '2mb' }));
this.app.use(express.urlencoded({ extended: false, limit: '2mb' }));
this.maxReconnectInterval = 60000;
this.reconnectTimeoutId = null; // To keep track of the reconnect timeout
this.stopped = false; // Flag to prevent reconnection when stopped manually
this.stopPromise = null;
this.initialConnection = true; // Flag to handle one-time actions on first connect
this.staticPlaceholderUpdateInterval = null; // 新增:静态占位符更新定时器
}
async bindHttpServer(preferredPort) {
const tryListen = (port) => new Promise((resolve, reject) => {
const onError = (error) => {
this.server.off('listening', onListening);
reject(error);
};
const onListening = () => {
this.server.off('error', onError);
resolve(this.server.address());
};
this.server.once('error', onError);
this.server.once('listening', onListening);
this.server.listen(port, '0.0.0.0');
});
try {
return await tryListen(preferredPort);
} catch (error) {
if (error && error.code === 'EADDRINUSE' && preferredPort !== 0) {
console.warn(`[${this.serverName}] Port ${preferredPort} is already in use. Falling back to a random available port.`);
return tryListen(0);
}
throw error;
}
}
async initialize() {
console.log(`[${this.serverName}] Initializing...`);
// Load server-specific config
const serverConfigPath = path.join(__dirname, 'config.env');
try {
if (fsSync.existsSync(serverConfigPath)) {
const serverEnv = dotenv.parse(fsSync.readFileSync(serverConfigPath));
if (serverEnv.DIST_SERVER_PORT) {
const newPort = parseInt(serverEnv.DIST_SERVER_PORT, 10);
if (!isNaN(newPort)) {
this.port = newPort;
console.log(`[${this.serverName}] Port loaded from config.env: ${this.port}`);
}
}
}
} catch (e) {
console.error(`[${this.serverName}] Error reading server config.env:`, e);
}
// The base path should be relative to this file's location.
const basePath = path.dirname(require.resolve('./VCPDistributedServer.js'));
pluginManager.setProjectBasePath(basePath);
await pluginManager.loadPlugins();
// 初始化服务类插件
await pluginManager.initializeServices(this.app, null, basePath);
this.registerDiagnosticRoutes();
const address = await this.bindHttpServer(this.port);
this.port = this.server.address().port; // 获取实际监听的端口
console.log(`[${this.serverName}] HTTP server listening on 0.0.0.0:${this.port}`);
// 注入端口到插件管理器,用于构造回调 URL
pluginManager.setServerPort(this.port);
// 注册异步插件回调接口
this.app.post('/plugin/callback', (req, res) => {
const callbackData = req.body;
if (this.debugMode) console.log(`[${this.serverName}] Received plugin callback:`, callbackData);
// 通过 WebSocket 隧道转发回调数据到主服务器
const payload = {
type: 'plugin_callback_forward',
data: {
serverName: this.serverName,
callbackData: callbackData
}
};
this.sendMessage(payload);
res.status(200).json({ status: 'success', message: 'Callback forwarded to main server.' });
});
// 在 HTTP 服务器启动后,再连接到主服务器
this.connect();
}
registerDiagnosticRoutes() {
const generatedConfig = loadGeneratedListsConfig();
const fileKey = generatedConfig.file_key;
if (!fileKey) {
console.error(`[${this.serverName}] DesktopRemote test route disabled: missing file_key in AppData/generated_lists/config.env.`);
return;
}
this.app.post(/\/pw=([^\/]+)\/desktop-remote-test/, async (req, res) => {
const requestKey = req.params[0];
const remoteAddress = getRequestRemoteAddress(req);
if (!isLoopbackAddress(remoteAddress)) {
return res.status(403).json({
success: false,
error: `Loopback only. Remote address: ${remoteAddress || 'unknown'}`,
stage: 'auth',
});
}
if (requestKey !== fileKey) {
return res.status(401).json({
success: false,
error: 'Unauthorized',
stage: 'auth',
});
}
let commandPayload;
try {
const normalized = await pluginManager.processToolCall('DesktopRemote', req.body || {});
commandPayload = typeof normalized === 'string' ? JSON.parse(normalized) : normalized;
} catch (error) {
return res.status(400).json({
success: false,
error: error.message || 'Failed to normalize DesktopRemote request.',
stage: 'normalize',
});
}
try {
if (typeof this.handleDesktopRemoteControl !== 'function') {
throw new Error('Desktop remote control handler is not configured.');
}
const result = await this.handleDesktopRemoteControl(commandPayload);
if (!result || result.status !== 'success') {
const message = result?.message || result?.error || 'DesktopRemote handler failed.';
const stage = /timed out/i.test(message) ? 'renderer-timeout' : 'main-handler';
return res.status(stage === 'renderer-timeout' ? 504 : 500).json({
success: false,
error: message,
stage,
commandPayload,
});
}
return res.json({
success: true,
commandPayload,
result,
});
} catch (error) {
const message = error.message || 'DesktopRemote handler failed.';
const stage = /timed out/i.test(message) ? 'renderer-timeout' : 'main-handler';
return res.status(stage === 'renderer-timeout' ? 504 : 500).json({
success: false,
error: message,
stage,
commandPayload,
});
}
});
console.log(`[${this.serverName}] DesktopRemote test route enabled: /pw=<file_key>/desktop-remote-test`);
}
connect() {
if (this.stopped) {
console.log(`[${this.serverName}] Server is stopped, not connecting.`);
return;
}
if (!this.mainServerUrl || !this.vcpKey) {
console.error(`[${this.serverName}] Error: mainServerUrl or vcpKey is not configured. Cannot connect.`);
return;
}
const connectionUrl = `${this.mainServerUrl.replace(/^http/, 'ws')}/vcp-distributed-server/VCP_Key=${this.vcpKey}`;
console.log(`[${this.serverName}] Attempting to connect to main server at ${connectionUrl}`);
// this.ws 现在是一个纯粹的客户端实例
this.ws = new WebSocket(connectionUrl);
this.ws.on('open', async () => {
console.log(`[${this.serverName}] Successfully connected to main server.`);
this.reconnectInterval = 5000;
this.registerTools();
await this.reportIPAddress();
// 新增:设置静态占位符定期推送
this.setupStaticPlaceholderUpdates();
});
this.ws.on('message', (message) => {
this.handleMainServerMessage(message);
});
this.ws.on('close', () => {
console.log(`[${this.serverName}] Disconnected from main server.`);
// 新增:清理静态占位符更新定时器
this.clearStaticPlaceholderUpdates();
this.scheduleReconnect();
});
this.ws.on('error', (error) => {
console.error(`[${this.serverName}] WebSocket client error:`, error.message);
// 'close' 事件会自动被触发,所以这里不需要额外的处理
});
}
scheduleReconnect() {
if (this.stopped) {
console.log(`[${this.serverName}] Stop called, cancelling reconnection.`);
return;
}
console.log(`[${this.serverName}] Attempting to reconnect in ${this.reconnectInterval / 1000}s...`);
// 新增:清理静态占位符更新定时器
this.clearStaticPlaceholderUpdates();
// Clear any existing timeout to avoid multiple reconnect loops
if (this.reconnectTimeoutId) {
clearTimeout(this.reconnectTimeoutId);
}
this.reconnectTimeoutId = setTimeout(() => this.connect(), this.reconnectInterval);
// Exponential backoff
this.reconnectInterval = Math.min(this.reconnectInterval * 2, this.maxReconnectInterval);
}
registerTools() {
const manifests = pluginManager.getAllPluginManifests();
// On the very first successful connection, send a notification about loaded plugins.
if (this.initialConnection && manifests.length > 0) {
const pluginCount = manifests.length;
// Directly send a structured message to the renderer process for notification
if (this.rendererProcess && !this.rendererProcess.isDestroyed()) {
// Add a delay to give the renderer process time to set up its listeners
setTimeout(() => {
if (this.rendererProcess && !this.rendererProcess.isDestroyed()) {
this.rendererProcess.send('vcp-log-message', {
type: 'vcp_log',
data: {
source: 'DistPluginManager',
content: `分布式服务器已启动,已推送 ${pluginCount} 个本地插件。`
}
});
}
}, 1000); // 2-second delay
}
this.initialConnection = false; // Ensure this only runs once
}
if (manifests.length > 0) {
const payload = {
type: 'register_tools',
data: {
serverName: this.serverName,
tools: manifests
}
};
this.sendMessage(payload);
console.log(`[${this.serverName}] Sent registration for ${manifests.length} tools to the main server.`);
} else {
if (this.debugMode) console.log(`[${this.serverName}] No local tools found to register.`);
}
}
async reportIPAddress() {
const { default: fetch } = await import('node-fetch');
const networkInterfaces = os.networkInterfaces();
const ipv4Addresses = [];
let publicIp = null;
for (const interfaceName in networkInterfaces) {
const interfaces = networkInterfaces[interfaceName];
for (const iface of interfaces) {
if (iface.family === 'IPv4' && !iface.internal) {
ipv4Addresses.push(iface.address);
}
}
}
try {
const response = await fetch('https://api.ipify.org?format=json');
if (response.ok) {
const data = await response.json();
publicIp = data.ip;
} else {
console.error(`[${this.serverName}] Failed to fetch public IP, status: ${response.status}`);
}
} catch (e) {
console.error(`[${this.serverName}] Could not fetch public IP:`, e.message);
}
const payload = {
type: 'report_ip',
data: {
serverName: this.serverName,
localIPs: ipv4Addresses,
publicIP: publicIp
}
};
this.sendMessage(payload);
console.log(`[${this.serverName}] Reported IP addresses to main server: Local: ${ipv4Addresses.join(', ')}, Public: ${publicIp || 'N/A'}`);
}
// 新增:设置静态占位符定期更新
setupStaticPlaceholderUpdates() {
// 每30秒推送一次静态占位符值
this.staticPlaceholderUpdateInterval = setInterval(() => {
this.pushStaticPlaceholderValues();
}, 30000); // 30秒
// 立即推送一次
setTimeout(() => {
this.pushStaticPlaceholderValues();
}, 2000); // 2秒后第一次推送
if (this.debugMode) console.log(`[${this.serverName}] Static placeholder updates scheduled every 30 seconds.`);
}
// 新增:清理静态占位符更新定时器
clearStaticPlaceholderUpdates() {
if (this.staticPlaceholderUpdateInterval) {
clearInterval(this.staticPlaceholderUpdateInterval);
this.staticPlaceholderUpdateInterval = null;
if (this.debugMode) console.log(`[${this.serverName}] Static placeholder update interval cleared.`);
}
}
// 新增:推送静态占位符值到主服务器
async pushStaticPlaceholderValues() {
const placeholderValues = pluginManager.getAllPlaceholderValues();
if (placeholderValues.size === 0) {
return;
}
// 检查是否在settings.json中禁用了静态插件日志
const logStaticPlugins = await this.shouldLogStaticPlugins();
const payload = {
type: 'update_static_placeholders',
data: {
serverName: this.serverName,
placeholders: Object.fromEntries(placeholderValues)
}
};
this.sendMessage(payload);
if (this.debugMode && logStaticPlugins) {
console.log(`[${this.serverName}] Pushed ${placeholderValues.size} static placeholder values to main server.`);
for (const [key, value] of placeholderValues) {
console.log(` - ${key}: ${value.substring(0, 100)}${value.length > 100 ? '...' : ''}`);
}
}
}
// 新增:检查是否应该记录静态插件日志
async shouldLogStaticPlugins() {
try {
const settingsPath = path.join(__dirname, '..', 'AppData', 'settings.json');
if (!fsSync.existsSync(settingsPath)) {
return true; // 默认启用日志
}
const settings = JSON.parse(fsSync.readFileSync(settingsPath, 'utf8'));
return settings.enableDistributedServerLogs !== false; // 默认启用,除非明确设置为false
} catch (error) {
if (this.debugMode) console.warn(`[${this.serverName}] Error reading settings for log control:`, error.message);
return true; // 错误时默认启用日志
}
}
async handleMainServerMessage(message) {
try {
const parsedMessage = JSON.parse(message);
if (this.debugMode) console.log(`[${this.serverName}] Received message from main server:`, parsedMessage.type);
if (parsedMessage.type === 'execute_tool') {
await this.handleToolExecutionRequest(parsedMessage.data);
}
} catch (e) {
console.error(`[${this.serverName}] Error parsing message from main server:`, e);
}
}
async handleToolExecutionRequest(data) {
const { requestId, toolName, toolArgs } = data;
if (!requestId || !toolName) {
console.error(`[${this.serverName}] Invalid tool execution request received.`);
return;
}
if (this.debugMode) console.log(`[${this.serverName}] Executing tool '${toolName}' for request ID: ${requestId}`);
let responsePayload;
try {
// --- 新增:处理内部文件请求 ---
if (toolName === 'internal_request_file') {
// 关键改进:对接 FileFetcherServer 的新协议
const { fileUrl } = toolArgs;
if (!fileUrl || !fileUrl.startsWith('file://')) {
throw new Error(`Invalid or missing fileUrl parameter for internal_request_file.`);
}
try {
// 在分布式服务器自己的环境中,安全地将 URL 转换为本地路径
const { fileURLToPath } = require('url');
const filePath = fileURLToPath(fileUrl);
const fileBuffer = await fs.readFile(filePath);
const mimeType = mime.lookup(filePath) || 'application/octet-stream';
responsePayload = {
type: 'tool_result',
data: {
requestId,
status: 'success',
result: {
status: 'success',
fileData: fileBuffer.toString('base64'),
mimeType: mimeType
}
}
};
} catch (e) {
if (e.code === 'ENOENT') {
throw new Error(`File not found on distributed server: ${fileUrl}`);
} else if (e.code === 'ERR_INVALID_FILE_URL_PATH') {
throw new Error(`Invalid file URL path on distributed server: ${fileUrl}`);
} else {
throw new Error(`Error reading file on distributed server (${fileUrl}): ${e.message}`);
}
}
this.sendMessage(responsePayload);
if (this.debugMode) console.log(`[${this.serverName}] Sent file content for request ID: ${requestId}`);
return; // 处理完毕,直接返回
}
// --- 结束:处理内部文件请求 ---
const result = await pluginManager.processToolCall(toolName, toolArgs);
let finalResult;
// --- Special Handling for MusicController ---
if (toolName === 'MusicController') {
const commandPayload = (typeof result === 'string') ? JSON.parse(result) : result;
if (commandPayload.status === 'error') {
throw new Error(commandPayload.error);
}
if (typeof this.handleMusicControl !== 'function') {
throw new Error('Music control handler is not configured for the Distributed Server.');
}
// Directly call the injected handler function from main.js
const resultFromMain = await this.handleMusicControl(commandPayload);
if (resultFromMain.status === 'error') {
throw new Error(resultFromMain.message);
}
// For AI, we want a simple, natural language response.
let naturalResponse = `指令 '${commandPayload.command}' 已成功执行。`;
if (commandPayload.command === 'play' && commandPayload.target) {
naturalResponse = `已为您播放歌曲: ${commandPayload.target}`;
} else if (commandPayload.command === 'play') {
naturalResponse = `已恢复播放。`;
} else if (commandPayload.command === 'pause') {
naturalResponse = `已暂停播放。`;
} else if (commandPayload.command === 'next') {
naturalResponse = `已切换到下一首。`;
} else if (commandPayload.command === 'prev') {
naturalResponse = `已切换到上一首。`;
}
finalResult = { message: naturalResponse };
} else if (toolName === 'SuperDice') {
if (typeof this.handleDiceControl !== 'function') {
throw new Error('Dice control handler is not configured for the Distributed Server.');
}
// The toolArgs are already parsed, e.g., { notation: '2d20' }
const resultFromMain = await this.handleDiceControl(toolArgs);
if (resultFromMain.status === 'error') {
throw new Error(resultFromMain.message);
}
// The result from the dice roll is already structured, so we can pass it directly.
finalResult = resultFromMain.data;
} else if (toolName === 'Flowlock') {
// --- Special Handling for Flowlock ---
if (typeof this.handleFlowlockControl !== 'function') {
throw new Error('Flowlock control handler is not configured for the Distributed Server.');
}
// The toolArgs contain the command and parameters
const resultFromMain = await this.handleFlowlockControl(toolArgs);
if (resultFromMain.status === 'error') {
throw new Error(resultFromMain.message);
}
finalResult = { message: resultFromMain.message };
} else if (toolName === 'DesktopRemote') {
// --- Special Handling for DesktopRemote ---
const commandPayload = (typeof result === 'string') ? JSON.parse(result) : result;
if (commandPayload.status === 'error') {
throw new Error(commandPayload.error);
}
if (typeof this.handleDesktopRemoteControl !== 'function') {
throw new Error('Desktop remote control handler is not configured for the Distributed Server.');
}
// Directly call the injected handler function from main.js
const resultFromMain = await this.handleDesktopRemoteControl(commandPayload);
if (resultFromMain.status === 'error') {
throw new Error(resultFromMain.message);
}
// The handler returns { status, result: { content: [...] } } format
// Pass through the result directly to preserve the content array structure
finalResult = resultFromMain.result || { message: resultFromMain.message };
} else {
// --- Default Handling for all other plugins ---
if (typeof result === 'object' && result !== null) {
// Result is already an object from a direct call (e.g., hybrid service)
finalResult = result;
} else {
// Result is a string from stdio, needs parsing
try {
// --- Robust JSON Parsing ---
// The plugin might output debug info (like from dotenv) to stdout before the JSON.
// We need to find the actual JSON string.
const jsonStartIndex = result.indexOf('{');
const jsonEndIndex = result.lastIndexOf('}');
if (jsonStartIndex === -1 || jsonEndIndex === -1) {
// If no JSON object is found, treat it as a raw string.
throw new SyntaxError("No JSON object found in plugin output.");
}
const jsonString = result.substring(jsonStartIndex, jsonEndIndex + 1);
const parsedPluginResult = JSON.parse(jsonString);
// --- End of Robust JSON Parsing ---
if (parsedPluginResult.status === 'success') {
finalResult = parsedPluginResult.result;
// --- VCP Protocol Enhancement ---
// If the plugin response has special action fields (e.g., for canvas),
// merge them into the final result object so they can be handled downstream.
if (parsedPluginResult._specialAction) {
if (typeof finalResult !== 'object' || finalResult === null) {
finalResult = {}; // Ensure finalResult is an object
}
finalResult._specialAction = parsedPluginResult._specialAction;
finalResult.payload = parsedPluginResult.payload;
}
} else {
throw new Error(parsedPluginResult.error || 'Plugin reported an error without a message.');
}
} catch (e) {
if (e instanceof SyntaxError) {
finalResult = result; // Legacy plugin returning a raw string
} else {
throw e; // Other error
}
}
}
// --- Special Handling for create_canvas action (applied to the finalResult) ---
if (finalResult && finalResult._specialAction === 'create_canvas') {
if (typeof this.handleCanvasControl === 'function') {
console.log(`[${this.serverName}] Detected create_canvas action. Calling main process handler.`);
this.handleCanvasControl(finalResult.payload.filePath);
} else {
console.error(`[${this.serverName}] Canvas control handler is not configured for the Distributed Server.`);
}
}
// --- End of special handling ---
}
responsePayload = {
type: 'tool_result',
data: {
requestId,
status: 'success',
result: finalResult
}
};
} catch (error) {
console.error(`[${this.serverName}] Error executing tool '${toolName}':`, error.message);
responsePayload = {
type: 'tool_result',
data: {
requestId,
status: 'error',
error: error.message || 'An unknown error occurred.'
}
};
}
this.sendMessage(responsePayload);
if (this.debugMode) console.log(`[${this.serverName}] Sent result for request ID: ${requestId}`);
}
sendMessage(payload) {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(payload));
} else {
console.error(`[${this.serverName}] Cannot send message, WebSocket is not open.`);
}
}
async stop() {
if (this.stopPromise) {
return this.stopPromise;
}
console.log(`[${this.serverName}] Stopping server...`);
this.stopPromise = Promise.resolve().then(async () => {
this.stopped = true;
// 新增:清理静态占位符更新定时器
this.clearStaticPlaceholderUpdates();
if (this.reconnectTimeoutId) {
clearTimeout(this.reconnectTimeoutId);
this.reconnectTimeoutId = null;
}
// 新增:关闭插件管理器 - 使用异步方式,但不等待结果
pluginManager.shutdownAllPlugins().catch(err => {
console.error(`[${this.serverName}] Error during plugin shutdown:`, err);
});
if (this.ws) {
// Remove listeners to prevent reconnection logic from firing on manual close
this.ws.removeAllListeners('close');
this.ws.removeAllListeners('error');
if (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING) {
this.ws.close(1000, 'Client initiated disconnect'); // 1000 is a normal closure
}
this.ws = null;
}
if (this.server && this.server.listening) {
await new Promise((resolve) => {
this.server.close(() => resolve());
});
}
console.log(`[${this.serverName}] Server stopped.`);
});
return this.stopPromise;
}
}
module.exports = DistributedServer;