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.
Files changed (41) hide show
  1. package/README.md +70 -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 +221 -23
  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 +87 -34
  12. package/src/listen/claudeCodeWake.mjs +74 -0
  13. package/src/listen/daemon.mjs +35 -0
  14. package/src/listen/listenCli.mjs +121 -30
  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 +39 -19
  19. package/src/listen/wakeSetupText.mjs +23 -5
  20. package/src/pairWait.mjs +3 -3
  21. package/src/pairingCode.mjs +10 -0
  22. package/src/prompt/buildGuidance.mjs +9 -7
  23. package/src/prompt/chatFlow.mjs +15 -0
  24. package/src/prompt/errorHints.mjs +24 -10
  25. package/src/prompt/guide.mjs +27 -14
  26. package/src/prompt/promptSession.mjs +74 -10
  27. package/src/prompt/promptTools.mjs +10 -6
  28. package/src/prompt/replyConfirm.mjs +69 -0
  29. package/src/relayMessages.mjs +43 -1
  30. package/src/remote/config.mjs +17 -13
  31. package/src/remote/session.mjs +103 -5
  32. package/src/room/seat.mjs +334 -0
  33. package/src/screenshotFile.mjs +9 -0
  34. package/src/server.mjs +155 -111
  35. package/src/stepUploadLimit.mjs +8 -0
  36. package/src/bridge/bridgePage.mjs +0 -132
  37. package/src/bridge/bridgePopup.mjs +0 -288
  38. package/src/bridge/relayHub.mjs +0 -556
  39. package/src/bridge/relayServer.mjs +0 -291
  40. package/src/nodeClient.mjs +0 -63
  41. package/src/relay.mjs +0 -419
