surfcad-mcp 0.3.9 → 0.4.0
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 +70 -49
- package/bin/surfcad-mcp.js +4 -3
- package/data/commands.json +6481 -5817
- package/data/helpers.json +243 -268
- package/package.json +2 -2
- package/src/cli.mjs +221 -23
- package/src/cliCall.mjs +221 -0
- package/src/errors.mjs +8 -5
- package/src/helpers.mjs +7 -5
- package/src/importFile.mjs +186 -0
- package/src/listen/bootstrap.mjs +87 -34
- package/src/listen/claudeCodeWake.mjs +74 -0
- package/src/listen/daemon.mjs +35 -0
- package/src/listen/listenCli.mjs +121 -30
- package/src/listen/listener.mjs +138 -8
- package/src/listen/owner.mjs +293 -0
- package/src/listen/waitCli.mjs +133 -0
- package/src/listen/wake.mjs +39 -19
- package/src/listen/wakeSetupText.mjs +23 -5
- package/src/pairWait.mjs +3 -3
- package/src/pairingCode.mjs +10 -0
- package/src/prompt/buildGuidance.mjs +9 -7
- package/src/prompt/chatFlow.mjs +15 -0
- package/src/prompt/errorHints.mjs +24 -10
- package/src/prompt/guide.mjs +27 -14
- package/src/prompt/promptSession.mjs +74 -10
- package/src/prompt/promptTools.mjs +10 -6
- package/src/prompt/replyConfirm.mjs +69 -0
- package/src/relayMessages.mjs +43 -1
- package/src/remote/config.mjs +17 -13
- package/src/remote/session.mjs +103 -5
- package/src/room/seat.mjs +334 -0
- package/src/screenshotFile.mjs +9 -0
- package/src/server.mjs +155 -111
- package/src/stepUploadLimit.mjs +8 -0
- package/src/bridge/bridgePage.mjs +0 -132
- package/src/bridge/bridgePopup.mjs +0 -288
- package/src/bridge/relayHub.mjs +0 -556
- package/src/bridge/relayServer.mjs +0 -291
- package/src/nodeClient.mjs +0 -63
- package/src/relay.mjs +0 -419
package/src/bridge/relayHub.mjs
DELETED
|
@@ -1,556 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* In-memory hub for pairing a browser tab with one local peer over WebSocket.
|
|
3
|
-
* Canonical implementation shared by surfcad-mcp and the SurfCAD dev server.
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
import { AGENT_PROTOCOL_VERSION, commandRequest, commandResponse, readCommandResponse } from '../commandProtocol.mjs';
|
|
7
|
-
import { PAIR_MSG } from '../relayMessages.mjs';
|
|
8
|
-
import { isAllowedHttpOrigin, isLoopbackAddress } from './localAddress.mjs';
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* @typedef {{
|
|
12
|
-
* send: (data: string) => void,
|
|
13
|
-
* close: () => void,
|
|
14
|
-
* on: (event: string, cb: (...args: unknown[]) => void) => void,
|
|
15
|
-
* ping?: () => void,
|
|
16
|
-
* terminate?: () => void,
|
|
17
|
-
* remoteAddress?: string,
|
|
18
|
-
* origin?: string,
|
|
19
|
-
* }} RelaySocket
|
|
20
|
-
* @typedef {'info' | 'warn'} RelayLogLevel
|
|
21
|
-
*/
|
|
22
|
-
|
|
23
|
-
/** Opaque secrets (tab key, resume key) are random URL-safe strings. */
|
|
24
|
-
const SECRET_RE = /^[A-Za-z0-9_-]{16,128}$/;
|
|
25
|
-
|
|
26
|
-
/** How long a dropped tab keeps its pairing code so a squatter cannot take it. */
|
|
27
|
-
export const DEFAULT_TAB_RESERVATION_TTL_MS = 24 * 60 * 60 * 1000;
|
|
28
|
-
/** How often expired reservations are swept from the Map (unref'd timer). */
|
|
29
|
-
export const DEFAULT_TAB_RESERVATION_SWEEP_MS = 60 * 1000;
|
|
30
|
-
/**
|
|
31
|
-
* A 2 MiB PNG is about 2.8 MB of base64 plus a short JSON envelope.
|
|
32
|
-
* Larger prompt frames are refused before they are forwarded.
|
|
33
|
-
*/
|
|
34
|
-
export const DEFAULT_MAX_AGENT_PROMPT_FRAME_CHARS = 4 * 1024 * 1024;
|
|
35
|
-
|
|
36
|
-
function sendJson(socket, payload) {
|
|
37
|
-
try {
|
|
38
|
-
socket.send(JSON.stringify(payload));
|
|
39
|
-
} catch {
|
|
40
|
-
/* socket already gone */
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
function parseMessage(raw) {
|
|
45
|
-
if (typeof raw !== 'string') return null;
|
|
46
|
-
try {
|
|
47
|
-
const msg = JSON.parse(raw);
|
|
48
|
-
if (!msg || typeof msg !== 'object' || Array.isArray(msg)) return null;
|
|
49
|
-
return msg;
|
|
50
|
-
} catch {
|
|
51
|
-
return null;
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
function secretOrNull(value) {
|
|
56
|
-
return typeof value === 'string' && SECRET_RE.test(value) ? value : null;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/**
|
|
60
|
-
* Logs must never carry a full pairing code: keep the first two characters.
|
|
61
|
-
* @param {string} token
|
|
62
|
-
*/
|
|
63
|
-
export function redactToken(token) {
|
|
64
|
-
const t = String(token || '');
|
|
65
|
-
if (!t) return '-';
|
|
66
|
-
return `${t.slice(0, 2)}${'*'.repeat(Math.max(2, t.length - 2))}`;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
function closeReason(code, reason) {
|
|
70
|
-
const text = reason == null ? '' : String(reason);
|
|
71
|
-
if (code == null) return 'socket_closed';
|
|
72
|
-
return text ? `socket_closed code=${code} (${text.slice(0, 80)})` : `socket_closed code=${code}`;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
/**
|
|
76
|
-
* @param {RelaySocket} socket
|
|
77
|
-
* @param {string} code
|
|
78
|
-
* @param {string} message
|
|
79
|
-
*/
|
|
80
|
-
function refuse(socket, code, message) {
|
|
81
|
-
sendJson(socket, { type: PAIR_MSG.ERROR, code, message });
|
|
82
|
-
try { socket.close(); } catch { /* already closed */ }
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/**
|
|
86
|
-
* @param {{
|
|
87
|
-
* onLog?: (line: string, level: RelayLogLevel) => void,
|
|
88
|
-
* reservationTtlMs?: number,
|
|
89
|
-
* reservationSweepMs?: number,
|
|
90
|
-
* maxPromptFrameChars?: number,
|
|
91
|
-
* }} [opts]
|
|
92
|
-
*/
|
|
93
|
-
export function createAgentBridgeRelayHub(opts = {}) {
|
|
94
|
-
/** @param {string} line @param {RelayLogLevel} [level] */
|
|
95
|
-
const log = (line, level = 'info') => { opts.onLog?.(line, level); };
|
|
96
|
-
const reservationTtlMs = opts.reservationTtlMs ?? DEFAULT_TAB_RESERVATION_TTL_MS;
|
|
97
|
-
const reservationSweepMs = opts.reservationSweepMs ?? DEFAULT_TAB_RESERVATION_SWEEP_MS;
|
|
98
|
-
const maxPromptFrameChars = opts.maxPromptFrameChars ?? DEFAULT_MAX_AGENT_PROMPT_FRAME_CHARS;
|
|
99
|
-
|
|
100
|
-
/**
|
|
101
|
-
* @type {Map<string, {
|
|
102
|
-
* socket: RelaySocket | null,
|
|
103
|
-
* token: string,
|
|
104
|
-
* tabKey: string | null,
|
|
105
|
-
* resumeKey: string | null,
|
|
106
|
-
* resumeTabKey: string | null,
|
|
107
|
-
* pairedPeer: RelaySocket | null,
|
|
108
|
-
* pendingPeer: RelaySocket | null,
|
|
109
|
-
* reservedAt: number | null,
|
|
110
|
-
* }>}
|
|
111
|
-
*/
|
|
112
|
-
const tabsByToken = new Map();
|
|
113
|
-
/** @type {Map<RelaySocket, { role: 'tab' | 'peer', token: string }>} */
|
|
114
|
-
const socketMeta = new Map();
|
|
115
|
-
/** @type {Map<RelaySocket, { alive: boolean, dropReason: string | null }>} */
|
|
116
|
-
const liveness = new Map();
|
|
117
|
-
|
|
118
|
-
function closePeer(peer) {
|
|
119
|
-
socketMeta.delete(peer);
|
|
120
|
-
try { peer.close(); } catch { /* gone */ }
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
function reservationExpired(tab) {
|
|
124
|
-
return tab.socket == null
|
|
125
|
-
&& tab.reservedAt != null
|
|
126
|
-
&& (Date.now() - tab.reservedAt) > reservationTtlMs;
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
function liveTab(token) {
|
|
130
|
-
const tab = tabsByToken.get(token);
|
|
131
|
-
if (!tab) return null;
|
|
132
|
-
if (reservationExpired(tab)) {
|
|
133
|
-
tabsByToken.delete(token);
|
|
134
|
-
return null;
|
|
135
|
-
}
|
|
136
|
-
return tab;
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
function sweepExpiredReservations() {
|
|
140
|
-
for (const [token, tab] of tabsByToken) {
|
|
141
|
-
if (reservationExpired(tab)) tabsByToken.delete(token);
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
const sweepTimer = reservationSweepMs > 0
|
|
146
|
-
? setInterval(sweepExpiredReservations, reservationSweepMs)
|
|
147
|
-
: null;
|
|
148
|
-
if (typeof sweepTimer?.unref === 'function') sweepTimer.unref();
|
|
149
|
-
|
|
150
|
-
function emptyEntry(token, extra = {}) {
|
|
151
|
-
return {
|
|
152
|
-
socket: null,
|
|
153
|
-
token,
|
|
154
|
-
tabKey: extra.tabKey ?? null,
|
|
155
|
-
resumeKey: extra.resumeKey ?? null,
|
|
156
|
-
resumeTabKey: extra.resumeTabKey ?? extra.tabKey ?? null,
|
|
157
|
-
pairedPeer: null,
|
|
158
|
-
pendingPeer: null,
|
|
159
|
-
reservedAt: extra.reservedAt ?? null,
|
|
160
|
-
};
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
function dropTab(token, reason) {
|
|
164
|
-
const tab = tabsByToken.get(token);
|
|
165
|
-
if (!tab) return;
|
|
166
|
-
if (tab.socket) socketMeta.delete(tab.socket);
|
|
167
|
-
const peerState = tab.pairedPeer ? 'paired' : (tab.pendingPeer ? 'pending' : 'none');
|
|
168
|
-
log(`tab dropped token=${redactToken(token)} reason=${reason} peer=${peerState}`, 'warn');
|
|
169
|
-
if (tab.pairedPeer) {
|
|
170
|
-
sendJson(tab.pairedPeer, { type: PAIR_MSG.UNPAIRED, reason: 'tab_disconnected', detail: reason });
|
|
171
|
-
closePeer(tab.pairedPeer);
|
|
172
|
-
}
|
|
173
|
-
if (tab.pendingPeer) {
|
|
174
|
-
sendJson(tab.pendingPeer, { type: PAIR_MSG.ERROR, code: 'pair_cancelled', message: 'Tab disconnected' });
|
|
175
|
-
closePeer(tab.pendingPeer);
|
|
176
|
-
}
|
|
177
|
-
if (tab.tabKey) {
|
|
178
|
-
tabsByToken.set(token, emptyEntry(token, {
|
|
179
|
-
tabKey: tab.tabKey,
|
|
180
|
-
resumeKey: tab.resumeKey,
|
|
181
|
-
resumeTabKey: tab.resumeTabKey || tab.tabKey,
|
|
182
|
-
reservedAt: Date.now(),
|
|
183
|
-
}));
|
|
184
|
-
return;
|
|
185
|
-
}
|
|
186
|
-
tabsByToken.delete(token);
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
function unpair(token, reason = 'disconnect') {
|
|
190
|
-
const tab = tabsByToken.get(token);
|
|
191
|
-
if (!tab || !tab.pairedPeer) return;
|
|
192
|
-
const peer = tab.pairedPeer;
|
|
193
|
-
tab.pairedPeer = null;
|
|
194
|
-
log(`pairing ended token=${redactToken(token)} reason=${reason}`, 'warn');
|
|
195
|
-
sendJson(tab.socket, { type: PAIR_MSG.UNPAIRED, reason });
|
|
196
|
-
sendJson(peer, { type: PAIR_MSG.UNPAIRED, reason });
|
|
197
|
-
closePeer(peer);
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
/**
|
|
201
|
-
* @param {RelaySocket} socket
|
|
202
|
-
*/
|
|
203
|
-
function attachSocket(socket) {
|
|
204
|
-
const remote = socket.remoteAddress || '';
|
|
205
|
-
if (!isLoopbackAddress(remote)) {
|
|
206
|
-
refuse(socket, 'remote_blocked', 'Agent bridge relay accepts loopback connections only');
|
|
207
|
-
return;
|
|
208
|
-
}
|
|
209
|
-
if (!isAllowedHttpOrigin(socket.origin)) {
|
|
210
|
-
refuse(socket, 'origin_blocked', 'Origin is not an allowed SurfCAD page (https://surfcad.com or local dev)');
|
|
211
|
-
return;
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
const live = { alive: true, dropReason: null };
|
|
215
|
-
if (typeof socket.ping === 'function') liveness.set(socket, live);
|
|
216
|
-
socket.on('pong', () => { live.alive = true; });
|
|
217
|
-
|
|
218
|
-
socket.on('message', (raw) => {
|
|
219
|
-
live.alive = true;
|
|
220
|
-
const rawText = typeof raw === 'string' ? raw : String(raw);
|
|
221
|
-
const msg = parseMessage(rawText);
|
|
222
|
-
if (!msg || typeof msg !== 'object') {
|
|
223
|
-
refuse(socket, 'bad_message', 'Expected JSON object');
|
|
224
|
-
return;
|
|
225
|
-
}
|
|
226
|
-
const meta = socketMeta.get(socket);
|
|
227
|
-
|
|
228
|
-
if (msg.type === PAIR_MSG.REGISTER_TAB) {
|
|
229
|
-
if (meta) {
|
|
230
|
-
refuse(socket, 'already_registered', 'Socket already registered');
|
|
231
|
-
return;
|
|
232
|
-
}
|
|
233
|
-
const token = typeof msg.token === 'string' ? msg.token.trim().toUpperCase() : '';
|
|
234
|
-
if (!token || token.length < 4) {
|
|
235
|
-
refuse(socket, 'bad_token', 'register_tab requires token');
|
|
236
|
-
return;
|
|
237
|
-
}
|
|
238
|
-
const tabKey = secretOrNull(msg.tabKey);
|
|
239
|
-
const existing = liveTab(token);
|
|
240
|
-
if (existing) {
|
|
241
|
-
// A reconnecting tab can beat the heartbeat to its own stale socket;
|
|
242
|
-
// only the tab that registered the code knows its tabKey. After a
|
|
243
|
-
// drop the entry is a reservation (socket null) for that same key.
|
|
244
|
-
if (!tabKey || existing.tabKey !== tabKey) {
|
|
245
|
-
refuse(socket, 'token_in_use', 'Another tab is already advertising this pairing code');
|
|
246
|
-
return;
|
|
247
|
-
}
|
|
248
|
-
const stale = existing.socket;
|
|
249
|
-
// Closing the bridge window is a user action: the tab sends
|
|
250
|
-
// forgetResume so the same MCP client cannot silent-resume.
|
|
251
|
-
const forgetResume = msg.forgetResume === true;
|
|
252
|
-
const kept = {
|
|
253
|
-
tabKey: existing.tabKey,
|
|
254
|
-
resumeKey: forgetResume ? null : existing.resumeKey,
|
|
255
|
-
resumeTabKey: existing.resumeTabKey || existing.tabKey,
|
|
256
|
-
};
|
|
257
|
-
if (stale && stale !== socket) {
|
|
258
|
-
dropTab(token, 'replaced_by_reconnect');
|
|
259
|
-
liveness.delete(stale);
|
|
260
|
-
try { (stale.terminate || stale.close).call(stale); } catch { /* gone */ }
|
|
261
|
-
}
|
|
262
|
-
tabsByToken.set(token, { ...emptyEntry(token, kept), socket });
|
|
263
|
-
socketMeta.set(socket, { role: 'tab', token });
|
|
264
|
-
log(`tab registered token=${redactToken(token)} (reconnect)`);
|
|
265
|
-
return;
|
|
266
|
-
}
|
|
267
|
-
tabsByToken.set(token, { ...emptyEntry(token, { tabKey }), socket });
|
|
268
|
-
socketMeta.set(socket, { role: 'tab', token });
|
|
269
|
-
log(`tab registered token=${redactToken(token)}`);
|
|
270
|
-
return;
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
if (msg.type === PAIR_MSG.PAIR) {
|
|
274
|
-
if (meta) {
|
|
275
|
-
refuse(socket, 'already_registered', 'Socket already registered');
|
|
276
|
-
return;
|
|
277
|
-
}
|
|
278
|
-
const token = typeof msg.token === 'string' ? msg.token.trim().toUpperCase() : '';
|
|
279
|
-
const tab = liveTab(token);
|
|
280
|
-
if (!tab || !tab.socket) {
|
|
281
|
-
refuse(socket, 'unknown_token', 'No SurfCAD tab is advertising this pairing code');
|
|
282
|
-
return;
|
|
283
|
-
}
|
|
284
|
-
if (tab.pairedPeer) {
|
|
285
|
-
refuse(socket, 'already_paired', 'Tab is already paired with another client');
|
|
286
|
-
return;
|
|
287
|
-
}
|
|
288
|
-
if (tab.pendingPeer && tab.pendingPeer !== socket) {
|
|
289
|
-
refuse(socket, 'pair_pending', 'Tab is already reviewing another pairing request');
|
|
290
|
-
return;
|
|
291
|
-
}
|
|
292
|
-
const offered = secretOrNull(msg.resume);
|
|
293
|
-
const silentResume = Boolean(
|
|
294
|
-
offered
|
|
295
|
-
&& tab.resumeKey
|
|
296
|
-
&& offered === tab.resumeKey
|
|
297
|
-
&& tab.tabKey
|
|
298
|
-
&& tab.resumeTabKey
|
|
299
|
-
&& tab.tabKey === tab.resumeTabKey,
|
|
300
|
-
);
|
|
301
|
-
socketMeta.set(socket, { role: 'peer', token });
|
|
302
|
-
if (silentResume) {
|
|
303
|
-
tab.pendingPeer = null;
|
|
304
|
-
tab.pairedPeer = socket;
|
|
305
|
-
sendJson(tab.socket, { type: PAIR_MSG.PAIRED, token, resume: true });
|
|
306
|
-
sendJson(socket, { type: PAIR_MSG.PAIRED, token, resumeKey: tab.resumeKey });
|
|
307
|
-
log(`paired token=${redactToken(token)} (resume)`);
|
|
308
|
-
return;
|
|
309
|
-
}
|
|
310
|
-
tab.pendingPeer = socket;
|
|
311
|
-
sendJson(tab.socket, { type: PAIR_MSG.PAIR_REQUEST, token });
|
|
312
|
-
log(`pair request token=${redactToken(token)}`);
|
|
313
|
-
return;
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
if (!meta) {
|
|
317
|
-
refuse(socket, 'not_registered', 'Send register_tab or pair first');
|
|
318
|
-
return;
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
const tab = liveTab(meta.token);
|
|
322
|
-
if (!tab) {
|
|
323
|
-
refuse(socket, 'session_gone', 'Pairing session ended');
|
|
324
|
-
return;
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
if (msg.type === PAIR_MSG.PAIR_APPROVE) {
|
|
328
|
-
if (meta.role !== 'tab') {
|
|
329
|
-
refuse(socket, 'forbidden', 'Only the tab may approve pairing');
|
|
330
|
-
return;
|
|
331
|
-
}
|
|
332
|
-
const peer = tab.pendingPeer;
|
|
333
|
-
if (!peer) {
|
|
334
|
-
sendJson(socket, { type: PAIR_MSG.ERROR, code: 'no_request', message: 'No pairing request to approve' });
|
|
335
|
-
return;
|
|
336
|
-
}
|
|
337
|
-
const resumeKey = secretOrNull(msg.resumeKey);
|
|
338
|
-
tab.pendingPeer = null;
|
|
339
|
-
tab.pairedPeer = peer;
|
|
340
|
-
tab.resumeKey = resumeKey;
|
|
341
|
-
tab.resumeTabKey = tab.tabKey;
|
|
342
|
-
sendJson(socket, { type: PAIR_MSG.PAIRED, token: meta.token });
|
|
343
|
-
sendJson(peer, resumeKey
|
|
344
|
-
? { type: PAIR_MSG.PAIRED, token: meta.token, resumeKey }
|
|
345
|
-
: { type: PAIR_MSG.PAIRED, token: meta.token });
|
|
346
|
-
log(`paired token=${redactToken(meta.token)}`);
|
|
347
|
-
return;
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
if (msg.type === PAIR_MSG.PAIR_REJECT) {
|
|
351
|
-
if (meta.role !== 'tab') {
|
|
352
|
-
refuse(socket, 'forbidden', 'Only the tab may reject pairing');
|
|
353
|
-
return;
|
|
354
|
-
}
|
|
355
|
-
const peer = tab.pendingPeer;
|
|
356
|
-
tab.pendingPeer = null;
|
|
357
|
-
if (peer) {
|
|
358
|
-
sendJson(peer, { type: PAIR_MSG.ERROR, code: 'pair_rejected', message: 'Pairing rejected in SurfCAD' });
|
|
359
|
-
closePeer(peer);
|
|
360
|
-
}
|
|
361
|
-
return;
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
if (msg.type === PAIR_MSG.AGENT_PROMPT || msg.type === PAIR_MSG.AGENT_PROMPT_CANCEL
|
|
365
|
-
|| msg.type === PAIR_MSG.AGENT_PROMPT_ACK || msg.type === PAIR_MSG.AGENT_PROMPT_CANCEL_RESULT
|
|
366
|
-
|| msg.type === PAIR_MSG.AGENT_REPLY || msg.type === PAIR_MSG.AGENT_MESSAGE
|
|
367
|
-
|| msg.type === PAIR_MSG.AGENT_STATUS
|
|
368
|
-
|| msg.type === PAIR_MSG.AGENT_ACTIVITY
|
|
369
|
-
|| msg.type === PAIR_MSG.AGENT_PROGRESS
|
|
370
|
-
|| msg.type === PAIR_MSG.AGENT_CLOSE_SESSION) {
|
|
371
|
-
if (msg.type === PAIR_MSG.AGENT_PROMPT || msg.type === PAIR_MSG.AGENT_PROMPT_CANCEL) {
|
|
372
|
-
if (meta.role !== 'tab') {
|
|
373
|
-
sendJson(socket, {
|
|
374
|
-
type: PAIR_MSG.ERROR,
|
|
375
|
-
code: 'forbidden',
|
|
376
|
-
message: msg.type === PAIR_MSG.AGENT_PROMPT_CANCEL
|
|
377
|
-
? 'Only the paired tab cancels prompts'
|
|
378
|
-
: 'Only the paired tab sends prompts',
|
|
379
|
-
});
|
|
380
|
-
return;
|
|
381
|
-
}
|
|
382
|
-
const promptId = typeof msg.id === 'string' ? msg.id : undefined;
|
|
383
|
-
if (msg.type === PAIR_MSG.AGENT_PROMPT && rawText.length > maxPromptFrameChars) {
|
|
384
|
-
sendJson(socket, {
|
|
385
|
-
type: PAIR_MSG.AGENT_PROMPT_ACK,
|
|
386
|
-
id: promptId,
|
|
387
|
-
delivery: 'failed',
|
|
388
|
-
error: 'screenshot_too_large',
|
|
389
|
-
});
|
|
390
|
-
return;
|
|
391
|
-
}
|
|
392
|
-
if (tab.pairedPeer == null) {
|
|
393
|
-
if (msg.type === PAIR_MSG.AGENT_PROMPT_CANCEL) {
|
|
394
|
-
sendJson(socket, {
|
|
395
|
-
type: PAIR_MSG.AGENT_PROMPT_CANCEL_RESULT,
|
|
396
|
-
v: 1,
|
|
397
|
-
id: promptId || '',
|
|
398
|
-
state: 'not_found',
|
|
399
|
-
});
|
|
400
|
-
return;
|
|
401
|
-
}
|
|
402
|
-
sendJson(socket, {
|
|
403
|
-
type: PAIR_MSG.AGENT_PROMPT_ACK,
|
|
404
|
-
id: promptId,
|
|
405
|
-
delivery: 'failed',
|
|
406
|
-
error: 'not_paired',
|
|
407
|
-
});
|
|
408
|
-
return;
|
|
409
|
-
}
|
|
410
|
-
sendJson(tab.pairedPeer, msg);
|
|
411
|
-
return;
|
|
412
|
-
}
|
|
413
|
-
if (meta.role !== 'peer' || tab.pairedPeer !== socket || tab.socket == null) {
|
|
414
|
-
const wrongRole = meta.role !== 'peer';
|
|
415
|
-
sendJson(socket, {
|
|
416
|
-
type: PAIR_MSG.ERROR,
|
|
417
|
-
code: wrongRole ? 'forbidden' : 'not_paired',
|
|
418
|
-
message: wrongRole
|
|
419
|
-
? 'Only the paired agent sends replies, status, and cancel results'
|
|
420
|
-
: 'Pair before sending agent messages',
|
|
421
|
-
});
|
|
422
|
-
return;
|
|
423
|
-
}
|
|
424
|
-
sendJson(tab.socket, msg);
|
|
425
|
-
return;
|
|
426
|
-
}
|
|
427
|
-
|
|
428
|
-
if (typeof msg.command === 'string' && msg.type !== PAIR_MSG.PAIR) {
|
|
429
|
-
if (meta.role !== 'peer' || tab.pairedPeer !== socket) {
|
|
430
|
-
refuse(socket, 'not_paired', 'Pair before sending bridge commands');
|
|
431
|
-
return;
|
|
432
|
-
}
|
|
433
|
-
if (msg.v != null && msg.v !== AGENT_PROTOCOL_VERSION) {
|
|
434
|
-
sendJson(socket, commandResponse({
|
|
435
|
-
id: msg.id,
|
|
436
|
-
ok: false,
|
|
437
|
-
error: { code: 'bad_call', message: `Unsupported protocol version: ${msg.v}` },
|
|
438
|
-
}));
|
|
439
|
-
return;
|
|
440
|
-
}
|
|
441
|
-
if (typeof msg.id !== 'string' && typeof msg.id !== 'number') {
|
|
442
|
-
sendJson(socket, commandResponse({
|
|
443
|
-
id: msg.id,
|
|
444
|
-
ok: false,
|
|
445
|
-
error: { code: 'bad_call', message: 'call requires id' },
|
|
446
|
-
}));
|
|
447
|
-
return;
|
|
448
|
-
}
|
|
449
|
-
sendJson(tab.socket, commandRequest({
|
|
450
|
-
id: msg.id,
|
|
451
|
-
command: msg.command,
|
|
452
|
-
args: msg.args == null ? {} : msg.args,
|
|
453
|
-
}));
|
|
454
|
-
return;
|
|
455
|
-
}
|
|
456
|
-
|
|
457
|
-
if (Object.prototype.hasOwnProperty.call(msg, 'ok') && msg.type !== PAIR_MSG.PAIR) {
|
|
458
|
-
if (meta.role !== 'tab' || tab.pairedPeer == null) {
|
|
459
|
-
refuse(socket, 'not_paired', 'No paired peer for response');
|
|
460
|
-
return;
|
|
461
|
-
}
|
|
462
|
-
if (msg.v != null && msg.v !== AGENT_PROTOCOL_VERSION) {
|
|
463
|
-
sendJson(tab.pairedPeer, commandResponse({
|
|
464
|
-
id: msg.id,
|
|
465
|
-
ok: false,
|
|
466
|
-
error: { code: 'bad_call', message: `Unsupported protocol version: ${msg.v}` },
|
|
467
|
-
}));
|
|
468
|
-
return;
|
|
469
|
-
}
|
|
470
|
-
const response = readCommandResponse(msg);
|
|
471
|
-
sendJson(tab.pairedPeer, commandResponse({
|
|
472
|
-
id: response?.id ?? msg.id,
|
|
473
|
-
ok: response?.ok === true,
|
|
474
|
-
result: response?.ok === true ? response.result : undefined,
|
|
475
|
-
error: response?.ok === true ? undefined : response?.error,
|
|
476
|
-
}));
|
|
477
|
-
return;
|
|
478
|
-
}
|
|
479
|
-
|
|
480
|
-
refuse(socket, 'unknown_type', `Unknown message type: ${msg.type}`);
|
|
481
|
-
});
|
|
482
|
-
|
|
483
|
-
socket.on('close', (code, reason) => {
|
|
484
|
-
liveness.delete(socket);
|
|
485
|
-
const m = socketMeta.get(socket);
|
|
486
|
-
if (!m) return;
|
|
487
|
-
const why = live.dropReason || closeReason(code, reason);
|
|
488
|
-
const tabEntry = tabsByToken.get(m.token);
|
|
489
|
-
if (!tabEntry) {
|
|
490
|
-
socketMeta.delete(socket);
|
|
491
|
-
return;
|
|
492
|
-
}
|
|
493
|
-
if (m.role === 'tab') {
|
|
494
|
-
if (tabEntry.socket === socket) dropTab(m.token, why);
|
|
495
|
-
else socketMeta.delete(socket);
|
|
496
|
-
return;
|
|
497
|
-
}
|
|
498
|
-
if (tabEntry.pendingPeer === socket) {
|
|
499
|
-
tabEntry.pendingPeer = null;
|
|
500
|
-
socketMeta.delete(socket);
|
|
501
|
-
return;
|
|
502
|
-
}
|
|
503
|
-
if (tabEntry.pairedPeer === socket) {
|
|
504
|
-
unpair(m.token, live.dropReason ? `peer_${live.dropReason}` : 'peer_disconnected');
|
|
505
|
-
}
|
|
506
|
-
socketMeta.delete(socket);
|
|
507
|
-
});
|
|
508
|
-
}
|
|
509
|
-
|
|
510
|
-
/**
|
|
511
|
-
* One heartbeat sweep: terminate sockets that did not answer the previous
|
|
512
|
-
* ping, then ping the rest. Call every `heartbeatMs`.
|
|
513
|
-
*/
|
|
514
|
-
function heartbeat() {
|
|
515
|
-
for (const [socket, live] of liveness) {
|
|
516
|
-
if (!live.alive) {
|
|
517
|
-
live.dropReason = 'heartbeat_timeout';
|
|
518
|
-
liveness.delete(socket);
|
|
519
|
-
try { (socket.terminate || socket.close).call(socket); } catch { /* gone */ }
|
|
520
|
-
continue;
|
|
521
|
-
}
|
|
522
|
-
live.alive = false;
|
|
523
|
-
try { socket.ping?.(); } catch { /* gone; next sweep terminates */ }
|
|
524
|
-
}
|
|
525
|
-
}
|
|
526
|
-
|
|
527
|
-
function disconnectToken(token) {
|
|
528
|
-
const tab = liveTab(token);
|
|
529
|
-
if (!tab) return;
|
|
530
|
-
unpair(token, 'tab_disconnect');
|
|
531
|
-
try { tab.socket.close(); } catch { /* gone */ }
|
|
532
|
-
dropTab(token, 'disconnect_requested');
|
|
533
|
-
}
|
|
534
|
-
|
|
535
|
-
function dispose() {
|
|
536
|
-
if (sweepTimer) clearInterval(sweepTimer);
|
|
537
|
-
}
|
|
538
|
-
|
|
539
|
-
return {
|
|
540
|
-
attachSocket,
|
|
541
|
-
disconnectToken,
|
|
542
|
-
heartbeat,
|
|
543
|
-
dispose,
|
|
544
|
-
/** @param {string} token */
|
|
545
|
-
hasTab(token) {
|
|
546
|
-
return liveTab(token) != null;
|
|
547
|
-
},
|
|
548
|
-
/** @param {string} token */
|
|
549
|
-
isPaired(token) {
|
|
550
|
-
return liveTab(token)?.pairedPeer != null;
|
|
551
|
-
},
|
|
552
|
-
PAIR_MSG,
|
|
553
|
-
};
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
export { PAIR_MSG };
|