surfcad-mcp 0.2.0 → 0.2.2
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/README.md +65 -8
- package/data/commands.json +1996 -301
- package/package.json +1 -1
- package/src/bridge/bridgePage.mjs +132 -0
- package/src/bridge/bridgePopup.mjs +261 -0
- package/src/bridge/localAddress.mjs +1 -1
- package/src/bridge/relayHub.mjs +282 -34
- package/src/bridge/relayServer.mjs +81 -13
- package/src/catalog.mjs +10 -0
- package/src/errors.mjs +24 -1
- package/src/nodeClient.mjs +27 -6
- package/src/prompt/promptSession.mjs +450 -0
- package/src/prompt/promptTools.mjs +152 -0
- package/src/prompt/webhookPost.mjs +111 -0
- package/src/prompt/webhookUrl.mjs +206 -0
- package/src/relay.mjs +319 -59
- package/src/relayMessages.mjs +8 -0
- package/src/screenshotFile.mjs +232 -0
- package/src/server.mjs +95 -19
package/src/bridge/relayHub.mjs
CHANGED
|
@@ -7,11 +7,37 @@ import { PAIR_MSG } from '../relayMessages.mjs';
|
|
|
7
7
|
import { isAllowedHttpOrigin, isLoopbackAddress } from './localAddress.mjs';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
|
-
* @typedef {{
|
|
10
|
+
* @typedef {{
|
|
11
|
+
* send: (data: string) => void,
|
|
12
|
+
* close: () => void,
|
|
13
|
+
* on: (event: string, cb: (...args: unknown[]) => void) => void,
|
|
14
|
+
* ping?: () => void,
|
|
15
|
+
* terminate?: () => void,
|
|
16
|
+
* remoteAddress?: string,
|
|
17
|
+
* origin?: string,
|
|
18
|
+
* }} RelaySocket
|
|
19
|
+
* @typedef {'info' | 'warn'} RelayLogLevel
|
|
11
20
|
*/
|
|
12
21
|
|
|
22
|
+
/** Opaque secrets (tab key, resume key) are random URL-safe strings. */
|
|
23
|
+
const SECRET_RE = /^[A-Za-z0-9_-]{16,128}$/;
|
|
24
|
+
|
|
25
|
+
/** How long a dropped tab keeps its pairing code so a squatter cannot take it. */
|
|
26
|
+
export const DEFAULT_TAB_RESERVATION_TTL_MS = 24 * 60 * 60 * 1000;
|
|
27
|
+
/** How often expired reservations are swept from the Map (unref'd timer). */
|
|
28
|
+
export const DEFAULT_TAB_RESERVATION_SWEEP_MS = 60 * 1000;
|
|
29
|
+
/**
|
|
30
|
+
* A 2 MiB PNG is about 2.8 MB of base64 plus a short JSON envelope.
|
|
31
|
+
* Larger prompt frames are refused before they are forwarded.
|
|
32
|
+
*/
|
|
33
|
+
export const DEFAULT_MAX_AGENT_PROMPT_FRAME_CHARS = 4 * 1024 * 1024;
|
|
34
|
+
|
|
13
35
|
function sendJson(socket, payload) {
|
|
14
|
-
|
|
36
|
+
try {
|
|
37
|
+
socket.send(JSON.stringify(payload));
|
|
38
|
+
} catch {
|
|
39
|
+
/* socket already gone */
|
|
40
|
+
}
|
|
15
41
|
}
|
|
16
42
|
|
|
17
43
|
function parseMessage(raw) {
|
|
@@ -25,6 +51,26 @@ function parseMessage(raw) {
|
|
|
25
51
|
}
|
|
26
52
|
}
|
|
27
53
|
|
|
54
|
+
function secretOrNull(value) {
|
|
55
|
+
return typeof value === 'string' && SECRET_RE.test(value) ? value : null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Logs must never carry a full pairing code: keep the first two characters.
|
|
60
|
+
* @param {string} token
|
|
61
|
+
*/
|
|
62
|
+
export function redactToken(token) {
|
|
63
|
+
const t = String(token || '');
|
|
64
|
+
if (!t) return '-';
|
|
65
|
+
return `${t.slice(0, 2)}${'*'.repeat(Math.max(2, t.length - 2))}`;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function closeReason(code, reason) {
|
|
69
|
+
const text = reason == null ? '' : String(reason);
|
|
70
|
+
if (code == null) return 'socket_closed';
|
|
71
|
+
return text ? `socket_closed code=${code} (${text.slice(0, 80)})` : `socket_closed code=${code}`;
|
|
72
|
+
}
|
|
73
|
+
|
|
28
74
|
/**
|
|
29
75
|
* @param {RelaySocket} socket
|
|
30
76
|
* @param {string} code
|
|
@@ -36,29 +82,107 @@ function refuse(socket, code, message) {
|
|
|
36
82
|
}
|
|
37
83
|
|
|
38
84
|
/**
|
|
39
|
-
* @param {{
|
|
85
|
+
* @param {{
|
|
86
|
+
* onLog?: (line: string, level: RelayLogLevel) => void,
|
|
87
|
+
* reservationTtlMs?: number,
|
|
88
|
+
* reservationSweepMs?: number,
|
|
89
|
+
* maxPromptFrameChars?: number,
|
|
90
|
+
* }} [opts]
|
|
40
91
|
*/
|
|
41
92
|
export function createAgentBridgeRelayHub(opts = {}) {
|
|
42
|
-
|
|
93
|
+
/** @param {string} line @param {RelayLogLevel} [level] */
|
|
94
|
+
const log = (line, level = 'info') => { opts.onLog?.(line, level); };
|
|
95
|
+
const reservationTtlMs = opts.reservationTtlMs ?? DEFAULT_TAB_RESERVATION_TTL_MS;
|
|
96
|
+
const reservationSweepMs = opts.reservationSweepMs ?? DEFAULT_TAB_RESERVATION_SWEEP_MS;
|
|
97
|
+
const maxPromptFrameChars = opts.maxPromptFrameChars ?? DEFAULT_MAX_AGENT_PROMPT_FRAME_CHARS;
|
|
43
98
|
|
|
44
|
-
/**
|
|
99
|
+
/**
|
|
100
|
+
* @type {Map<string, {
|
|
101
|
+
* socket: RelaySocket | null,
|
|
102
|
+
* token: string,
|
|
103
|
+
* tabKey: string | null,
|
|
104
|
+
* resumeKey: string | null,
|
|
105
|
+
* resumeTabKey: string | null,
|
|
106
|
+
* pairedPeer: RelaySocket | null,
|
|
107
|
+
* pendingPeer: RelaySocket | null,
|
|
108
|
+
* reservedAt: number | null,
|
|
109
|
+
* }>}
|
|
110
|
+
*/
|
|
45
111
|
const tabsByToken = new Map();
|
|
46
112
|
/** @type {Map<RelaySocket, { role: 'tab' | 'peer', token: string }>} */
|
|
47
113
|
const socketMeta = new Map();
|
|
114
|
+
/** @type {Map<RelaySocket, { alive: boolean, dropReason: string | null }>} */
|
|
115
|
+
const liveness = new Map();
|
|
116
|
+
|
|
117
|
+
function closePeer(peer) {
|
|
118
|
+
socketMeta.delete(peer);
|
|
119
|
+
try { peer.close(); } catch { /* gone */ }
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function reservationExpired(tab) {
|
|
123
|
+
return tab.socket == null
|
|
124
|
+
&& tab.reservedAt != null
|
|
125
|
+
&& (Date.now() - tab.reservedAt) > reservationTtlMs;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function liveTab(token) {
|
|
129
|
+
const tab = tabsByToken.get(token);
|
|
130
|
+
if (!tab) return null;
|
|
131
|
+
if (reservationExpired(tab)) {
|
|
132
|
+
tabsByToken.delete(token);
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
return tab;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function sweepExpiredReservations() {
|
|
139
|
+
for (const [token, tab] of tabsByToken) {
|
|
140
|
+
if (reservationExpired(tab)) tabsByToken.delete(token);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const sweepTimer = reservationSweepMs > 0
|
|
145
|
+
? setInterval(sweepExpiredReservations, reservationSweepMs)
|
|
146
|
+
: null;
|
|
147
|
+
if (typeof sweepTimer?.unref === 'function') sweepTimer.unref();
|
|
48
148
|
|
|
49
|
-
function
|
|
149
|
+
function emptyEntry(token, extra = {}) {
|
|
150
|
+
return {
|
|
151
|
+
socket: null,
|
|
152
|
+
token,
|
|
153
|
+
tabKey: extra.tabKey ?? null,
|
|
154
|
+
resumeKey: extra.resumeKey ?? null,
|
|
155
|
+
resumeTabKey: extra.resumeTabKey ?? extra.tabKey ?? null,
|
|
156
|
+
pairedPeer: null,
|
|
157
|
+
pendingPeer: null,
|
|
158
|
+
reservedAt: extra.reservedAt ?? null,
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function dropTab(token, reason) {
|
|
50
163
|
const tab = tabsByToken.get(token);
|
|
51
164
|
if (!tab) return;
|
|
52
|
-
|
|
165
|
+
if (tab.socket) socketMeta.delete(tab.socket);
|
|
166
|
+
const peerState = tab.pairedPeer ? 'paired' : (tab.pendingPeer ? 'pending' : 'none');
|
|
167
|
+
log(`tab dropped token=${redactToken(token)} reason=${reason} peer=${peerState}`, 'warn');
|
|
53
168
|
if (tab.pairedPeer) {
|
|
54
|
-
sendJson(tab.pairedPeer, { type: PAIR_MSG.UNPAIRED, reason: 'tab_disconnected' });
|
|
55
|
-
|
|
169
|
+
sendJson(tab.pairedPeer, { type: PAIR_MSG.UNPAIRED, reason: 'tab_disconnected', detail: reason });
|
|
170
|
+
closePeer(tab.pairedPeer);
|
|
56
171
|
}
|
|
57
172
|
if (tab.pendingPeer) {
|
|
58
173
|
sendJson(tab.pendingPeer, { type: PAIR_MSG.ERROR, code: 'pair_cancelled', message: 'Tab disconnected' });
|
|
59
|
-
|
|
174
|
+
closePeer(tab.pendingPeer);
|
|
175
|
+
}
|
|
176
|
+
if (tab.tabKey) {
|
|
177
|
+
tabsByToken.set(token, emptyEntry(token, {
|
|
178
|
+
tabKey: tab.tabKey,
|
|
179
|
+
resumeKey: tab.resumeKey,
|
|
180
|
+
resumeTabKey: tab.resumeTabKey || tab.tabKey,
|
|
181
|
+
reservedAt: Date.now(),
|
|
182
|
+
}));
|
|
183
|
+
return;
|
|
60
184
|
}
|
|
61
|
-
|
|
185
|
+
tabsByToken.delete(token);
|
|
62
186
|
}
|
|
63
187
|
|
|
64
188
|
function unpair(token, reason = 'disconnect') {
|
|
@@ -66,10 +190,10 @@ export function createAgentBridgeRelayHub(opts = {}) {
|
|
|
66
190
|
if (!tab || !tab.pairedPeer) return;
|
|
67
191
|
const peer = tab.pairedPeer;
|
|
68
192
|
tab.pairedPeer = null;
|
|
193
|
+
log(`pairing ended token=${redactToken(token)} reason=${reason}`, 'warn');
|
|
69
194
|
sendJson(tab.socket, { type: PAIR_MSG.UNPAIRED, reason });
|
|
70
195
|
sendJson(peer, { type: PAIR_MSG.UNPAIRED, reason });
|
|
71
|
-
|
|
72
|
-
try { peer.close(); } catch { /* gone */ }
|
|
196
|
+
closePeer(peer);
|
|
73
197
|
}
|
|
74
198
|
|
|
75
199
|
/**
|
|
@@ -86,8 +210,14 @@ export function createAgentBridgeRelayHub(opts = {}) {
|
|
|
86
210
|
return;
|
|
87
211
|
}
|
|
88
212
|
|
|
213
|
+
const live = { alive: true, dropReason: null };
|
|
214
|
+
if (typeof socket.ping === 'function') liveness.set(socket, live);
|
|
215
|
+
socket.on('pong', () => { live.alive = true; });
|
|
216
|
+
|
|
89
217
|
socket.on('message', (raw) => {
|
|
90
|
-
|
|
218
|
+
live.alive = true;
|
|
219
|
+
const rawText = typeof raw === 'string' ? raw : String(raw);
|
|
220
|
+
const msg = parseMessage(rawText);
|
|
91
221
|
if (!msg || typeof msg !== 'object') {
|
|
92
222
|
refuse(socket, 'bad_message', 'Expected JSON object');
|
|
93
223
|
return;
|
|
@@ -104,14 +234,38 @@ export function createAgentBridgeRelayHub(opts = {}) {
|
|
|
104
234
|
refuse(socket, 'bad_token', 'register_tab requires token');
|
|
105
235
|
return;
|
|
106
236
|
}
|
|
107
|
-
const
|
|
237
|
+
const tabKey = secretOrNull(msg.tabKey);
|
|
238
|
+
const existing = liveTab(token);
|
|
108
239
|
if (existing) {
|
|
109
|
-
|
|
240
|
+
// A reconnecting tab can beat the heartbeat to its own stale socket;
|
|
241
|
+
// only the tab that registered the code knows its tabKey. After a
|
|
242
|
+
// drop the entry is a reservation (socket null) for that same key.
|
|
243
|
+
if (!tabKey || existing.tabKey !== tabKey) {
|
|
244
|
+
refuse(socket, 'token_in_use', 'Another tab is already advertising this pairing code');
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
const stale = existing.socket;
|
|
248
|
+
// Closing the bridge window is a user action: the tab sends
|
|
249
|
+
// forgetResume so the same MCP client cannot silent-resume.
|
|
250
|
+
const forgetResume = msg.forgetResume === true;
|
|
251
|
+
const kept = {
|
|
252
|
+
tabKey: existing.tabKey,
|
|
253
|
+
resumeKey: forgetResume ? null : existing.resumeKey,
|
|
254
|
+
resumeTabKey: existing.resumeTabKey || existing.tabKey,
|
|
255
|
+
};
|
|
256
|
+
if (stale && stale !== socket) {
|
|
257
|
+
dropTab(token, 'replaced_by_reconnect');
|
|
258
|
+
liveness.delete(stale);
|
|
259
|
+
try { (stale.terminate || stale.close).call(stale); } catch { /* gone */ }
|
|
260
|
+
}
|
|
261
|
+
tabsByToken.set(token, { ...emptyEntry(token, kept), socket });
|
|
262
|
+
socketMeta.set(socket, { role: 'tab', token });
|
|
263
|
+
log(`tab registered token=${redactToken(token)} (reconnect)`);
|
|
110
264
|
return;
|
|
111
265
|
}
|
|
112
|
-
tabsByToken.set(token, {
|
|
266
|
+
tabsByToken.set(token, { ...emptyEntry(token, { tabKey }), socket });
|
|
113
267
|
socketMeta.set(socket, { role: 'tab', token });
|
|
114
|
-
log(`tab registered token=${token}`);
|
|
268
|
+
log(`tab registered token=${redactToken(token)}`);
|
|
115
269
|
return;
|
|
116
270
|
}
|
|
117
271
|
|
|
@@ -121,8 +275,8 @@ export function createAgentBridgeRelayHub(opts = {}) {
|
|
|
121
275
|
return;
|
|
122
276
|
}
|
|
123
277
|
const token = typeof msg.token === 'string' ? msg.token.trim().toUpperCase() : '';
|
|
124
|
-
const tab =
|
|
125
|
-
if (!tab) {
|
|
278
|
+
const tab = liveTab(token);
|
|
279
|
+
if (!tab || !tab.socket) {
|
|
126
280
|
refuse(socket, 'unknown_token', 'No SurfCAD tab is advertising this pairing code');
|
|
127
281
|
return;
|
|
128
282
|
}
|
|
@@ -134,10 +288,27 @@ export function createAgentBridgeRelayHub(opts = {}) {
|
|
|
134
288
|
refuse(socket, 'pair_pending', 'Tab is already reviewing another pairing request');
|
|
135
289
|
return;
|
|
136
290
|
}
|
|
137
|
-
|
|
291
|
+
const offered = secretOrNull(msg.resume);
|
|
292
|
+
const silentResume = Boolean(
|
|
293
|
+
offered
|
|
294
|
+
&& tab.resumeKey
|
|
295
|
+
&& offered === tab.resumeKey
|
|
296
|
+
&& tab.tabKey
|
|
297
|
+
&& tab.resumeTabKey
|
|
298
|
+
&& tab.tabKey === tab.resumeTabKey,
|
|
299
|
+
);
|
|
138
300
|
socketMeta.set(socket, { role: 'peer', token });
|
|
301
|
+
if (silentResume) {
|
|
302
|
+
tab.pendingPeer = null;
|
|
303
|
+
tab.pairedPeer = socket;
|
|
304
|
+
sendJson(tab.socket, { type: PAIR_MSG.PAIRED, token, resume: true });
|
|
305
|
+
sendJson(socket, { type: PAIR_MSG.PAIRED, token, resumeKey: tab.resumeKey });
|
|
306
|
+
log(`paired token=${redactToken(token)} (resume)`);
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
tab.pendingPeer = socket;
|
|
139
310
|
sendJson(tab.socket, { type: PAIR_MSG.PAIR_REQUEST, token });
|
|
140
|
-
log(`pair request token=${token}`);
|
|
311
|
+
log(`pair request token=${redactToken(token)}`);
|
|
141
312
|
return;
|
|
142
313
|
}
|
|
143
314
|
|
|
@@ -146,7 +317,7 @@ export function createAgentBridgeRelayHub(opts = {}) {
|
|
|
146
317
|
return;
|
|
147
318
|
}
|
|
148
319
|
|
|
149
|
-
const tab =
|
|
320
|
+
const tab = liveTab(meta.token);
|
|
150
321
|
if (!tab) {
|
|
151
322
|
refuse(socket, 'session_gone', 'Pairing session ended');
|
|
152
323
|
return;
|
|
@@ -162,11 +333,16 @@ export function createAgentBridgeRelayHub(opts = {}) {
|
|
|
162
333
|
sendJson(socket, { type: PAIR_MSG.ERROR, code: 'no_request', message: 'No pairing request to approve' });
|
|
163
334
|
return;
|
|
164
335
|
}
|
|
336
|
+
const resumeKey = secretOrNull(msg.resumeKey);
|
|
165
337
|
tab.pendingPeer = null;
|
|
166
338
|
tab.pairedPeer = peer;
|
|
339
|
+
tab.resumeKey = resumeKey;
|
|
340
|
+
tab.resumeTabKey = tab.tabKey;
|
|
167
341
|
sendJson(socket, { type: PAIR_MSG.PAIRED, token: meta.token });
|
|
168
|
-
sendJson(peer,
|
|
169
|
-
|
|
342
|
+
sendJson(peer, resumeKey
|
|
343
|
+
? { type: PAIR_MSG.PAIRED, token: meta.token, resumeKey }
|
|
344
|
+
: { type: PAIR_MSG.PAIRED, token: meta.token });
|
|
345
|
+
log(`paired token=${redactToken(meta.token)}`);
|
|
170
346
|
return;
|
|
171
347
|
}
|
|
172
348
|
|
|
@@ -179,12 +355,55 @@ export function createAgentBridgeRelayHub(opts = {}) {
|
|
|
179
355
|
tab.pendingPeer = null;
|
|
180
356
|
if (peer) {
|
|
181
357
|
sendJson(peer, { type: PAIR_MSG.ERROR, code: 'pair_rejected', message: 'Pairing rejected in SurfCAD' });
|
|
182
|
-
|
|
183
|
-
try { peer.close(); } catch { /* gone */ }
|
|
358
|
+
closePeer(peer);
|
|
184
359
|
}
|
|
185
360
|
return;
|
|
186
361
|
}
|
|
187
362
|
|
|
363
|
+
if (msg.type === PAIR_MSG.AGENT_PROMPT || msg.type === PAIR_MSG.AGENT_PROMPT_ACK
|
|
364
|
+
|| msg.type === PAIR_MSG.AGENT_REPLY || msg.type === PAIR_MSG.AGENT_STATUS) {
|
|
365
|
+
if (msg.type === PAIR_MSG.AGENT_PROMPT) {
|
|
366
|
+
if (meta.role !== 'tab') {
|
|
367
|
+
sendJson(socket, { type: PAIR_MSG.ERROR, code: 'forbidden', message: 'Only the paired tab sends prompts' });
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
const promptId = typeof msg.id === 'string' ? msg.id : undefined;
|
|
371
|
+
if (rawText.length > maxPromptFrameChars) {
|
|
372
|
+
sendJson(socket, {
|
|
373
|
+
type: PAIR_MSG.AGENT_PROMPT_ACK,
|
|
374
|
+
id: promptId,
|
|
375
|
+
delivery: 'failed',
|
|
376
|
+
error: 'screenshot_too_large',
|
|
377
|
+
});
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
if (tab.pairedPeer == null) {
|
|
381
|
+
sendJson(socket, {
|
|
382
|
+
type: PAIR_MSG.AGENT_PROMPT_ACK,
|
|
383
|
+
id: promptId,
|
|
384
|
+
delivery: 'failed',
|
|
385
|
+
error: 'not_paired',
|
|
386
|
+
});
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
sendJson(tab.pairedPeer, msg);
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
if (meta.role !== 'peer' || tab.pairedPeer !== socket || tab.socket == null) {
|
|
393
|
+
const wrongRole = meta.role !== 'peer';
|
|
394
|
+
sendJson(socket, {
|
|
395
|
+
type: PAIR_MSG.ERROR,
|
|
396
|
+
code: wrongRole ? 'forbidden' : 'not_paired',
|
|
397
|
+
message: wrongRole
|
|
398
|
+
? 'Only the paired agent sends replies and status'
|
|
399
|
+
: 'Pair before sending agent messages',
|
|
400
|
+
});
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
sendJson(tab.socket, msg);
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
406
|
+
|
|
188
407
|
if (typeof msg.command === 'string' && msg.type !== PAIR_MSG.PAIR) {
|
|
189
408
|
if (meta.role !== 'peer' || tab.pairedPeer !== socket) {
|
|
190
409
|
refuse(socket, 'not_paired', 'Pair before sending bridge commands');
|
|
@@ -219,17 +438,19 @@ export function createAgentBridgeRelayHub(opts = {}) {
|
|
|
219
438
|
refuse(socket, 'unknown_type', `Unknown message type: ${msg.type}`);
|
|
220
439
|
});
|
|
221
440
|
|
|
222
|
-
socket.on('close', () => {
|
|
441
|
+
socket.on('close', (code, reason) => {
|
|
442
|
+
liveness.delete(socket);
|
|
223
443
|
const m = socketMeta.get(socket);
|
|
224
444
|
if (!m) return;
|
|
445
|
+
const why = live.dropReason || closeReason(code, reason);
|
|
225
446
|
const tabEntry = tabsByToken.get(m.token);
|
|
226
447
|
if (!tabEntry) {
|
|
227
448
|
socketMeta.delete(socket);
|
|
228
449
|
return;
|
|
229
450
|
}
|
|
230
451
|
if (m.role === 'tab') {
|
|
231
|
-
dropTab(m.token);
|
|
232
|
-
|
|
452
|
+
if (tabEntry.socket === socket) dropTab(m.token, why);
|
|
453
|
+
else socketMeta.delete(socket);
|
|
233
454
|
return;
|
|
234
455
|
}
|
|
235
456
|
if (tabEntry.pendingPeer === socket) {
|
|
@@ -238,26 +459,53 @@ export function createAgentBridgeRelayHub(opts = {}) {
|
|
|
238
459
|
return;
|
|
239
460
|
}
|
|
240
461
|
if (tabEntry.pairedPeer === socket) {
|
|
241
|
-
unpair(m.token, 'peer_disconnected');
|
|
462
|
+
unpair(m.token, live.dropReason ? `peer_${live.dropReason}` : 'peer_disconnected');
|
|
242
463
|
}
|
|
243
464
|
socketMeta.delete(socket);
|
|
244
465
|
});
|
|
245
466
|
}
|
|
246
467
|
|
|
468
|
+
/**
|
|
469
|
+
* One heartbeat sweep: terminate sockets that did not answer the previous
|
|
470
|
+
* ping, then ping the rest. Call every `heartbeatMs`.
|
|
471
|
+
*/
|
|
472
|
+
function heartbeat() {
|
|
473
|
+
for (const [socket, live] of liveness) {
|
|
474
|
+
if (!live.alive) {
|
|
475
|
+
live.dropReason = 'heartbeat_timeout';
|
|
476
|
+
liveness.delete(socket);
|
|
477
|
+
try { (socket.terminate || socket.close).call(socket); } catch { /* gone */ }
|
|
478
|
+
continue;
|
|
479
|
+
}
|
|
480
|
+
live.alive = false;
|
|
481
|
+
try { socket.ping?.(); } catch { /* gone; next sweep terminates */ }
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
|
|
247
485
|
function disconnectToken(token) {
|
|
248
|
-
const tab =
|
|
486
|
+
const tab = liveTab(token);
|
|
249
487
|
if (!tab) return;
|
|
250
488
|
unpair(token, 'tab_disconnect');
|
|
251
489
|
try { tab.socket.close(); } catch { /* gone */ }
|
|
252
|
-
dropTab(token);
|
|
490
|
+
dropTab(token, 'disconnect_requested');
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
function dispose() {
|
|
494
|
+
if (sweepTimer) clearInterval(sweepTimer);
|
|
253
495
|
}
|
|
254
496
|
|
|
255
497
|
return {
|
|
256
498
|
attachSocket,
|
|
257
499
|
disconnectToken,
|
|
500
|
+
heartbeat,
|
|
501
|
+
dispose,
|
|
258
502
|
/** @param {string} token */
|
|
259
503
|
hasTab(token) {
|
|
260
|
-
return
|
|
504
|
+
return liveTab(token) != null;
|
|
505
|
+
},
|
|
506
|
+
/** @param {string} token */
|
|
507
|
+
isPaired(token) {
|
|
508
|
+
return liveTab(token)?.pairedPeer != null;
|
|
261
509
|
},
|
|
262
510
|
PAIR_MSG,
|
|
263
511
|
};
|
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Loopback HTTP/WebSocket server for the M1 agent-bridge relay.
|
|
3
3
|
* Binds 127.0.0.1 only. Handles CORS / Private Network Access preflight for
|
|
4
|
-
* https://surfcad.com → ws://127.0.0.1 upgrades
|
|
4
|
+
* https://surfcad.com → ws://127.0.0.1 upgrades, and serves the `/bridge`
|
|
5
|
+
* popup page for browsers that block that upgrade (Safari).
|
|
5
6
|
*/
|
|
6
7
|
|
|
7
8
|
import { createServer } from 'node:http';
|
|
8
9
|
import { WebSocket, WebSocketServer } from 'ws';
|
|
9
10
|
import { createAgentBridgeRelayHub } from './relayHub.mjs';
|
|
10
|
-
import { isAllowedHttpOrigin, isLoopbackAddress } from './localAddress.mjs';
|
|
11
|
+
import { extraAllowedOrigins, isAllowedHttpOrigin, isLoopbackAddress } from './localAddress.mjs';
|
|
12
|
+
import { handleBridgeRequest } from './bridgePage.mjs';
|
|
13
|
+
import { loadCommandsCatalog, toolsCatalogPayload } from '../catalog.mjs';
|
|
11
14
|
|
|
12
15
|
export const DEFAULT_RELAY_PORT = 17341;
|
|
13
16
|
|
|
@@ -65,19 +68,39 @@ export function probeRelayAtUrl(url, timeoutMs = 1500) {
|
|
|
65
68
|
});
|
|
66
69
|
}
|
|
67
70
|
|
|
71
|
+
export const DEFAULT_HEARTBEAT_MS = 5000;
|
|
72
|
+
|
|
73
|
+
function parseHeartbeatMs(value) {
|
|
74
|
+
const n = Number(value);
|
|
75
|
+
return Number.isFinite(n) && n >= 50 ? n : DEFAULT_HEARTBEAT_MS;
|
|
76
|
+
}
|
|
77
|
+
|
|
68
78
|
/**
|
|
69
|
-
*
|
|
79
|
+
* Drops and heartbeat timeouts always go to stderr (stdout is the MCP stdio
|
|
80
|
+
* channel); routine pairing lines only with SURFCAD_AGENT_BRIDGE_WS_VERBOSE=1.
|
|
81
|
+
*
|
|
82
|
+
* @param {string} line
|
|
83
|
+
* @param {'info' | 'warn'} [level]
|
|
84
|
+
*/
|
|
85
|
+
export function defaultRelayLog(line, level = 'info') {
|
|
86
|
+
if (level !== 'warn' && process.env.SURFCAD_AGENT_BRIDGE_WS_VERBOSE !== '1') return;
|
|
87
|
+
console.error(`${new Date().toISOString()} [surfcad-relay] ${level === 'warn' ? 'WARN ' : ''}${line}`);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* @param {{
|
|
92
|
+
* port?: number,
|
|
93
|
+
* host?: string,
|
|
94
|
+
* heartbeatMs?: number,
|
|
95
|
+
* onReady?: (url: string) => void,
|
|
96
|
+
* onLog?: (line: string, level: 'info' | 'warn') => void,
|
|
97
|
+
* }} [options]
|
|
70
98
|
*/
|
|
71
99
|
export function startAgentBridgeRelay(options = {}) {
|
|
72
100
|
const host = options.host || '127.0.0.1';
|
|
73
101
|
const port = options.port ?? parsePort(process.env.SURFCAD_AGENT_BRIDGE_WS_PORT);
|
|
74
|
-
const
|
|
75
|
-
|
|
76
|
-
if (process.env.SURFCAD_AGENT_BRIDGE_WS_VERBOSE === '1') {
|
|
77
|
-
console.log(`[agent-bridge-ws] ${line}`);
|
|
78
|
-
}
|
|
79
|
-
}),
|
|
80
|
-
});
|
|
102
|
+
const heartbeatMs = options.heartbeatMs ?? parseHeartbeatMs(process.env.SURFCAD_AGENT_BRIDGE_HEARTBEAT_MS);
|
|
103
|
+
const hub = createAgentBridgeRelayHub({ onLog: options.onLog || defaultRelayLog });
|
|
81
104
|
|
|
82
105
|
const server = createServer((req, res) => {
|
|
83
106
|
const origin = req.headers.origin;
|
|
@@ -99,6 +122,30 @@ export function startAgentBridgeRelay(options = {}) {
|
|
|
99
122
|
return;
|
|
100
123
|
}
|
|
101
124
|
|
|
125
|
+
const bound = server.address();
|
|
126
|
+
const boundPort = bound && typeof bound === 'object' ? bound.port : port;
|
|
127
|
+
if (handleBridgeRequest(req, res, { port: boundPort, extraOrigins: [...extraAllowedOrigins()] })) {
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
let pathname = '/';
|
|
132
|
+
try {
|
|
133
|
+
pathname = new URL(req.url || '/', 'http://127.0.0.1').pathname;
|
|
134
|
+
} catch {
|
|
135
|
+
pathname = '/';
|
|
136
|
+
}
|
|
137
|
+
if (req.method === 'GET' && pathname === '/tools') {
|
|
138
|
+
const body = JSON.stringify(toolsCatalogPayload(loadCommandsCatalog()));
|
|
139
|
+
res.writeHead(200, {
|
|
140
|
+
...cors,
|
|
141
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
142
|
+
'Cache-Control': 'no-store',
|
|
143
|
+
'Content-Length': Buffer.byteLength(body),
|
|
144
|
+
});
|
|
145
|
+
res.end(body);
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
|
|
102
149
|
res.writeHead(404, cors);
|
|
103
150
|
res.end();
|
|
104
151
|
});
|
|
@@ -121,8 +168,12 @@ export function startAgentBridgeRelay(options = {}) {
|
|
|
121
168
|
}
|
|
122
169
|
const origin = req.headers.origin;
|
|
123
170
|
if (origin && !isAllowedHttpOrigin(origin)) {
|
|
124
|
-
|
|
125
|
-
|
|
171
|
+
// Complete the handshake and policy-close so the browser probe can
|
|
172
|
+
// read close 1008 / reason origin_blocked. A raw HTTP 403 never
|
|
173
|
+
// becomes a WebSocket (browsers report 1006, same as ECONNREFUSED).
|
|
174
|
+
wss.handleUpgrade(req, socket, head, (ws) => {
|
|
175
|
+
ws.close(1008, 'origin_blocked');
|
|
176
|
+
});
|
|
126
177
|
return;
|
|
127
178
|
}
|
|
128
179
|
wss.handleUpgrade(req, socket, head, (ws) => {
|
|
@@ -130,13 +181,26 @@ export function startAgentBridgeRelay(options = {}) {
|
|
|
130
181
|
hub.attachSocket({
|
|
131
182
|
send: (data) => { ws.send(data); },
|
|
132
183
|
close: () => { ws.close(); },
|
|
133
|
-
|
|
184
|
+
ping: () => { ws.ping(); },
|
|
185
|
+
terminate: () => { ws.terminate(); },
|
|
186
|
+
on: (event, cb) => {
|
|
187
|
+
if (event === 'close') {
|
|
188
|
+
ws.on('close', (code, reason) => cb(code, reason?.toString?.() || ''));
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
ws.on(event, cb);
|
|
192
|
+
},
|
|
134
193
|
remoteAddress: remote,
|
|
135
194
|
origin,
|
|
136
195
|
});
|
|
137
196
|
});
|
|
138
197
|
});
|
|
139
198
|
|
|
199
|
+
const heartbeatTimer = setInterval(() => { hub.heartbeat(); }, heartbeatMs);
|
|
200
|
+
if (typeof heartbeatTimer.unref === 'function') heartbeatTimer.unref();
|
|
201
|
+
wss.on('close', () => { clearInterval(heartbeatTimer); });
|
|
202
|
+
server.on('close', () => { clearInterval(heartbeatTimer); });
|
|
203
|
+
|
|
140
204
|
return new Promise((resolve, reject) => {
|
|
141
205
|
server.listen(port, host, () => {
|
|
142
206
|
const bound = server.address();
|
|
@@ -194,6 +258,7 @@ export async function ensureAgentBridgeRelay(options = {}) {
|
|
|
194
258
|
* @param {{ server?: import('node:http').Server | null, wss?: import('ws').WebSocketServer | null, port?: number, ownsServer?: boolean } | null | undefined} relay
|
|
195
259
|
*/
|
|
196
260
|
export function stopAgentBridgeRelay(relay) {
|
|
261
|
+
relay?.hub?.dispose?.();
|
|
197
262
|
if (!relay || !relay.ownsServer) {
|
|
198
263
|
return Promise.resolve();
|
|
199
264
|
}
|
|
@@ -202,6 +267,9 @@ export function stopAgentBridgeRelay(relay) {
|
|
|
202
267
|
const wss = relay.wss;
|
|
203
268
|
const server = relay.server;
|
|
204
269
|
if (wss) {
|
|
270
|
+
for (const client of wss.clients) {
|
|
271
|
+
try { client.terminate(); } catch { /* gone */ }
|
|
272
|
+
}
|
|
205
273
|
wss.close(() => {
|
|
206
274
|
if (server) server.close(finish);
|
|
207
275
|
else finish();
|
package/src/catalog.mjs
CHANGED
|
@@ -24,3 +24,13 @@ export function bridgeToolDefinitions(doc) {
|
|
|
24
24
|
inputSchema: row.args,
|
|
25
25
|
}));
|
|
26
26
|
}
|
|
27
|
+
|
|
28
|
+
/** JSON body for GET /tools. Same rows as the MCP bridge tools and commands.json. */
|
|
29
|
+
export function toolsCatalogPayload(doc) {
|
|
30
|
+
const tools = bridgeToolDefinitions(doc);
|
|
31
|
+
return {
|
|
32
|
+
version: doc.version,
|
|
33
|
+
count: tools.length,
|
|
34
|
+
tools,
|
|
35
|
+
};
|
|
36
|
+
}
|
package/src/errors.mjs
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
|
+
export const RECONNECT_HINT = 'Open SurfCAD in Chrome and keep the tab open; it will reconnect.';
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
|
-
* @param {{ code?: string, message?: string, details?: unknown }} err
|
|
4
|
+
* @param {{ code?: string, message?: string, details?: unknown, hint?: string, retryable?: boolean }} err
|
|
3
5
|
*/
|
|
4
6
|
export function formatBridgeError(err) {
|
|
5
7
|
const code = err?.code || 'bridge_error';
|
|
6
8
|
const message = err?.message || 'Bridge call failed';
|
|
7
9
|
const payload = { code, message };
|
|
10
|
+
if (err?.hint) payload.hint = err.hint;
|
|
11
|
+
if (err?.retryable !== undefined) payload.retryable = err.retryable;
|
|
8
12
|
if (err?.details !== undefined) payload.details = err.details;
|
|
9
13
|
return payload;
|
|
10
14
|
}
|
|
@@ -13,9 +17,28 @@ export function notPairedError() {
|
|
|
13
17
|
return {
|
|
14
18
|
code: 'not_paired',
|
|
15
19
|
message: 'Not paired to a SurfCAD tab. Set SURFCAD_PAIRING_CODE or call the pair tool, then click Allow in the app.',
|
|
20
|
+
hint: pairingEnvHint(),
|
|
16
21
|
};
|
|
17
22
|
}
|
|
18
23
|
|
|
24
|
+
/**
|
|
25
|
+
* @param {string} [reason]
|
|
26
|
+
*/
|
|
27
|
+
export function pairingLostError(reason) {
|
|
28
|
+
const why = reason ? ` (${reason})` : '';
|
|
29
|
+
return Object.assign(
|
|
30
|
+
new Error(`Lost the connection to the SurfCAD tab${why}. Reconnecting in the background; retry in a few seconds.`),
|
|
31
|
+
{ code: 'pairing_lost', hint: RECONNECT_HINT, retryable: true },
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function pairPendingError() {
|
|
36
|
+
return Object.assign(
|
|
37
|
+
new Error('Waiting for Allow in SurfCAD. Click Allow in the app, then retry.'),
|
|
38
|
+
{ code: 'pair_pending', hint: 'The pairing request is still open in the SurfCAD tab.', retryable: true },
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
|
|
19
42
|
export function pairingEnvHint() {
|
|
20
43
|
return 'Copy the 6-character code from SurfCAD → Local agent → Show pairing code.';
|
|
21
44
|
}
|