@@ -0,0 +1,334 @@
1
+ /**
2
+ * A seat in a SurfCAD room for an agent with no browser.
3
+ *
4
+ * `room join` asks the room for a seat, prints a short code, and waits
5
+ * for the room's host to approve it in SurfCAD. The agent proves it is the
6
+ * one that asked with a secret it made: the request carries the secret's
7
+ * hash, the poll carries the secret. On approval the server answers once
8
+ * with a seat token for that one room. It is saved in the config dir
9
+ * (mode 0600) and is never printed or logged.
10
+ */
11
+
12
+ import { createHash, randomBytes } from 'node:crypto';
13
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
14
+ import { hostname } from 'node:os';
15
+ import { join } from 'node:path';
16
+ import { configDir, normalizeServer } from '../remote/config.mjs';
17
+
18
+ /** What the server allows in a label; a longer one is cut there. */
19
+ const LABEL_MAX = 60;
20
+ const MACHINE_MAX = 40;
21
+ const ROOM_KEY_MAX = 400;
22
+
23
+ /**
24
+ * @param {NodeJS.ProcessEnv} [env]
25
+ */
26
+ export function roomSeatPath(env = process.env) {
27
+ return join(configDir(env), 'room-seat.json');
28
+ }
29
+
30
+ /**
31
+ * A room's key, `owner/name:branch:assemblyId`, or '' when the text is
32
+ * not one. The repository is lower case, as the room server keys it.
33
+ * @param {unknown} value
34
+ */
35
+ export function normalizeRoomKey(value) {
36
+ const key = typeof value === 'string' ? value.trim() : '';
37
+ if (!key || key.length > ROOM_KEY_MAX) return '';
38
+ for (let i = 0; i < key.length; i += 1) {
39
+ if (key.charCodeAt(i) < 32) return '';
40
+ }
41
+ const first = key.indexOf(':');
42
+ const last = key.lastIndexOf(':');
43
+ if (first <= 0 || last <= first) return '';
44
+ const repo = key.slice(0, first);
45
+ const slash = repo.indexOf('/');
46
+ if (slash <= 0 || slash === repo.length - 1 || repo.indexOf('/', slash + 1) !== -1) return '';
47
+ if (!key.slice(first + 1, last) || !key.slice(last + 1) || repo !== repo.toLowerCase()) return '';
48
+ return key;
49
+ }
50
+
51
+ /**
52
+ * What `--room` names: the room link SurfCAD shows the host
53
+ * (`https://surfcad.com/?room=owner%2Fname%3Abranch%3AassemblyId`), or the
54
+ * room's key by itself. The link names the room and the server. It
55
+ * carries no access: only the host's approval gives a seat.
56
+ * @param {unknown} input
57
+ * @returns {{ room: string, server: string }} `server` is '' for a bare key
58
+ */
59
+ export function parseRoomLink(input) {
60
+ const text = typeof input === 'string' ? input.trim() : '';
61
+ const bad = () => Object.assign(
62
+ new Error('--room needs the room link from SurfCAD, or a room key (owner/name:branch:assemblyId).'),
63
+ { code: 'bad_room' },
64
+ );
65
+ if (!text) throw bad();
66
+ if (/^https?:\/\//i.test(text)) {
67
+ let url;
68
+ try {
69
+ url = new URL(text);
70
+ } catch {
71
+ throw bad();
72
+ }
73
+ const fromHash = new URLSearchParams(url.hash.replace(/^#/, '')).get('room');
74
+ const room = normalizeRoomKey(url.searchParams.get('room') || fromHash || '');
75
+ if (!room) throw bad();
76
+ return { room, server: normalizeServer(url.origin) };
77
+ }
78
+ const room = normalizeRoomKey(text);
79
+ if (!room) throw bad();
80
+ return { room, server: '' };
81
+ }
82
+
83
+ /**
84
+ * @param {string} origin http(s) origin, no path
85
+ */
86
+ export function roomSeatUrls(origin) {
87
+ const base = normalizeServer(origin);
88
+ const url = new URL(base);
89
+ return {
90
+ origin: base,
91
+ requestUrl: `${base}/api/rooms/agent-seats/request`,
92
+ tokenUrl: `${base}/api/rooms/agent-seats/token`,
93
+ wsUrl: `${url.protocol === 'https:' ? 'wss:' : 'ws:'}//${url.host}/room`,
94
+ };
95
+ }
96
+
97
+ /**
98
+ * @typedef {{
99
+ * token: string,
100
+ * server: string,
101
+ * room: string,
102
+ * label: string,
103
+ * machine: string,
104
+ * expiresAt: number,
105
+ * savedAt: string,
106
+ * }} SavedRoomSeat
107
+ */
108
+
109
+ /**
110
+ * @param {NodeJS.ProcessEnv} [env]
111
+ * @returns {Promise<SavedRoomSeat | null>}
112
+ */
113
+ export async function readRoomSeat(env = process.env) {
114
+ /** @type {string} */
115
+ let text;
116
+ try {
117
+ text = await readFile(roomSeatPath(env), 'utf8');
118
+ } catch (err) {
119
+ if (err && typeof err === 'object' && err.code === 'ENOENT') return null;
120
+ throw Object.assign(new Error('The saved room seat could not be read.'), { code: 'bad_seat_file' });
121
+ }
122
+ /** @type {unknown} */
123
+ let parsed;
124
+ try {
125
+ parsed = JSON.parse(text);
126
+ } catch {
127
+ throw Object.assign(new Error('The saved room seat could not be read.'), { code: 'bad_seat_file' });
128
+ }
129
+ if (!parsed || typeof parsed !== 'object') return null;
130
+ const record = /** @type {Record<string, unknown>} */ (parsed);
131
+ if (typeof record.token !== 'string' || !record.token || typeof record.room !== 'string' || !record.room) return null;
132
+ return {
133
+ token: record.token,
134
+ server: typeof record.server === 'string' ? record.server : '',
135
+ room: record.room,
136
+ label: typeof record.label === 'string' ? record.label : '',
137
+ machine: typeof record.machine === 'string' ? record.machine : '',
138
+ expiresAt: Number.isFinite(record.expiresAt) ? Number(record.expiresAt) : 0,
139
+ savedAt: typeof record.savedAt === 'string' ? record.savedAt : '',
140
+ };
141
+ }
142
+
143
+ /**
144
+ * @param {Omit<SavedRoomSeat, 'savedAt'> & { savedAt?: string }} record
145
+ * @param {NodeJS.ProcessEnv} [env]
146
+ * @returns {Promise<string>} path written
147
+ */
148
+ export async function saveRoomSeat(record, env = process.env) {
149
+ if (typeof record.token !== 'string' || !record.token) {
150
+ throw Object.assign(new Error('The server approved the seat but sent no token.'), { code: 'bad_seat' });
151
+ }
152
+ const dir = configDir(env);
153
+ await mkdir(dir, { recursive: true, mode: 0o700 });
154
+ await chmod(dir, 0o700);
155
+ const path = roomSeatPath(env);
156
+ const tmp = join(dir, `.room-seat-${process.pid}-${Date.now()}.tmp`);
157
+ const body = `${JSON.stringify({
158
+ token: record.token,
159
+ server: record.server,
160
+ room: record.room,
161
+ label: record.label || '',
162
+ machine: record.machine || '',
163
+ expiresAt: Number.isFinite(record.expiresAt) ? record.expiresAt : 0,
164
+ savedAt: record.savedAt || new Date().toISOString(),
165
+ })}\n`;
166
+ try {
167
+ await writeFile(tmp, body, { mode: 0o600, flag: 'wx' });
168
+ await chmod(tmp, 0o600);
169
+ await rename(tmp, path);
170
+ await chmod(path, 0o600);
171
+ } catch {
172
+ await rm(tmp, { force: true });
173
+ throw Object.assign(new Error('Could not save the room seat.'), { code: 'save_failed' });
174
+ }
175
+ return path;
176
+ }
177
+
178
+ /**
179
+ * @param {NodeJS.ProcessEnv} [env]
180
+ */
181
+ export async function forgetRoomSeat(env = process.env) {
182
+ await rm(roomSeatPath(env), { force: true });
183
+ }
184
+
185
+ /**
186
+ * What `room status` prints. Never the token.
187
+ * @param {SavedRoomSeat | null} saved
188
+ * @param {number} [now]
189
+ */
190
+ export function formatRoomSeatStatus(saved, now = Date.now()) {
191
+ if (!saved) return 'No room seat is saved on this machine. Run npx surfcad-mcp room join --room LINK.\n';
192
+ const left = saved.expiresAt - now;
193
+ const until = saved.expiresAt > 0
194
+ ? (left > 0 ? `good until ${new Date(saved.expiresAt).toISOString()} unless the host removes it` : 'run out')
195
+ : 'expiry unknown';
196
+ return [
197
+ `Room seat: ${saved.label || 'Agent'}${saved.machine ? ` on ${saved.machine}` : ''}`,
198
+ `Room: ${saved.room}`,
199
+ `Server: ${saved.server}`,
200
+ `Seat: ${until}`,
201
+ '',
202
+ ].join('\n');
203
+ }
204
+
205
+ /**
206
+ * @param {string} url
207
+ * @param {object} body
208
+ * @param {typeof fetch} fetchImpl
209
+ */
210
+ async function postJson(url, body, fetchImpl) {
211
+ /** @type {Response} */
212
+ let res;
213
+ try {
214
+ res = await fetchImpl(url, {
215
+ method: 'POST',
216
+ headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
217
+ body: JSON.stringify(body),
218
+ });
219
+ } catch {
220
+ throw Object.assign(new Error('Could not reach the SurfCAD server.'), { code: 'unreachable' });
221
+ }
222
+ /** @type {any} */
223
+ let json = null;
224
+ try {
225
+ json = await res.json();
226
+ } catch {
227
+ json = null;
228
+ }
229
+ return { status: res.status, json };
230
+ }
231
+
232
+ const AGAIN = 'Run npx surfcad-mcp room join again.';
233
+
234
+ /**
235
+ * Why the server would not take the request, in words.
236
+ * @param {number} status
237
+ * @param {unknown} error
238
+ */
239
+ export function roomRequestError(status, error) {
240
+ if (status === 429) return { code: 'rate_limited', message: `Too many agents are asking for a seat in this room, or this machine asked too often. Wait a minute. ${AGAIN}` };
241
+ if (status === 403) return { code: 'rooms_off', message: 'Rooms are off on this server for now.' };
242
+ if (error === 'bad_room') return { code: 'bad_room', message: 'The server does not take that room link. Copy it again from SurfCAD.' };
243
+ return { code: 'request_failed', message: 'Could not ask for a seat.' };
244
+ }
245
+
246
+ /**
247
+ * Ask for a seat, wait for the host, save the seat token.
248
+ * @param {{
249
+ * serverUrl: string,
250
+ * room: string,
251
+ * label?: string,
252
+ * machine?: string,
253
+ * env?: NodeJS.ProcessEnv,
254
+ * fetch?: typeof fetch,
255
+ * sleep?: (ms: number) => Promise<void>,
256
+ * now?: () => number,
257
+ * onCode?: (info: { code: string, expiresAt: number }) => Promise<void> | void,
258
+ * }} options
259
+ * @returns {Promise<{ server: string, room: string, label: string, machine: string, expiresAt: number }>}
260
+ */
261
+ export async function joinRoom(options) {
262
+ const urls = roomSeatUrls(options.serverUrl);
263
+ const fetchImpl = options.fetch || fetch;
264
+ const sleep = options.sleep || ((ms) => new Promise((resolve) => {
265
+ setTimeout(resolve, ms);
266
+ }));
267
+ const now = options.now || Date.now;
268
+ const room = normalizeRoomKey(options.room);
269
+ if (!room) throw Object.assign(new Error('That is not a room.'), { code: 'bad_room' });
270
+ const label = (typeof options.label === 'string' ? options.label.trim() : '').slice(0, LABEL_MAX);
271
+ const machine = (options.machine || hostname() || '').trim().slice(0, MACHINE_MAX);
272
+
273
+ // 32 random bytes. The request sends only their SHA-256; the poll sends
274
+ // the secret itself. Neither is logged.
275
+ const bytes = randomBytes(32);
276
+ const secret = bytes.toString('base64url');
277
+ const secretHash = createHash('sha256').update(bytes).digest('hex');
278
+
279
+ const asked = await postJson(urls.requestUrl, {
280
+ room,
281
+ secretHash,
282
+ ...(label ? { label } : {}),
283
+ ...(machine ? { machine } : {}),
284
+ }, fetchImpl);
285
+ if (asked.status !== 201 || typeof asked.json?.code !== 'string') {
286
+ const { code, message } = roomRequestError(asked.status, asked.json?.error);
287
+ throw Object.assign(new Error(message), { code });
288
+ }
289
+ const intervalSec = Number(asked.json.interval);
290
+ const pollMs = Number.isFinite(intervalSec) && intervalSec > 0 ? intervalSec * 1000 : 5000;
291
+ const deadline = Number.isFinite(asked.json.expiresAt) ? Number(asked.json.expiresAt) : now() + 10 * 60 * 1000;
292
+ if (options.onCode) await options.onCode({ code: asked.json.code, expiresAt: deadline });
293
+
294
+ // One more poll after the deadline: the host may have approved in the last seconds.
295
+ let last = false;
296
+ for (;;) {
297
+ const polled = await postJson(urls.tokenUrl, { secret }, fetchImpl);
298
+ if (polled.status === 200 && polled.json?.status === 'approved') {
299
+ const token = polled.json.token;
300
+ if (typeof token !== 'string' || !token) {
301
+ throw Object.assign(new Error(`The server approved the seat but sent no token. ${AGAIN}`), { code: 'bad_seat' });
302
+ }
303
+ const seat = polled.json.seat && typeof polled.json.seat === 'object' ? polled.json.seat : {};
304
+ const record = {
305
+ token,
306
+ server: urls.origin,
307
+ room,
308
+ label: typeof seat.label === 'string' ? seat.label : label,
309
+ machine: typeof seat.machine === 'string' ? seat.machine : machine,
310
+ expiresAt: Number.isFinite(seat.expiresAt) ? Number(seat.expiresAt) : 0,
311
+ };
312
+ await saveRoomSeat(record, options.env);
313
+ return { server: record.server, room, label: record.label, machine: record.machine, expiresAt: record.expiresAt };
314
+ }
315
+ if (polled.status === 403 && polled.json?.error === 'denied') {
316
+ throw Object.assign(new Error('The host denied this agent.'), { code: 'denied' });
317
+ }
318
+ if (polled.status === 403) throw Object.assign(new Error('Rooms are off on this server for now.'), { code: 'rooms_off' });
319
+ if (polled.status === 404) {
320
+ throw Object.assign(new Error(`Nobody approved the code in time. ${AGAIN}`), { code: 'expired' });
321
+ }
322
+ if (polled.status === 429) {
323
+ throw Object.assign(new Error(`This machine asked too often. Wait a minute. ${AGAIN}`), { code: 'rate_limited' });
324
+ }
325
+ if (polled.status !== 200 || polled.json?.status !== 'pending') {
326
+ throw Object.assign(new Error('Could not check whether the host approved.'), { code: 'poll_failed' });
327
+ }
328
+ if (last) break;
329
+ const wait = Math.min(pollMs, Math.max(0, deadline - now()));
330
+ if (wait > 0) await sleep(wait);
331
+ if (now() >= deadline) last = true;
332
+ }
333
+ throw Object.assign(new Error(`Nobody approved the code in time. ${AGAIN}`), { code: 'expired' });
334
+ }
@@ -2,6 +2,7 @@ import { randomBytes } from 'node:crypto';
2
2
  import { mkdir, open, stat, writeFile } from 'node:fs/promises';
3
3
  import { tmpdir } from 'node:os';
4
4
  import { basename, dirname, extname, isAbsolute, join, resolve } from 'node:path';
5
+ import { callBenchShowFromPath, callImportFromPath } from './importFile.mjs';
5
6
 
6
7
  const BROWSER_KEYS = ['format', 'quality', 'max_width', 'scale'];
7
8
 
@@ -181,6 +182,14 @@ export async function callPairedBridgeTool(session, name, args) {
181
182
  forward = prepared.browserArgs;
182
183
  save = prepared.save;
183
184
  }
185
+ if (name === 'import_model') {
186
+ const imported = await callImportFromPath(session, forward);
187
+ if (imported) return imported;
188
+ }
189
+ if (name === 'bench_show') {
190
+ const shown = await callBenchShowFromPath(session, forward);
191
+ if (shown) return shown;
192
+ }
184
193
  const result = await session.call(name, forward);
185
194
  if (!save) return { value: result, isError: false };
186
195
  try {