surfcad-mcp 0.3.8 → 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.
Files changed (43) hide show
  1. package/README.md +102 -49
  2. package/bin/surfcad-mcp.js +4 -3
  3. package/data/commands.json +6481 -5817
  4. package/data/helpers.json +243 -268
  5. package/package.json +2 -2
  6. package/src/cli.mjs +234 -24
  7. package/src/cliCall.mjs +221 -0
  8. package/src/errors.mjs +8 -5
  9. package/src/helpers.mjs +7 -5
  10. package/src/importFile.mjs +186 -0
  11. package/src/listen/bootstrap.mjs +285 -0
  12. package/src/listen/claudeCodeWake.mjs +74 -0
  13. package/src/listen/daemon.mjs +40 -0
  14. package/src/listen/listenCli.mjs +157 -27
  15. package/src/listen/listener.mjs +138 -8
  16. package/src/listen/owner.mjs +293 -0
  17. package/src/listen/waitCli.mjs +133 -0
  18. package/src/listen/wake.mjs +42 -8
  19. package/src/listen/wakeConfig.mjs +17 -2
  20. package/src/listen/wakeSetupText.mjs +53 -14
  21. package/src/pairWait.mjs +3 -3
  22. package/src/pairingCode.mjs +10 -0
  23. package/src/prompt/buildGuidance.mjs +9 -7
  24. package/src/prompt/chatFlow.mjs +15 -0
  25. package/src/prompt/errorHints.mjs +24 -10
  26. package/src/prompt/guide.mjs +31 -18
  27. package/src/prompt/promptSession.mjs +74 -10
  28. package/src/prompt/promptTools.mjs +10 -15
  29. package/src/prompt/replyConfirm.mjs +69 -0
  30. package/src/relayMessages.mjs +43 -1
  31. package/src/remote/config.mjs +17 -13
  32. package/src/remote/session.mjs +103 -5
  33. package/src/remote/tokenStore.mjs +20 -0
  34. package/src/room/seat.mjs +334 -0
  35. package/src/screenshotFile.mjs +9 -0
  36. package/src/server.mjs +241 -119
  37. package/src/stepUploadLimit.mjs +8 -0
  38. package/src/bridge/bridgePage.mjs +0 -132
  39. package/src/bridge/bridgePopup.mjs +0 -288
  40. package/src/bridge/relayHub.mjs +0 -556
  41. package/src/bridge/relayServer.mjs +0 -291
  42. package/src/nodeClient.mjs +0 -63
  43. package/src/relay.mjs +0 -419
