@wmxia/mcp-bridge 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/wsHub.js ADDED
@@ -0,0 +1,861 @@
1
+ import crypto from 'node:crypto';
2
+ import { EventEmitter } from 'node:events';
3
+ import http from 'node:http';
4
+ import { WebSocket, WebSocketServer } from 'ws';
5
+ import { AUTH_HANDSHAKE_TIMEOUT_MS, BRIDGE_VERSION, DEFAULT_BRIDGE_HOST, DEFAULT_BRIDGE_PORT, DEFAULT_CALL_TIMEOUT_MS, MCP_PROTOCOL_VERSION, generateNonce, isAllowedExtensionOrigin, logStderr, sha256Hex, signChallenge, verifyChallengeSignature, } from './protocol.js';
6
+ export class WmxBridgeHub extends EventEmitter {
7
+ tokenHash;
8
+ host;
9
+ port;
10
+ allowedOrigins;
11
+ callTimeoutMs;
12
+ clientName;
13
+ log;
14
+ role = 'stopped';
15
+ httpServer = null;
16
+ extWss = null;
17
+ agentWss = null;
18
+ extSocket = null;
19
+ extCapabilities = null;
20
+ followerSockets = new Set();
21
+ leaderSocket = null;
22
+ followerReconnectTimer = null;
23
+ closed = false;
24
+ pendingCalls = new Map();
25
+ pendingReads = new Map();
26
+ constructor(options) {
27
+ super();
28
+ if (!options.token || !options.token.trim()) {
29
+ throw new Error('WMX_MCP_TOKEN 不能为空');
30
+ }
31
+ const host = options.host || DEFAULT_BRIDGE_HOST;
32
+ if (host !== '127.0.0.1' && host !== 'localhost' && host !== '::1') {
33
+ throw new Error(`出于安全限制,Bridge 仅允许绑定本机回环地址,不支持 ${host}`);
34
+ }
35
+ this.tokenHash = sha256Hex(options.token.trim());
36
+ this.host = host;
37
+ this.port = options.port ?? DEFAULT_BRIDGE_PORT;
38
+ this.allowedOrigins = (options.allowedOrigins || []).filter(Boolean);
39
+ this.callTimeoutMs = options.callTimeoutMs ?? DEFAULT_CALL_TIMEOUT_MS;
40
+ this.clientName = options.clientName || 'wmx-mcp-bridge';
41
+ this.log = options.logger || logStderr;
42
+ }
43
+ getStatus() {
44
+ const extensionConnected = this.role === 'leader'
45
+ ? this.extSocket !== null && this.extSocket.readyState === WebSocket.OPEN && this.extCapabilities !== null
46
+ : this.leaderSocket !== null && this.leaderSocket.readyState === WebSocket.OPEN && this.extCapabilities !== null;
47
+ return {
48
+ role: this.role,
49
+ host: this.host,
50
+ port: this.port,
51
+ extensionConnected,
52
+ capabilities: extensionConnected ? this.extCapabilities : null,
53
+ followerCount: this.followerSockets.size,
54
+ bridgeVersion: BRIDGE_VERSION,
55
+ };
56
+ }
57
+ async start() {
58
+ this.closed = false;
59
+ this.role = 'starting';
60
+ const startedAsLeader = await this.tryStartAsLeader();
61
+ if (!startedAsLeader) {
62
+ this.log(`端口 ${this.host}:${this.port} 已被现有 Bridge 占用,自动切换为 Follower 模式复用连接`);
63
+ await this.connectAsFollower();
64
+ }
65
+ }
66
+ async close() {
67
+ this.closed = true;
68
+ this.role = 'stopped';
69
+ if (this.followerReconnectTimer) {
70
+ clearTimeout(this.followerReconnectTimer);
71
+ this.followerReconnectTimer = null;
72
+ }
73
+ this.rejectAllPending(new Error('MCP Bridge 已关闭'));
74
+ if (this.extSocket) {
75
+ this.extSocket.close(1000, 'Bridge shutting down');
76
+ this.extSocket = null;
77
+ }
78
+ for (const sock of this.followerSockets) {
79
+ sock.close(1000, 'Leader shutting down');
80
+ }
81
+ this.followerSockets.clear();
82
+ if (this.leaderSocket) {
83
+ this.leaderSocket.close(1000, 'Follower shutting down');
84
+ this.leaderSocket = null;
85
+ }
86
+ this.extWss?.close();
87
+ this.agentWss?.close();
88
+ this.extWss = null;
89
+ this.agentWss = null;
90
+ if (this.httpServer) {
91
+ const server = this.httpServer;
92
+ this.httpServer = null;
93
+ await new Promise((resolve) => {
94
+ server.close(() => resolve());
95
+ });
96
+ }
97
+ }
98
+ async callTool(name, args = {}, options) {
99
+ const id = crypto.randomUUID();
100
+ const clientName = options?.clientName || this.clientName;
101
+ if (this.role === 'leader') {
102
+ if (!this.extSocket || this.extSocket.readyState !== WebSocket.OPEN || !this.extCapabilities) {
103
+ return {
104
+ isError: true,
105
+ errorCode: 'EXTENSION_DISCONNECTED',
106
+ content: '外贸侠浏览器插件未连接。请确认 Chrome 已打开且在插件设置 ->「本地 Agent (MCP)」中开启了连接并核对 Token 与端口。',
107
+ };
108
+ }
109
+ return this.dispatchToolToExtension(id, name, args, clientName, options?.onProgress, options?.signal);
110
+ }
111
+ if (this.role === 'follower') {
112
+ if (!this.leaderSocket || this.leaderSocket.readyState !== WebSocket.OPEN) {
113
+ return {
114
+ isError: true,
115
+ errorCode: 'BRIDGE_DISCONNECTED',
116
+ content: '本地主 Bridge 正在重连,请稍后重试。',
117
+ };
118
+ }
119
+ if (!this.extCapabilities) {
120
+ return {
121
+ isError: true,
122
+ errorCode: 'EXTENSION_DISCONNECTED',
123
+ content: '外贸侠浏览器插件未连接。请确认 Chrome 已打开且在插件设置 ->「本地 Agent (MCP)」中开启了连接。',
124
+ };
125
+ }
126
+ return this.dispatchToolToLeader(id, name, args, clientName, options?.onProgress, options?.signal);
127
+ }
128
+ return {
129
+ isError: true,
130
+ errorCode: 'BRIDGE_NOT_READY',
131
+ content: 'MCP Bridge 尚未就绪。',
132
+ };
133
+ }
134
+ async readResource(uri, clientName) {
135
+ const id = crypto.randomUUID();
136
+ const caller = clientName || this.clientName;
137
+ if (this.role === 'leader') {
138
+ if (!this.extSocket || this.extSocket.readyState !== WebSocket.OPEN || !this.extCapabilities) {
139
+ return {
140
+ isError: true,
141
+ errorCode: 'EXTENSION_DISCONNECTED',
142
+ errorMessage: '外贸侠浏览器插件未连接,无法读取资源。',
143
+ };
144
+ }
145
+ return this.dispatchResourceToExtension(id, uri, caller);
146
+ }
147
+ if (this.role === 'follower') {
148
+ if (!this.leaderSocket || this.leaderSocket.readyState !== WebSocket.OPEN || !this.extCapabilities) {
149
+ return {
150
+ isError: true,
151
+ errorCode: 'EXTENSION_DISCONNECTED',
152
+ errorMessage: '外贸侠浏览器插件未连接,无法读取资源。',
153
+ };
154
+ }
155
+ return this.dispatchResourceToLeader(id, uri, caller);
156
+ }
157
+ return {
158
+ isError: true,
159
+ errorCode: 'BRIDGE_NOT_READY',
160
+ errorMessage: 'MCP Bridge 尚未就绪。',
161
+ };
162
+ }
163
+ // ==================== Leader 实现 ====================
164
+ async tryStartAsLeader() {
165
+ const httpServer = http.createServer((req, res) => {
166
+ res.writeHead(404, { 'Content-Type': 'application/json' });
167
+ res.end(JSON.stringify({ error: 'Use WebSocket endpoint /ext' }));
168
+ });
169
+ const extWss = new WebSocketServer({ noServer: true, maxPayload: 4 * 1024 * 1024 });
170
+ const agentWss = new WebSocketServer({ noServer: true, maxPayload: 4 * 1024 * 1024 });
171
+ httpServer.on('upgrade', (request, socket, head) => {
172
+ const hostHeader = request.headers.host || '';
173
+ const validHost = /^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(hostHeader);
174
+ if (!validHost) {
175
+ this.log(`拒绝非法 Host 升级请求: ${hostHeader}`);
176
+ socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
177
+ socket.destroy();
178
+ return;
179
+ }
180
+ const pathname = new URL(request.url || '/', `http://${hostHeader}`).pathname;
181
+ const origin = request.headers.origin;
182
+ if (pathname === '/ext' || pathname === '/') {
183
+ if (!isAllowedExtensionOrigin(origin, this.allowedOrigins)) {
184
+ this.log(`拒绝非扩展 Origin 连接 /ext: ${origin ?? '<empty>'}`);
185
+ socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
186
+ socket.destroy();
187
+ return;
188
+ }
189
+ extWss.handleUpgrade(request, socket, head, (ws) => {
190
+ this.handleExtensionConnection(ws, origin || '');
191
+ });
192
+ return;
193
+ }
194
+ if (pathname === '/agent') {
195
+ // 浏览器网页总是携带 Origin;/agent 只允许无 Origin 的本地进程连接
196
+ if (origin) {
197
+ this.log(`拒绝携带 Origin 的 /agent 连接: ${origin}`);
198
+ socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
199
+ socket.destroy();
200
+ return;
201
+ }
202
+ agentWss.handleUpgrade(request, socket, head, (ws) => {
203
+ this.handleFollowerConnection(ws);
204
+ });
205
+ return;
206
+ }
207
+ socket.write('HTTP/1.1 404 Not Found\r\n\r\n');
208
+ socket.destroy();
209
+ });
210
+ const bound = await new Promise((resolve, reject) => {
211
+ const onError = (err) => {
212
+ httpServer.removeListener('listening', onListening);
213
+ if (err.code === 'EADDRINUSE') {
214
+ resolve(false);
215
+ }
216
+ else {
217
+ reject(err);
218
+ }
219
+ };
220
+ const onListening = () => {
221
+ httpServer.removeListener('error', onError);
222
+ resolve(true);
223
+ };
224
+ httpServer.once('error', onError);
225
+ httpServer.once('listening', onListening);
226
+ httpServer.listen(this.port, this.host);
227
+ });
228
+ if (!bound) {
229
+ extWss.close();
230
+ agentWss.close();
231
+ return false;
232
+ }
233
+ this.httpServer = httpServer;
234
+ this.extWss = extWss;
235
+ this.agentWss = agentWss;
236
+ this.role = 'leader';
237
+ this.log(`Leader 已监听 ws://${this.host}:${this.port}/ext,等待外贸侠插件连接...`);
238
+ return true;
239
+ }
240
+ handleExtensionConnection(ws, origin) {
241
+ const nonce = generateNonce();
242
+ let authenticated = false;
243
+ const authTimer = setTimeout(() => {
244
+ if (!authenticated) {
245
+ this.sendJson(ws, { type: 'auth_error', code: 'AUTH_TIMEOUT', message: '握手超时' });
246
+ ws.close(4001, 'Auth timeout');
247
+ }
248
+ }, AUTH_HANDSHAKE_TIMEOUT_MS);
249
+ this.sendJson(ws, {
250
+ type: 'auth_challenge',
251
+ nonce,
252
+ bridgeVersion: BRIDGE_VERSION,
253
+ protocolVersion: MCP_PROTOCOL_VERSION,
254
+ });
255
+ ws.on('message', (raw) => {
256
+ let msg;
257
+ try {
258
+ msg = JSON.parse(raw.toString('utf8'));
259
+ }
260
+ catch {
261
+ return;
262
+ }
263
+ if (!authenticated) {
264
+ if (msg.type !== 'auth_response') {
265
+ this.sendJson(ws, { type: 'auth_error', code: 'AUTH_REQUIRED', message: '请先完成握手鉴权' });
266
+ ws.close(4002, 'Auth required');
267
+ return;
268
+ }
269
+ clearTimeout(authTimer);
270
+ if (!verifyChallengeSignature(this.tokenHash, nonce, msg.signature)) {
271
+ this.log(`插件鉴权失败 (origin=${origin}),请检查两端 WMX_MCP_TOKEN 是否一致`);
272
+ this.sendJson(ws, {
273
+ type: 'auth_error',
274
+ code: 'INVALID_TOKEN',
275
+ message: 'Token 签名校验失败,请确认插件与本地 Agent 配置的 WMX_MCP_TOKEN 一致',
276
+ });
277
+ ws.close(4003, 'Invalid token');
278
+ return;
279
+ }
280
+ authenticated = true;
281
+ const sessionId = crypto.randomUUID();
282
+ if (this.extSocket && this.extSocket !== ws && this.extSocket.readyState === WebSocket.OPEN) {
283
+ this.extSocket.close(1000, 'Replaced by newer extension session');
284
+ }
285
+ this.extSocket = ws;
286
+ this.extCapabilities = {
287
+ deviceId: msg.deviceId || 'unknown',
288
+ extensionVersion: msg.extensionVersion || 'unknown',
289
+ shopDomain: msg.shopDomain ?? null,
290
+ scopes: Array.isArray(msg.scopes) ? msg.scopes : [],
291
+ tools: Array.isArray(msg.tools) ? msg.tools : [],
292
+ resources: Array.isArray(msg.resources) ? msg.resources : [],
293
+ };
294
+ this.sendJson(ws, { type: 'auth_ok', sessionId });
295
+ this.log(`外贸侠插件已连接 (origin=${origin}, shop=${this.extCapabilities.shopDomain || '未识别'}, tools=${this.extCapabilities.tools.length})`);
296
+ this.broadcastExtensionState();
297
+ this.emit('capabilitiesChanged', this.extCapabilities);
298
+ return;
299
+ }
300
+ this.handleAuthenticatedExtensionMessage(msg);
301
+ });
302
+ ws.on('close', () => {
303
+ clearTimeout(authTimer);
304
+ if (this.extSocket === ws) {
305
+ this.extSocket = null;
306
+ this.extCapabilities = null;
307
+ this.log('外贸侠插件连接已断开');
308
+ this.rejectAllPending(new Error('外贸侠插件连接已断开'));
309
+ this.broadcastExtensionState();
310
+ this.emit('capabilitiesChanged', null);
311
+ }
312
+ });
313
+ ws.on('error', (err) => {
314
+ this.log(`插件 WS 连接异常: ${err.message}`);
315
+ });
316
+ }
317
+ handleAuthenticatedExtensionMessage(msg) {
318
+ if (msg.type === 'ping') {
319
+ if (this.extSocket) {
320
+ this.sendJson(this.extSocket, { type: 'pong', ts: msg.ts });
321
+ }
322
+ return;
323
+ }
324
+ if (msg.type === 'pong')
325
+ return;
326
+ if (msg.type === 'capabilities_update') {
327
+ if (this.extCapabilities) {
328
+ this.extCapabilities = {
329
+ ...this.extCapabilities,
330
+ shopDomain: msg.shopDomain !== undefined ? msg.shopDomain : this.extCapabilities.shopDomain,
331
+ scopes: Array.isArray(msg.scopes) ? msg.scopes : this.extCapabilities.scopes,
332
+ tools: Array.isArray(msg.tools) ? msg.tools : this.extCapabilities.tools,
333
+ resources: Array.isArray(msg.resources) ? msg.resources : this.extCapabilities.resources,
334
+ };
335
+ this.broadcastExtensionState();
336
+ this.emit('capabilitiesChanged', this.extCapabilities);
337
+ }
338
+ return;
339
+ }
340
+ if (msg.type === 'tool_progress') {
341
+ const pending = this.pendingCalls.get(msg.id);
342
+ if (!pending)
343
+ return;
344
+ if (pending.followerSocket && pending.originalId) {
345
+ this.sendJson(pending.followerSocket, {
346
+ type: 'tool_progress',
347
+ id: pending.originalId,
348
+ progress: msg.progress,
349
+ total: msg.total,
350
+ message: msg.message,
351
+ });
352
+ }
353
+ else {
354
+ pending.onProgress?.({ progress: msg.progress, total: msg.total, message: msg.message });
355
+ }
356
+ return;
357
+ }
358
+ if (msg.type === 'tool_result') {
359
+ const pending = this.pendingCalls.get(msg.id);
360
+ if (!pending)
361
+ return;
362
+ clearTimeout(pending.timer);
363
+ this.pendingCalls.delete(msg.id);
364
+ if (pending.followerSocket && pending.originalId) {
365
+ this.sendJson(pending.followerSocket, {
366
+ type: 'tool_result',
367
+ id: pending.originalId,
368
+ isError: msg.isError,
369
+ errorCode: msg.errorCode,
370
+ content: msg.content,
371
+ meta: msg.meta,
372
+ });
373
+ }
374
+ else {
375
+ pending.resolve({
376
+ isError: msg.isError,
377
+ errorCode: msg.errorCode,
378
+ content: msg.content,
379
+ meta: msg.meta,
380
+ });
381
+ }
382
+ return;
383
+ }
384
+ if (msg.type === 'resource_result') {
385
+ const pending = this.pendingReads.get(msg.id);
386
+ if (!pending)
387
+ return;
388
+ clearTimeout(pending.timer);
389
+ this.pendingReads.delete(msg.id);
390
+ if (pending.followerSocket && pending.originalId) {
391
+ this.sendJson(pending.followerSocket, {
392
+ type: 'resource_result',
393
+ id: pending.originalId,
394
+ isError: msg.isError,
395
+ errorCode: msg.errorCode,
396
+ mimeType: msg.mimeType,
397
+ text: msg.text,
398
+ errorMessage: msg.errorMessage,
399
+ });
400
+ }
401
+ else {
402
+ pending.resolve({
403
+ isError: msg.isError,
404
+ errorCode: msg.errorCode,
405
+ mimeType: msg.mimeType,
406
+ text: msg.text,
407
+ errorMessage: msg.errorMessage,
408
+ });
409
+ }
410
+ }
411
+ }
412
+ handleFollowerConnection(ws) {
413
+ const nonce = generateNonce();
414
+ let authenticated = false;
415
+ const authTimer = setTimeout(() => {
416
+ if (!authenticated) {
417
+ this.sendJson(ws, { type: 'auth_error', code: 'AUTH_TIMEOUT', message: 'Follower 握手超时' });
418
+ ws.close(4001, 'Auth timeout');
419
+ }
420
+ }, AUTH_HANDSHAKE_TIMEOUT_MS);
421
+ this.sendJson(ws, {
422
+ type: 'auth_challenge',
423
+ nonce,
424
+ bridgeVersion: BRIDGE_VERSION,
425
+ });
426
+ ws.on('message', (raw) => {
427
+ let msg;
428
+ try {
429
+ msg = JSON.parse(raw.toString('utf8'));
430
+ }
431
+ catch {
432
+ return;
433
+ }
434
+ if (!authenticated) {
435
+ if (msg.type !== 'auth_response' || !verifyChallengeSignature(this.tokenHash, nonce, msg.signature)) {
436
+ clearTimeout(authTimer);
437
+ this.sendJson(ws, {
438
+ type: 'auth_error',
439
+ code: 'INVALID_TOKEN',
440
+ message: 'Follower Token 与当前运行的 Leader 不一致',
441
+ });
442
+ ws.close(4003, 'Invalid token');
443
+ return;
444
+ }
445
+ clearTimeout(authTimer);
446
+ authenticated = true;
447
+ this.followerSockets.add(ws);
448
+ this.sendJson(ws, {
449
+ type: 'auth_ok',
450
+ sessionId: crypto.randomUUID(),
451
+ extensionConnected: this.extSocket !== null && this.extCapabilities !== null,
452
+ capabilities: this.extCapabilities,
453
+ });
454
+ return;
455
+ }
456
+ if (msg.type === 'tool_call') {
457
+ if (!this.extSocket || this.extSocket.readyState !== WebSocket.OPEN || !this.extCapabilities) {
458
+ this.sendJson(ws, {
459
+ type: 'tool_result',
460
+ id: msg.id,
461
+ isError: true,
462
+ errorCode: 'EXTENSION_DISCONNECTED',
463
+ content: '外贸侠浏览器插件未连接。',
464
+ });
465
+ return;
466
+ }
467
+ const leaderCallId = `flw_${crypto.randomUUID()}`;
468
+ const timer = setTimeout(() => {
469
+ this.pendingCalls.delete(leaderCallId);
470
+ this.sendJson(ws, {
471
+ type: 'tool_result',
472
+ id: msg.id,
473
+ isError: true,
474
+ errorCode: 'TIMEOUT',
475
+ content: `工具 ${msg.name} 执行超时 (${this.callTimeoutMs}ms)`,
476
+ });
477
+ }, this.callTimeoutMs);
478
+ this.pendingCalls.set(leaderCallId, {
479
+ resolve: () => { },
480
+ reject: () => { },
481
+ timer,
482
+ followerSocket: ws,
483
+ originalId: msg.id,
484
+ });
485
+ this.sendJson(this.extSocket, {
486
+ type: 'tool_call',
487
+ id: leaderCallId,
488
+ name: msg.name,
489
+ arguments: msg.arguments,
490
+ clientName: msg.clientName || 'follower-agent',
491
+ });
492
+ return;
493
+ }
494
+ if (msg.type === 'tool_cancel') {
495
+ for (const [leaderId, pending] of this.pendingCalls.entries()) {
496
+ if (pending.followerSocket === ws && pending.originalId === msg.id) {
497
+ clearTimeout(pending.timer);
498
+ this.pendingCalls.delete(leaderId);
499
+ if (this.extSocket && this.extSocket.readyState === WebSocket.OPEN) {
500
+ this.sendJson(this.extSocket, { type: 'tool_cancel', id: leaderId });
501
+ }
502
+ }
503
+ }
504
+ return;
505
+ }
506
+ if (msg.type === 'resource_read') {
507
+ if (!this.extSocket || this.extSocket.readyState !== WebSocket.OPEN || !this.extCapabilities) {
508
+ this.sendJson(ws, {
509
+ type: 'resource_result',
510
+ id: msg.id,
511
+ isError: true,
512
+ errorCode: 'EXTENSION_DISCONNECTED',
513
+ errorMessage: '外贸侠浏览器插件未连接。',
514
+ });
515
+ return;
516
+ }
517
+ const leaderReadId = `flw_res_${crypto.randomUUID()}`;
518
+ const timer = setTimeout(() => {
519
+ this.pendingReads.delete(leaderReadId);
520
+ this.sendJson(ws, {
521
+ type: 'resource_result',
522
+ id: msg.id,
523
+ isError: true,
524
+ errorCode: 'TIMEOUT',
525
+ errorMessage: `读取资源 ${msg.uri} 超时`,
526
+ });
527
+ }, this.callTimeoutMs);
528
+ this.pendingReads.set(leaderReadId, {
529
+ resolve: () => { },
530
+ reject: () => { },
531
+ timer,
532
+ followerSocket: ws,
533
+ originalId: msg.id,
534
+ });
535
+ this.sendJson(this.extSocket, {
536
+ type: 'resource_read',
537
+ id: leaderReadId,
538
+ uri: msg.uri,
539
+ clientName: msg.clientName || 'follower-agent',
540
+ });
541
+ }
542
+ });
543
+ ws.on('close', () => {
544
+ clearTimeout(authTimer);
545
+ this.followerSockets.delete(ws);
546
+ for (const [key, pending] of this.pendingCalls.entries()) {
547
+ if (pending.followerSocket === ws) {
548
+ clearTimeout(pending.timer);
549
+ this.pendingCalls.delete(key);
550
+ }
551
+ }
552
+ for (const [key, pending] of this.pendingReads.entries()) {
553
+ if (pending.followerSocket === ws) {
554
+ clearTimeout(pending.timer);
555
+ this.pendingReads.delete(key);
556
+ }
557
+ }
558
+ });
559
+ }
560
+ broadcastExtensionState() {
561
+ const payload = {
562
+ type: 'extension_state',
563
+ connected: this.extSocket !== null && this.extCapabilities !== null,
564
+ capabilities: this.extCapabilities,
565
+ };
566
+ for (const sock of this.followerSockets) {
567
+ if (sock.readyState === WebSocket.OPEN) {
568
+ this.sendJson(sock, payload);
569
+ }
570
+ }
571
+ }
572
+ // ==================== Follower 实现 ====================
573
+ async connectAsFollower() {
574
+ if (this.closed)
575
+ return;
576
+ this.role = 'follower';
577
+ await new Promise((resolve) => {
578
+ let settled = false;
579
+ const done = () => {
580
+ if (!settled) {
581
+ settled = true;
582
+ resolve();
583
+ }
584
+ };
585
+ const ws = new WebSocket(`ws://${this.host}:${this.port}/agent`);
586
+ this.leaderSocket = ws;
587
+ ws.on('message', (raw) => {
588
+ let msg;
589
+ try {
590
+ msg = JSON.parse(raw.toString('utf8'));
591
+ }
592
+ catch {
593
+ return;
594
+ }
595
+ if (msg.type === 'auth_challenge') {
596
+ const signature = signChallenge(this.tokenHash, msg.nonce);
597
+ this.sendJson(ws, {
598
+ type: 'auth_response',
599
+ signature,
600
+ clientName: this.clientName,
601
+ });
602
+ return;
603
+ }
604
+ if (msg.type === 'auth_ok') {
605
+ this.extCapabilities = msg.extensionConnected ? msg.capabilities : null;
606
+ this.log('已作为 Follower 接入本地主 Bridge');
607
+ this.emit('capabilitiesChanged', this.extCapabilities);
608
+ done();
609
+ return;
610
+ }
611
+ if (msg.type === 'auth_error') {
612
+ this.log(`Follower 鉴权失败: ${msg.message}`);
613
+ ws.close();
614
+ done();
615
+ return;
616
+ }
617
+ if (msg.type === 'extension_state') {
618
+ this.extCapabilities = msg.connected ? msg.capabilities : null;
619
+ this.emit('capabilitiesChanged', this.extCapabilities);
620
+ return;
621
+ }
622
+ if (msg.type === 'tool_progress') {
623
+ const pending = this.pendingCalls.get(msg.id);
624
+ pending?.onProgress?.({ progress: msg.progress, total: msg.total, message: msg.message });
625
+ return;
626
+ }
627
+ if (msg.type === 'tool_result') {
628
+ const pending = this.pendingCalls.get(msg.id);
629
+ if (!pending)
630
+ return;
631
+ clearTimeout(pending.timer);
632
+ this.pendingCalls.delete(msg.id);
633
+ pending.resolve({
634
+ isError: msg.isError,
635
+ errorCode: msg.errorCode,
636
+ content: msg.content,
637
+ meta: msg.meta,
638
+ });
639
+ return;
640
+ }
641
+ if (msg.type === 'resource_result') {
642
+ const pending = this.pendingReads.get(msg.id);
643
+ if (!pending)
644
+ return;
645
+ clearTimeout(pending.timer);
646
+ this.pendingReads.delete(msg.id);
647
+ pending.resolve({
648
+ isError: msg.isError,
649
+ errorCode: msg.errorCode,
650
+ mimeType: msg.mimeType,
651
+ text: msg.text,
652
+ errorMessage: msg.errorMessage,
653
+ });
654
+ }
655
+ });
656
+ ws.on('close', () => {
657
+ done();
658
+ if (this.leaderSocket === ws) {
659
+ this.leaderSocket = null;
660
+ this.extCapabilities = null;
661
+ this.rejectAllPending(new Error('与本地主 Bridge 的连接已断开'));
662
+ this.emit('capabilitiesChanged', null);
663
+ this.scheduleFollowerFailover();
664
+ }
665
+ });
666
+ ws.on('error', () => {
667
+ done();
668
+ });
669
+ });
670
+ }
671
+ scheduleFollowerFailover() {
672
+ if (this.closed || this.followerReconnectTimer)
673
+ return;
674
+ this.followerReconnectTimer = setTimeout(async () => {
675
+ this.followerReconnectTimer = null;
676
+ if (this.closed)
677
+ return;
678
+ try {
679
+ const becameLeader = await this.tryStartAsLeader();
680
+ if (!becameLeader) {
681
+ await this.connectAsFollower();
682
+ }
683
+ }
684
+ catch (err) {
685
+ this.log(`Follower 恢复失败: ${err instanceof Error ? err.message : String(err)}`);
686
+ this.scheduleFollowerFailover();
687
+ }
688
+ }, 1500);
689
+ }
690
+ // ==================== 调度辅助 ====================
691
+ dispatchToolToExtension(id, name, args, clientName, onProgress, signal) {
692
+ return new Promise((resolve, reject) => {
693
+ const timer = setTimeout(() => {
694
+ this.pendingCalls.delete(id);
695
+ resolve({
696
+ isError: true,
697
+ errorCode: 'TIMEOUT',
698
+ content: `调用工具 ${name} 超时 (${this.callTimeoutMs}ms)`,
699
+ });
700
+ }, this.callTimeoutMs);
701
+ const onAbort = () => {
702
+ clearTimeout(timer);
703
+ this.pendingCalls.delete(id);
704
+ if (this.extSocket && this.extSocket.readyState === WebSocket.OPEN) {
705
+ this.sendJson(this.extSocket, { type: 'tool_cancel', id });
706
+ }
707
+ resolve({ isError: true, errorCode: 'CANCELLED', content: '调用已取消' });
708
+ };
709
+ if (signal) {
710
+ if (signal.aborted) {
711
+ onAbort();
712
+ return;
713
+ }
714
+ signal.addEventListener('abort', onAbort, { once: true });
715
+ }
716
+ this.pendingCalls.set(id, {
717
+ resolve: (res) => {
718
+ signal?.removeEventListener('abort', onAbort);
719
+ resolve(res);
720
+ },
721
+ reject: (err) => {
722
+ signal?.removeEventListener('abort', onAbort);
723
+ reject(err);
724
+ },
725
+ timer,
726
+ onProgress,
727
+ });
728
+ this.sendJson(this.extSocket, {
729
+ type: 'tool_call',
730
+ id,
731
+ name,
732
+ arguments: args,
733
+ clientName,
734
+ });
735
+ });
736
+ }
737
+ dispatchToolToLeader(id, name, args, clientName, onProgress, signal) {
738
+ return new Promise((resolve, reject) => {
739
+ const timer = setTimeout(() => {
740
+ this.pendingCalls.delete(id);
741
+ resolve({
742
+ isError: true,
743
+ errorCode: 'TIMEOUT',
744
+ content: `调用工具 ${name} 超时 (${this.callTimeoutMs}ms)`,
745
+ });
746
+ }, this.callTimeoutMs);
747
+ const onAbort = () => {
748
+ clearTimeout(timer);
749
+ this.pendingCalls.delete(id);
750
+ if (this.leaderSocket && this.leaderSocket.readyState === WebSocket.OPEN) {
751
+ this.sendJson(this.leaderSocket, { type: 'tool_cancel', id });
752
+ }
753
+ resolve({ isError: true, errorCode: 'CANCELLED', content: '调用已取消' });
754
+ };
755
+ if (signal) {
756
+ if (signal.aborted) {
757
+ onAbort();
758
+ return;
759
+ }
760
+ signal.addEventListener('abort', onAbort, { once: true });
761
+ }
762
+ this.pendingCalls.set(id, {
763
+ resolve: (res) => {
764
+ signal?.removeEventListener('abort', onAbort);
765
+ resolve(res);
766
+ },
767
+ reject: (err) => {
768
+ signal?.removeEventListener('abort', onAbort);
769
+ reject(err);
770
+ },
771
+ timer,
772
+ onProgress,
773
+ });
774
+ this.sendJson(this.leaderSocket, {
775
+ type: 'tool_call',
776
+ id,
777
+ name,
778
+ arguments: args,
779
+ clientName,
780
+ });
781
+ });
782
+ }
783
+ dispatchResourceToExtension(id, uri, clientName) {
784
+ return new Promise((resolve, reject) => {
785
+ const timer = setTimeout(() => {
786
+ this.pendingReads.delete(id);
787
+ resolve({ isError: true, errorCode: 'TIMEOUT', errorMessage: `读取资源 ${uri} 超时` });
788
+ }, this.callTimeoutMs);
789
+ this.pendingReads.set(id, { resolve, reject, timer });
790
+ this.sendJson(this.extSocket, {
791
+ type: 'resource_read',
792
+ id,
793
+ uri,
794
+ clientName,
795
+ });
796
+ });
797
+ }
798
+ dispatchResourceToLeader(id, uri, clientName) {
799
+ return new Promise((resolve, reject) => {
800
+ const timer = setTimeout(() => {
801
+ this.pendingReads.delete(id);
802
+ resolve({ isError: true, errorCode: 'TIMEOUT', errorMessage: `读取资源 ${uri} 超时` });
803
+ }, this.callTimeoutMs);
804
+ this.pendingReads.set(id, { resolve, reject, timer });
805
+ this.sendJson(this.leaderSocket, {
806
+ type: 'resource_read',
807
+ id,
808
+ uri,
809
+ clientName,
810
+ });
811
+ });
812
+ }
813
+ rejectAllPending(error) {
814
+ for (const [id, pending] of this.pendingCalls.entries()) {
815
+ clearTimeout(pending.timer);
816
+ if (pending.followerSocket && pending.originalId) {
817
+ this.sendJson(pending.followerSocket, {
818
+ type: 'tool_result',
819
+ id: pending.originalId,
820
+ isError: true,
821
+ errorCode: 'EXTENSION_DISCONNECTED',
822
+ content: error.message,
823
+ });
824
+ }
825
+ else {
826
+ pending.resolve({
827
+ isError: true,
828
+ errorCode: 'EXTENSION_DISCONNECTED',
829
+ content: error.message,
830
+ });
831
+ }
832
+ this.pendingCalls.delete(id);
833
+ }
834
+ for (const [id, pending] of this.pendingReads.entries()) {
835
+ clearTimeout(pending.timer);
836
+ if (pending.followerSocket && pending.originalId) {
837
+ this.sendJson(pending.followerSocket, {
838
+ type: 'resource_result',
839
+ id: pending.originalId,
840
+ isError: true,
841
+ errorCode: 'EXTENSION_DISCONNECTED',
842
+ errorMessage: error.message,
843
+ });
844
+ }
845
+ else {
846
+ pending.resolve({
847
+ isError: true,
848
+ errorCode: 'EXTENSION_DISCONNECTED',
849
+ errorMessage: error.message,
850
+ });
851
+ }
852
+ this.pendingReads.delete(id);
853
+ }
854
+ }
855
+ sendJson(ws, payload) {
856
+ if (ws.readyState === WebSocket.OPEN) {
857
+ ws.send(JSON.stringify(payload));
858
+ }
859
+ }
860
+ }
861
+ //# sourceMappingURL=wsHub.js.map