-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrelay-server-wss.js
More file actions
703 lines (593 loc) · 17.6 KB
/
relay-server-wss.js
File metadata and controls
703 lines (593 loc) · 17.6 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
const WebSocket = require('ws');
const https = require('https');
const fs = require('fs');
const PORT = process.env.PORT || 8080;
const WSS_PORT = process.env.WSS_PORT || 8443;
const AUTH_TOKEN = process.env.RELAY_AUTH_TOKEN || '84c348bea7be634216ef5277cf84e4b2bfbbbf2df3d6d2e3';
// 客户端管理
const clients = new Map(); // clientId -> { ws, type, metadata, lastPing }
const instances = new Map(); // instanceId -> clientId
const offlineMessages = new Map(); // clientId -> [messages]
// 日志
function log(level, message, data = null) {
const timestamp = new Date().toISOString();
const prefix = {
info: '📘',
success: '✅',
error: '❌',
warn: '⚠️',
debug: '🔍'
}[level] || '📝';
console.log(`${prefix} [${timestamp}] ${message}`);
if (data) {
console.log(JSON.stringify(data, null, 2));
}
}
// 生成客户端 ID
function generateClientId() {
return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
}
// 发送消息
function sendMessage(ws, data) {
if (ws.readyState === WebSocket.OPEN) {
try {
ws.send(JSON.stringify(data));
return true;
} catch (error) {
log('error', 'Failed to send message', { error: error.message });
return false;
}
}
return false;
}
// 广播消息
function broadcast(data, excludeClientId = null) {
let sent = 0;
clients.forEach((client, clientId) => {
if (clientId !== excludeClientId) {
if (sendMessage(client.ws, data)) {
sent++;
}
}
});
return sent;
}
// 处理注册
function handleRegister(clientId, client, payload) {
const { type, instanceId, instanceName, metadata, token } = payload;
// 认证检查
if (token !== AUTH_TOKEN) {
log('warn', `Authentication failed for ${clientId}`, { type });
sendMessage(client.ws, {
type: 'auth_error',
payload: { message: 'Invalid authentication token' }
});
client.ws.close(4001, 'Authentication failed');
return;
}
client.type = type || 'unknown';
client.metadata = metadata || {};
if (type === 'openclaw' && instanceId) {
// OpenClaw 实例注册
client.instanceId = instanceId;
client.instanceName = instanceName || instanceId;
instances.set(instanceId, clientId);
log('success', `OpenClaw instance registered: ${instanceId}`, {
clientId,
instanceName,
metadata
});
// 确认注册
sendMessage(client.ws, {
type: 'registered',
payload: {
clientId,
instanceId,
instanceName
}
});
// 广播实例上线
broadcast({
type: 'instance_online',
payload: {
instanceId,
instanceName,
timestamp: Date.now()
}
}, clientId);
// 发送离线消息
if (offlineMessages.has(clientId)) {
const messages = offlineMessages.get(clientId);
log('info', `Delivering ${messages.length} offline messages to ${clientId}`);
messages.forEach(msg => sendMessage(client.ws, msg));
offlineMessages.delete(clientId);
}
} else if (type === 'android') {
// Android 客户端注册
log('success', `Android client registered: ${clientId}`, { metadata });
sendMessage(client.ws, {
type: 'registered',
payload: {
clientId,
type: 'android'
}
});
// 发送实例列表
const instanceList = [];
instances.forEach((cid, iid) => {
const c = clients.get(cid);
if (c) {
instanceList.push({
instanceId: iid,
instanceName: c.instanceName || iid,
online: true
});
}
});
sendMessage(client.ws, {
type: 'instance_list',
payload: { instances: instanceList }
});
} else {
// 其他类型客户端
log('info', `Client registered: ${clientId}`, { type, metadata });
sendMessage(client.ws, {
type: 'registered',
payload: { clientId, type }
});
}
}
// 处理消息
function handleMessage(clientId, client, msg) {
let { target, payload } = msg;
// 如果没有指定 target,且发送者是 Android 客户端,自动路由到 OpenClaw 实例
if (!target && client.type === 'android') {
// 查找第一个 OpenClaw 实例
const openclawInstances = Array.from(clients.entries())
.filter(([_, c]) => c.type === 'openclaw');
if (openclawInstances.length > 0) {
target = openclawInstances[0][0]; // 使用第一个 OpenClaw 实例的 clientId
log('info', `Auto-routing Android message to OpenClaw: ${target}`);
}
}
if (!target) {
log('error', 'Message missing target', { clientId, msg });
sendMessage(client.ws, {
type: 'error',
payload: { message: 'Missing target and no OpenClaw instance available' }
});
return;
}
// 查找目标客户端
let targetClientId = target;
// 如果 target 是 instanceId,转换为 clientId
if (instances.has(target)) {
targetClientId = instances.get(target);
}
const targetClient = clients.get(targetClientId);
if (targetClient) {
// 在线,直接发送
log('info', `Routing message: ${clientId} -> ${targetClientId}`);
sendMessage(targetClient.ws, {
type: 'message',
from: clientId,
payload: payload
});
} else {
// 离线,存储消息
log('warn', `Target offline, queueing message: ${targetClientId}`);
if (!offlineMessages.has(targetClientId)) {
offlineMessages.set(targetClientId, []);
}
offlineMessages.get(targetClientId).push({
type: 'message',
from: clientId,
payload: payload,
timestamp: Date.now()
});
// 通知发送者
sendMessage(client.ws, {
type: 'message_queued',
payload: {
target: targetClientId,
queueSize: offlineMessages.get(targetClientId).length
}
});
}
}
// 处理命令
function handleCommand(clientId, client, msg) {
const { target, payload } = msg;
// 查找目标客户端
let targetClientId = target;
if (instances.has(target)) {
targetClientId = instances.get(target);
}
const targetClient = clients.get(targetClientId);
if (targetClient) {
log('info', `Routing command: ${clientId} -> ${targetClientId}`);
sendMessage(targetClient.ws, {
type: 'command',
from: clientId,
payload: payload
});
} else {
log('warn', `Command target not found: ${targetClientId}`);
sendMessage(client.ws, {
type: 'error',
payload: { message: 'Target not found' }
});
}
}
// 流式消息透传:stream_start / stream_chunk / stream_end
function handleStreamMessage(clientId, client, msg) {
const { target, payload } = msg;
let targetClientId = target;
if (instances.has(target)) {
targetClientId = instances.get(target);
}
const targetClient = clients.get(targetClientId);
if (targetClient) {
sendMessage(targetClient.ws, {
type: msg.type,
from: clientId,
payload: payload
});
} else {
log('warn', `Stream target not found: ${targetClientId}`);
}
}
// 处理任务派发(App → 指定 OpenClaw 客户端)
function handleTaskDispatch(clientId, client, msg) {
const { target, payload } = msg;
log('info', `Task dispatch from ${clientId}`, {
taskId: payload?.taskId,
template: payload?.template,
target
});
// 查找目标 OpenClaw 实例
let targetClientId = target;
if (instances.has(target)) {
targetClientId = instances.get(target);
}
// 如果没有指定 target,自动路由到第一个 OpenClaw 实例
if (!targetClientId || !clients.has(targetClientId)) {
const openclawInstances = Array.from(clients.entries())
.filter(([_, c]) => c.type === 'openclaw');
if (openclawInstances.length > 0) {
targetClientId = openclawInstances[0][0];
log('info', `Auto-routing task_dispatch to OpenClaw: ${targetClientId}`);
} else {
log('error', 'No OpenClaw instance available for task_dispatch');
sendMessage(client.ws, {
type: 'task_update',
payload: {
taskId: payload?.taskId,
status: 'failed',
output: '没有在线的 OpenClaw 实例'
}
});
return;
}
}
const targetClient = clients.get(targetClientId);
if (targetClient) {
sendMessage(targetClient.ws, {
type: 'task_dispatch',
from: clientId,
payload: payload
});
log('success', `Task dispatched: ${payload?.taskId} -> ${targetClientId}`);
}
}
// 处理任务状态更新(OpenClaw 客户端 → 所有 App)
function handleTaskUpdate(clientId, client, msg) {
const { payload } = msg;
log('info', `Task update from ${clientId}`, {
taskId: payload?.taskId,
status: payload?.status
});
// 广播给所有 Android 客户端
clients.forEach((c, cid) => {
if (c.type === 'android' && cid !== clientId) {
sendMessage(c.ws, {
type: 'task_update',
from: clientId,
payload: payload
});
}
});
}
// 处理任务取消(App → 指定 OpenClaw 客户端)
function handleTaskCancel(clientId, client, msg) {
const { target, payload } = msg;
log('info', `Task cancel from ${clientId}`, {
taskId: payload?.taskId,
target
});
// 查找目标 OpenClaw 实例
let targetClientId = target;
if (instances.has(target)) {
targetClientId = instances.get(target);
}
// 如果没有指定 target,广播到所有 OpenClaw 实例
if (!targetClientId || !clients.has(targetClientId)) {
clients.forEach((c, cid) => {
if (c.type === 'openclaw') {
sendMessage(c.ws, {
type: 'task_cancel',
from: clientId,
payload: payload
});
}
});
return;
}
const targetClient = clients.get(targetClientId);
if (targetClient) {
sendMessage(targetClient.ws, {
type: 'task_cancel',
from: clientId,
payload: payload
});
log('success', `Task cancel sent: ${payload?.taskId} -> ${targetClientId}`);
}
}
// 处理 sub-agent 更新
function handleSubAgentUpdate(clientId, client, msg) {
const { payload } = msg;
log('info', `Sub-agent update from ${clientId}`, {
subagentCount: payload?.subagents?.length || 0
});
// 广播给所有 Android 客户端
clients.forEach((c, cid) => {
if (c.type === 'android' && cid !== clientId) {
sendMessage(c.ws, {
type: 'subagent_update',
from: clientId,
payload: payload
});
}
});
}
// 处理记忆搜索(App → OpenClaw 客户端)
function handleMemorySearch(clientId, client, msg) {
const { target, payload } = msg;
log('info', `Memory search from ${clientId}`, {
query: payload?.query,
target
});
// 查找目标 OpenClaw 实例
let targetClientId = target;
if (instances.has(target)) {
targetClientId = instances.get(target);
}
// 如果没有指定 target,自动路由到第一个 OpenClaw 实例
if (!targetClientId || !clients.has(targetClientId)) {
const openclawInstances = Array.from(clients.entries())
.filter(([_, c]) => c.type === 'openclaw');
if (openclawInstances.length > 0) {
targetClientId = openclawInstances[0][0];
log('info', `Auto-routing memory_search to OpenClaw: ${targetClientId}`);
} else {
log('error', 'No OpenClaw instance available for memory_search');
sendMessage(client.ws, {
type: 'memory_result',
payload: {
error: '没有在线的 OpenClaw 实例',
result: ''
}
});
return;
}
}
const targetClient = clients.get(targetClientId);
if (targetClient) {
sendMessage(targetClient.ws, {
type: 'memory_search',
from: clientId,
payload: payload
});
log('success', `Memory search routed: ${clientId} -> ${targetClientId}`);
}
}
// 处理记忆结果(OpenClaw 客户端 → App)
function handleMemoryResult(clientId, client, msg) {
const { target, payload } = msg;
log('info', `Memory result from ${clientId}`);
// 如果有指定 target,发给 target
if (target && clients.has(target)) {
sendMessage(clients.get(target).ws, {
type: 'memory_result',
from: clientId,
payload: payload
});
return;
}
// 否则广播给所有 Android 客户端
clients.forEach((c, cid) => {
if (c.type === 'android' && cid !== clientId) {
sendMessage(c.ws, {
type: 'memory_result',
from: clientId,
payload: payload
});
}
});
}
// 处理心跳
function handlePing(clientId, client) {
client.lastPing = Date.now();
sendMessage(client.ws, { type: 'pong' });
}
// 清理客户端
function cleanupClient(clientId) {
const client = clients.get(clientId);
if (client) {
// 如果是 OpenClaw 实例,从实例列表移除
if (client.instanceId) {
instances.delete(client.instanceId);
log('info', `OpenClaw instance offline: ${client.instanceId}`);
// 广播实例下线
broadcast({
type: 'instance_offline',
payload: {
instanceId: client.instanceId,
instanceName: client.instanceName,
timestamp: Date.now()
}
});
}
clients.delete(clientId);
log('info', `Client disconnected: ${clientId}`, {
type: client.type,
totalClients: clients.size
});
}
}
// 连接处理函数(WS 和 WSS 共用)
function handleConnection(ws) {
const clientId = generateClientId();
const client = {
ws,
type: 'unknown',
metadata: {},
lastPing: Date.now()
};
clients.set(clientId, client);
log('info', `New connection: ${clientId}`, {
totalClients: clients.size
});
// 发送欢迎消息
sendMessage(ws, {
type: 'welcome',
clientId,
timestamp: Date.now()
});
// 处理消息
ws.on('message', (data) => {
try {
const msg = JSON.parse(data.toString());
log('debug', `Message from ${clientId}: ${msg.type}`);
switch (msg.type) {
case 'register':
handleRegister(clientId, client, msg.payload || {});
break;
case 'message':
handleMessage(clientId, client, msg);
break;
case 'command':
handleCommand(clientId, client, msg);
break;
case 'stream_start':
case 'stream_chunk':
case 'stream_end':
case 'process_update':
handleStreamMessage(clientId, client, msg);
break;
case 'subagent_update':
handleSubAgentUpdate(clientId, client, msg);
break;
case 'task_dispatch':
handleTaskDispatch(clientId, client, msg);
break;
case 'task_update':
handleTaskUpdate(clientId, client, msg);
break;
case 'task_cancel':
handleTaskCancel(clientId, client, msg);
break;
case 'memory_search':
handleMemorySearch(clientId, client, msg);
break;
case 'memory_result':
handleMemoryResult(clientId, client, msg);
break;
case 'ping':
handlePing(clientId, client);
break;
case 'broadcast':
const sent = broadcast(msg.payload, clientId);
log('info', `Broadcast from ${clientId}, sent to ${sent} clients`);
break;
default:
log('warn', `Unknown message type: ${msg.type}`, { clientId });
}
} catch (error) {
log('error', 'Failed to parse message', {
clientId,
error: error.message
});
}
});
// 处理错误
ws.on('error', (error) => {
log('error', `WebSocket error: ${clientId}`, {
error: error.message
});
});
// 处理断开
ws.on('close', () => {
cleanupClient(clientId);
});
}
// 创建 WS 服务器(明文,向后兼容)
const wss = new WebSocket.Server({ port: PORT });
wss.on('connection', handleConnection);
log('success', `🦞 OpenClaw Relay Server started on port ${PORT} (WS)`);
// 创建 WSS 服务器(加密)
try {
const sslOptions = {
cert: fs.readFileSync('/etc/letsencrypt/live/api.lingjiangapp.online/fullchain.pem'),
key: fs.readFileSync('/etc/letsencrypt/live/api.lingjiangapp.online/privkey.pem')
};
const httpsServer = https.createServer(sslOptions);
const wssSecure = new WebSocket.Server({ server: httpsServer });
wssSecure.on('connection', handleConnection);
httpsServer.listen(WSS_PORT, () => {
log('success', `🔒 WSS Server started on port ${WSS_PORT}`);
});
} catch (e) {
log('warn', `WSS disabled: ${e.message}`);
}
// 心跳检测(每 60 秒)
setInterval(() => {
const now = Date.now();
const timeout = 90000; // 90 秒超时
clients.forEach((client, clientId) => {
if (now - client.lastPing > timeout) {
log('warn', `Client timeout: ${clientId}`);
client.ws.close();
cleanupClient(clientId);
}
});
}, 60000);
// 状态报告(每 5 分钟)
setInterval(() => {
log('info', 'Server status', {
totalClients: clients.size,
openclawInstances: instances.size,
offlineQueues: offlineMessages.size
});
}, 300000);
// 优雅退出
process.on('SIGINT', () => {
log('info', 'Shutting down...');
// 通知所有客户端
broadcast({
type: 'server_shutdown',
payload: { message: 'Server is shutting down' }
});
// 关闭所有连接
clients.forEach((client) => {
client.ws.close();
});
wss.close(() => {
log('success', 'Server stopped');
process.exit(0);
});
});
process.on('SIGTERM', () => {
log('info', 'Received SIGTERM, shutting down...');
process.emit('SIGINT');
});