@@ -1,291 +0,0 @@
1
- /**
2
- * Loopback HTTP/WebSocket server for the M1 agent-bridge relay.
3
- * Binds 127.0.0.1 only. Handles CORS / Private Network Access preflight for
4
- * https://surfcad.com → ws://127.0.0.1 upgrades, and serves the `/bridge`
5
- * popup page for browsers that block that upgrade (Safari).
6
- */
7
-
8
- import { createServer } from 'node:http';
9
- import { WebSocket, WebSocketServer } from 'ws';
10
- import { createAgentBridgeRelayHub } from './relayHub.mjs';
11
- import { extraAllowedOrigins, isAllowedHttpOrigin, isLoopbackAddress } from './localAddress.mjs';
12
- import { handleBridgeRequest } from './bridgePage.mjs';
13
- import { loadCommandsCatalog, toolsCatalogPayload } from '../catalog.mjs';
14
-
15
- export const DEFAULT_RELAY_PORT = 17341;
16
-
17
- function parsePort(value) {
18
- const n = Number(value);
19
- return Number.isInteger(n) && n > 0 && n < 65536 ? n : DEFAULT_RELAY_PORT;
20
- }
21
-
22
- /**
23
- * @param {string | undefined} origin
24
- * @returns {Record<string, string>}
25
- */
26
- function corsHeadersForOrigin(origin) {
27
- if (!origin || !isAllowedHttpOrigin(origin)) return {};
28
- return {
29
- 'Access-Control-Allow-Origin': origin,
30
- 'Access-Control-Allow-Private-Network': 'true',
31
- 'Vary': 'Origin',
32
- };
33
- }
34
-
35
- /**
36
- * @param {string} url
37
- * @param {number} [timeoutMs]
38
- */
39
- export function probeRelayAtUrl(url, timeoutMs = 1500) {
40
- return new Promise((resolve) => {
41
- let settled = false;
42
- const finish = (ok) => {
43
- if (settled) return;
44
- settled = true;
45
- resolve(ok);
46
- };
47
- let ws;
48
- try {
49
- ws = new WebSocket(url);
50
- } catch {
51
- finish(false);
52
- return;
53
- }
54
- const timer = setTimeout(() => {
55
- try { ws.close(); } catch { /* noop */ }
56
- finish(false);
57
- }, timeoutMs);
58
- if (typeof timer.unref === 'function') timer.unref();
59
- ws.once('open', () => {
60
- clearTimeout(timer);
61
- try { ws.close(); } catch { /* noop */ }
62
- finish(true);
63
- });
64
- ws.once('error', () => {
65
- clearTimeout(timer);
66
- finish(false);
67
- });
68
- });
69
- }
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
-
78
- /**
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]
98
- */
99
- export function startAgentBridgeRelay(options = {}) {
100
- const host = options.host || '127.0.0.1';
101
- const port = options.port ?? parsePort(process.env.SURFCAD_AGENT_BRIDGE_WS_PORT);
102
- const heartbeatMs = options.heartbeatMs ?? parseHeartbeatMs(process.env.SURFCAD_AGENT_BRIDGE_HEARTBEAT_MS);
103
- const hub = createAgentBridgeRelayHub({ onLog: options.onLog || defaultRelayLog });
104
-
105
- const server = createServer((req, res) => {
106
- const origin = req.headers.origin;
107
- const cors = corsHeadersForOrigin(origin);
108
-
109
- if (req.method === 'OPTIONS') {
110
- if (!origin || !isAllowedHttpOrigin(origin)) {
111
- res.writeHead(403);
112
- res.end();
113
- return;
114
- }
115
- res.writeHead(204, {
116
- ...cors,
117
- 'Access-Control-Allow-Methods': 'GET, OPTIONS',
118
- 'Access-Control-Allow-Headers': 'Content-Type, Authorization, Sec-WebSocket-Protocol, Sec-WebSocket-Extensions',
119
- 'Access-Control-Max-Age': '86400',
120
- });
121
- res.end();
122
- return;
123
- }
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
-
149
- res.writeHead(404, cors);
150
- res.end();
151
- });
152
-
153
- const wss = new WebSocketServer({ noServer: true });
154
-
155
- wss.on('headers', (headers, req) => {
156
- const origin = req.headers.origin;
157
- const cors = corsHeadersForOrigin(origin);
158
- for (const [key, value] of Object.entries(cors)) {
159
- headers.push(`${key}: ${value}`);
160
- }
161
- });
162
-
163
- server.on('upgrade', (req, socket, head) => {
164
- const remote = req.socket.remoteAddress || '';
165
- if (!isLoopbackAddress(remote)) {
166
- socket.destroy();
167
- return;
168
- }
169
- const origin = req.headers.origin;
170
- if (origin && !isAllowedHttpOrigin(origin)) {
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
- });
177
- return;
178
- }
179
- wss.handleUpgrade(req, socket, head, (ws) => {
180
- wss.emit('connection', ws, req);
181
- hub.attachSocket({
182
- send: (data) => { ws.send(data); },
183
- close: () => { ws.close(); },
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
- },
193
- remoteAddress: remote,
194
- origin,
195
- });
196
- });
197
- });
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
-
204
- return new Promise((resolve, reject) => {
205
- server.listen(port, host, () => {
206
- const bound = server.address();
207
- const actualPort = bound && typeof bound === 'object' ? bound.port : port;
208
- const url = `ws://${host}:${actualPort}`;
209
- options.onReady?.(url);
210
- resolve({ server, wss, hub, url, port: actualPort, host, ownsServer: true });
211
- });
212
- server.on('error', reject);
213
- });
214
- }
215
-
216
- /** @type {Map<number, Promise<unknown>>} */
217
- const sharedRelayByPort = new Map();
218
-
219
- /**
220
- * Start the relay or attach to one already listening on the default loopback port.
221
- *
222
- * @param {{ port?: number, onReady?: (url: string) => void }} [options]
223
- */
224
- export async function ensureAgentBridgeRelay(options = {}) {
225
- const host = '127.0.0.1';
226
- const port = options.port ?? parsePort(process.env.SURFCAD_AGENT_BRIDGE_WS_PORT);
227
- const url = `ws://${host}:${port}`;
228
-
229
- const existing = sharedRelayByPort.get(port);
230
- if (existing) {
231
- return existing;
232
- }
233
-
234
- const promise = (async () => {
235
- try {
236
- const started = await startAgentBridgeRelay({ ...options, host, port });
237
- return started;
238
- } catch (err) {
239
- if (err && typeof err === 'object' && err.code === 'EADDRINUSE') {
240
- const alive = await probeRelayAtUrl(url);
241
- if (alive) {
242
- options.onReady?.(url);
243
- return { url, server: null, wss: null, hub: null, port, host, ownsServer: false, reused: true };
244
- }
245
- }
246
- sharedRelayByPort.delete(port);
247
- throw err;
248
- }
249
- })();
250
-
251
- sharedRelayByPort.set(port, promise);
252
- return promise;
253
- }
254
-
255
- /**
256
- * Close relay HTTP/WebSocket listeners started by {@link startAgentBridgeRelay}.
257
- *
258
- * @param {{ server?: import('node:http').Server | null, wss?: import('ws').WebSocketServer | null, port?: number, ownsServer?: boolean } | null | undefined} relay
259
- */
260
- export function stopAgentBridgeRelay(relay) {
261
- relay?.hub?.dispose?.();
262
- if (!relay || !relay.ownsServer) {
263
- return Promise.resolve();
264
- }
265
- return new Promise((resolve) => {
266
- const finish = () => resolve();
267
- const wss = relay.wss;
268
- const server = relay.server;
269
- if (wss) {
270
- for (const client of wss.clients) {
271
- try { client.terminate(); } catch { /* gone */ }
272
- }
273
- wss.close(() => {
274
- if (server) server.close(finish);
275
- else finish();
276
- });
277
- return;
278
- }
279
- if (server) server.close(finish);
280
- else finish();
281
- });
282
- }
283
-
284
- /** @param {number} [port] */
285
- export function resetAgentBridgeRelayCache(port) {
286
- if (port == null) {
287
- sharedRelayByPort.clear();
288
- return;
289
- }
290
- sharedRelayByPort.delete(port);
291
- }
@@ -1,63 +0,0 @@
1
- /**
2
- * Node WebSocket client for the M1 agent-bridge relay.
3
- */
4
- import { WebSocket } from 'ws';
5
- import { PAIR_MSG } from './relayMessages.mjs';
6
-
7
- /**
8
- * Resolves once the tab approves. `resume` is the key the tab handed out on
9
- * the previous approval; the hub matches it for that tabKey and auto-pairs
10
- * without putting the secret on PAIR_REQUEST.
11
- *
12
- * @param {string} url
13
- * @param {string} token
14
- * @param {{ resume?: string | null }} [options]
15
- * @returns {Promise<{ ws: WebSocket, resumeKey: string | null }>}
16
- */
17
- export function connectPeer(url, token, options = {}) {
18
- return new Promise((resolve, reject) => {
19
- const ws = new WebSocket(url);
20
- let settled = false;
21
- const fail = (err) => {
22
- if (settled) return;
23
- settled = true;
24
- ws.removeAllListeners('message');
25
- try { ws.close(); } catch { /* noop */ }
26
- reject(err instanceof Error ? err : new Error(String(err)));
27
- };
28
- ws.once('open', () => {
29
- const pair = { type: PAIR_MSG.PAIR, token: token.trim().toUpperCase() };
30
- if (options.resume) pair.resume = options.resume;
31
- ws.send(JSON.stringify(pair));
32
- });
33
- ws.on('message', (raw) => {
34
- let msg;
35
- try {
36
- msg = JSON.parse(String(raw));
37
- } catch {
38
- fail(new Error('Invalid JSON from relay'));
39
- return;
40
- }
41
- if (msg?.type === PAIR_MSG.PAIRED) {
42
- settled = true;
43
- ws.removeAllListeners('message');
44
- ws.removeAllListeners('close');
45
- resolve({ ws, resumeKey: typeof msg.resumeKey === 'string' ? msg.resumeKey : null });
46
- return;
47
- }
48
- if (msg?.type === PAIR_MSG.ERROR || (msg?.code && !msg?.id)) {
49
- fail(Object.assign(new Error(msg.message || msg.code || 'Pairing failed'), {
50
- code: typeof msg.code === 'string' ? msg.code : 'pair_failed',
51
- }));
52
- }
53
- });
54
- ws.once('error', (err) => {
55
- fail(Object.assign(err instanceof Error ? err : new Error(String(err)), {
56
- code: err?.code === 'ECONNREFUSED' ? 'relay_unreachable' : (err?.code || 'relay_error'),
57
- }));
58
- });
59
- ws.once('close', () => {
60
- fail(Object.assign(new Error('Relay closed the connection before pairing finished'), { code: 'pair_cancelled' }));
61
- });
62
- });
63
- }