surfcad-mcp 0.3.2 → 0.3.4
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 +55 -7
- package/bin/surfcad-mcp.js +36 -3
- package/data/commands.json +4424 -129
- package/data/helpers.json +35 -11
- package/package.json +2 -2
- package/src/bridge/bridgePopup.mjs +28 -1
- package/src/bridge/localAddress.mjs +43 -5
- package/src/bridge/relayHub.mjs +31 -9
- package/src/cli.mjs +230 -0
- package/src/commandProtocol.mjs +126 -0
- package/src/errors.mjs +81 -2
- package/src/helpers.mjs +1 -1
- package/src/pairWait.mjs +34 -0
- package/src/prompt/errorHints.mjs +22 -5
- package/src/prompt/guide.mjs +4 -4
- package/src/prompt/promptSession.mjs +62 -23
- package/src/prompt/promptTools.mjs +2 -2
- package/src/relay.mjs +8 -5
- package/src/remote/config.mjs +178 -0
- package/src/remote/httpFallback.mjs +289 -0
- package/src/remote/login.mjs +258 -0
- package/src/remote/logout.mjs +67 -0
- package/src/remote/session.mjs +534 -0
- package/src/remote/tokenStore.mjs +109 -0
- package/src/server.mjs +52 -23
|
@@ -0,0 +1,534 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Outbound session to the server relay. WebSocket first; if that upgrade
|
|
3
|
+
* fails, commands go over HTTPS POST plus SSE, then long-poll.
|
|
4
|
+
* The bearer token is never logged and is never placed in the URL.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { WebSocket } from 'ws';
|
|
8
|
+
import {
|
|
9
|
+
AGENT_HANDSHAKE_UPDATE_MESSAGE,
|
|
10
|
+
AGENT_PROTOCOL_VERSION,
|
|
11
|
+
commandRequest,
|
|
12
|
+
} from '../commandProtocol.mjs';
|
|
13
|
+
import {
|
|
14
|
+
asRemoteError,
|
|
15
|
+
clientUpdateError,
|
|
16
|
+
pairingLostError,
|
|
17
|
+
tokenRevokedError,
|
|
18
|
+
} from '../errors.mjs';
|
|
19
|
+
import { PAIR_MSG } from '../relayMessages.mjs';
|
|
20
|
+
import { createPromptSession } from '../prompt/promptSession.mjs';
|
|
21
|
+
import { agentUrls, resolveAgentName } from './config.mjs';
|
|
22
|
+
import { callOverHttp, COMMAND_WAIT_MS, commandWaitTimeout, resultFromCommandResponse } from './httpFallback.mjs';
|
|
23
|
+
|
|
24
|
+
/** Server relay closes a revoked or expired token with this code. */
|
|
25
|
+
const TOKEN_CLOSE_CODE = 4001;
|
|
26
|
+
const HELLO_TIMEOUT_MS = 8000;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* @param {string} wsUrl
|
|
30
|
+
* @param {string} token
|
|
31
|
+
*/
|
|
32
|
+
function openAuthorizedSocket(wsUrl, token) {
|
|
33
|
+
return new Promise((resolve, reject) => {
|
|
34
|
+
const ws = new WebSocket(wsUrl, {
|
|
35
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
36
|
+
handshakeTimeout: HELLO_TIMEOUT_MS,
|
|
37
|
+
});
|
|
38
|
+
let settled = false;
|
|
39
|
+
const fail = (err) => {
|
|
40
|
+
if (settled) return;
|
|
41
|
+
settled = true;
|
|
42
|
+
try { ws.terminate(); } catch { /* noop */ }
|
|
43
|
+
reject(err);
|
|
44
|
+
};
|
|
45
|
+
ws.once('unexpected-response', (_req, res) => {
|
|
46
|
+
const status = res.statusCode || 0;
|
|
47
|
+
res.resume();
|
|
48
|
+
if (status === 401) {
|
|
49
|
+
fail(tokenRevokedError());
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
fail(Object.assign(new Error(`WebSocket upgrade failed (${status})`), {
|
|
53
|
+
code: 'ws_blocked',
|
|
54
|
+
statusCode: status,
|
|
55
|
+
}));
|
|
56
|
+
});
|
|
57
|
+
ws.once('error', (error) => {
|
|
58
|
+
const errno = error && typeof error === 'object' ? error.code : '';
|
|
59
|
+
const code = errno === 'ECONNREFUSED' || errno === 'ENOTFOUND' ? 'unreachable' : 'ws_blocked';
|
|
60
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
61
|
+
fail(Object.assign(err, { code: /** @type {Error & { code?: string }} */ (err).code || code }));
|
|
62
|
+
});
|
|
63
|
+
ws.once('open', () => {
|
|
64
|
+
if (settled) return;
|
|
65
|
+
settled = true;
|
|
66
|
+
resolve(ws);
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Hello frame. `name` is omitted when empty so the server keeps its default.
|
|
73
|
+
* @param {{ v?: number, name?: string }} fields
|
|
74
|
+
*/
|
|
75
|
+
export function agentHelloFrame(fields = {}) {
|
|
76
|
+
/** @type {{ type: 'hello', v: number, name?: string }} */
|
|
77
|
+
const frame = {
|
|
78
|
+
type: 'hello',
|
|
79
|
+
v: typeof fields.v === 'number' ? fields.v : AGENT_PROTOCOL_VERSION,
|
|
80
|
+
};
|
|
81
|
+
if (typeof fields.name === 'string' && fields.name.trim()) frame.name = fields.name.trim();
|
|
82
|
+
return frame;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function defaultLog(line) {
|
|
86
|
+
console.error(`${new Date().toISOString()} [surfcad-mcp] ${line}`);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export class RemoteSession {
|
|
90
|
+
/** @type {WebSocket | null} */
|
|
91
|
+
#ws = null;
|
|
92
|
+
#urls;
|
|
93
|
+
#token;
|
|
94
|
+
#name;
|
|
95
|
+
#fillFromClient;
|
|
96
|
+
#protocolVersion;
|
|
97
|
+
/** @type {'ws' | 'http' | null} */
|
|
98
|
+
#transport = null;
|
|
99
|
+
/** @type {'unpaired' | 'pairing' | 'paired'} */
|
|
100
|
+
#state = 'unpaired';
|
|
101
|
+
/** @type {Promise<void> | null} */
|
|
102
|
+
#connecting = null;
|
|
103
|
+
/** @type {{ resolve: () => void, reject: (err: Error) => void } | null} */
|
|
104
|
+
#hello = null;
|
|
105
|
+
/** @type {Map<string, { resolve: (v: unknown) => void, reject: (e: Error) => void }>} */
|
|
106
|
+
#pending = new Map();
|
|
107
|
+
#log;
|
|
108
|
+
#fetch;
|
|
109
|
+
#commandTimeoutMs;
|
|
110
|
+
#prompts;
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* @param {{
|
|
114
|
+
* serverUrl: string,
|
|
115
|
+
* token: string,
|
|
116
|
+
* name?: string,
|
|
117
|
+
* fillNameFromClient?: boolean,
|
|
118
|
+
* protocolVersion?: number,
|
|
119
|
+
* onLog?: (line: string) => void,
|
|
120
|
+
* fetch?: typeof fetch,
|
|
121
|
+
* env?: NodeJS.ProcessEnv,
|
|
122
|
+
* promptSession?: ReturnType<typeof createPromptSession>,
|
|
123
|
+
* commandTimeoutMs?: number,
|
|
124
|
+
* }} options
|
|
125
|
+
*/
|
|
126
|
+
constructor(options) {
|
|
127
|
+
this.#urls = agentUrls(options.serverUrl);
|
|
128
|
+
this.#token = options.token;
|
|
129
|
+
this.#name = typeof options.name === 'string' ? options.name.trim() : '';
|
|
130
|
+
this.#fillFromClient = options.fillNameFromClient === true && !this.#name;
|
|
131
|
+
this.#protocolVersion = typeof options.protocolVersion === 'number'
|
|
132
|
+
? options.protocolVersion
|
|
133
|
+
: AGENT_PROTOCOL_VERSION;
|
|
134
|
+
this.#log = options.onLog || defaultLog;
|
|
135
|
+
this.#fetch = options.fetch || fetch;
|
|
136
|
+
this.#commandTimeoutMs = Number.isFinite(options.commandTimeoutMs) && options.commandTimeoutMs > 0
|
|
137
|
+
? options.commandTimeoutMs
|
|
138
|
+
: COMMAND_WAIT_MS;
|
|
139
|
+
this.#prompts = options.promptSession || createPromptSession({
|
|
140
|
+
send: (payload) => this.#sendToTab(payload),
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
get url() {
|
|
145
|
+
return this.#urls.wsUrl;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
get state() {
|
|
149
|
+
return this.#state;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
get agentName() {
|
|
153
|
+
return this.#name;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** True when hello should wait for the MCP client name. */
|
|
157
|
+
needsClientName() {
|
|
158
|
+
return this.#fillFromClient && !this.#name;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* @param {{ name?: string } | null | undefined} clientInfo
|
|
163
|
+
*/
|
|
164
|
+
applyClientInfo(clientInfo) {
|
|
165
|
+
if (!this.#fillFromClient || this.#name) return;
|
|
166
|
+
const name = resolveAgentName({ clientInfo });
|
|
167
|
+
if (name) this.#name = name;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* @param {string} name
|
|
172
|
+
*/
|
|
173
|
+
setName(name) {
|
|
174
|
+
const text = typeof name === 'string' ? name.trim() : '';
|
|
175
|
+
if (text) this.#name = text;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
status() {
|
|
179
|
+
return {
|
|
180
|
+
state: this.#state,
|
|
181
|
+
transport: this.#transport,
|
|
182
|
+
remote: true,
|
|
183
|
+
server: this.#urls.origin,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
isPaired() {
|
|
188
|
+
if (this.#state !== 'paired') return false;
|
|
189
|
+
if (this.#transport === 'http') return true;
|
|
190
|
+
return this.#ws != null && this.#ws.readyState === WebSocket.OPEN;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
get prompts() {
|
|
194
|
+
return this.#prompts;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* @param {{ mutates?: boolean }} [info]
|
|
199
|
+
*/
|
|
200
|
+
noteAgentToolCall(info = {}) {
|
|
201
|
+
try {
|
|
202
|
+
this.#prompts.noteToolCall(info);
|
|
203
|
+
} catch {
|
|
204
|
+
/* status is advisory */
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* @param {boolean} held
|
|
210
|
+
*/
|
|
211
|
+
holdAgentWork(held) {
|
|
212
|
+
try {
|
|
213
|
+
this.#prompts.holdWork(held === true);
|
|
214
|
+
} catch {
|
|
215
|
+
/* status is advisory */
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Already logged in. The 8-character code is the local relay's; remote
|
|
221
|
+
* mode ignores it and reports the saved login.
|
|
222
|
+
* @param {string} [_] local pairing code; a remote login ignores it
|
|
223
|
+
*/
|
|
224
|
+
pair(_) {
|
|
225
|
+
return this.connect().then(() => ({
|
|
226
|
+
paired: true,
|
|
227
|
+
remote: true,
|
|
228
|
+
relay: this.#urls.approvalUrl,
|
|
229
|
+
}));
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
connect() {
|
|
233
|
+
if (this.#state === 'paired' && this.isPaired()) return Promise.resolve();
|
|
234
|
+
if (!this.#connecting) this.#connecting = this.#connect();
|
|
235
|
+
return this.#connecting;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async #connect() {
|
|
239
|
+
this.#state = 'pairing';
|
|
240
|
+
try {
|
|
241
|
+
try {
|
|
242
|
+
await this.#openWebSocket();
|
|
243
|
+
this.#transport = 'ws';
|
|
244
|
+
this.#state = 'paired';
|
|
245
|
+
this.#log('remote agent connected via websocket');
|
|
246
|
+
return;
|
|
247
|
+
} catch (err) {
|
|
248
|
+
this.#dropSocket();
|
|
249
|
+
const code = err && typeof err === 'object' ? err.code : '';
|
|
250
|
+
if (code === 'token_revoked' || code === 'client_update_required') {
|
|
251
|
+
// Stay 'pairing' so a later tool call reaches `call()` and surfaces this error.
|
|
252
|
+
this.#state = 'pairing';
|
|
253
|
+
throw err;
|
|
254
|
+
}
|
|
255
|
+
try {
|
|
256
|
+
await this.#probeHttp();
|
|
257
|
+
} catch (probeErr) {
|
|
258
|
+
this.#state = 'pairing';
|
|
259
|
+
throw probeErr;
|
|
260
|
+
}
|
|
261
|
+
this.#transport = 'http';
|
|
262
|
+
this.#state = 'paired';
|
|
263
|
+
this.#log('remote agent connected via https fallback');
|
|
264
|
+
}
|
|
265
|
+
} finally {
|
|
266
|
+
// Success used to leave the settled promise here, so a later connect()
|
|
267
|
+
// that was no longer paired reused it and never opened a new socket.
|
|
268
|
+
this.#connecting = null;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
async #openWebSocket() {
|
|
273
|
+
const ws = await openAuthorizedSocket(this.#urls.wsUrl, this.#token);
|
|
274
|
+
this.#ws = ws;
|
|
275
|
+
ws.on('message', (raw) => this.#onMessage(raw));
|
|
276
|
+
ws.on('close', (code, reason) => this.#onClose(code, reason));
|
|
277
|
+
ws.on('error', () => { /* close follows */ });
|
|
278
|
+
const hello = agentHelloFrame({ v: this.#protocolVersion, name: this.#name });
|
|
279
|
+
const acked = new Promise((resolve, reject) => {
|
|
280
|
+
this.#hello = { resolve, reject };
|
|
281
|
+
const timer = setTimeout(() => {
|
|
282
|
+
if (this.#hello) {
|
|
283
|
+
this.#hello = null;
|
|
284
|
+
reject(Object.assign(new Error('Agent handshake timed out'), { code: 'ws_blocked' }));
|
|
285
|
+
}
|
|
286
|
+
}, HELLO_TIMEOUT_MS);
|
|
287
|
+
const settle = this.#hello;
|
|
288
|
+
this.#hello = {
|
|
289
|
+
resolve: () => {
|
|
290
|
+
clearTimeout(timer);
|
|
291
|
+
settle.resolve();
|
|
292
|
+
},
|
|
293
|
+
reject: (err) => {
|
|
294
|
+
clearTimeout(timer);
|
|
295
|
+
settle.reject(err);
|
|
296
|
+
},
|
|
297
|
+
};
|
|
298
|
+
});
|
|
299
|
+
ws.send(JSON.stringify(hello));
|
|
300
|
+
await acked;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
async #probeHttp() {
|
|
304
|
+
try {
|
|
305
|
+
const res = await this.#fetch(this.#urls.approvalUrl, {
|
|
306
|
+
method: 'GET',
|
|
307
|
+
signal: AbortSignal.timeout(HELLO_TIMEOUT_MS),
|
|
308
|
+
});
|
|
309
|
+
try { await res.body?.cancel?.(); } catch { /* noop */ }
|
|
310
|
+
if (!res.status) {
|
|
311
|
+
throw Object.assign(new Error('Could not reach the SurfCAD agent server.'), { code: 'unreachable' });
|
|
312
|
+
}
|
|
313
|
+
} catch (err) {
|
|
314
|
+
if (err && typeof err === 'object' && err.code === 'unreachable') throw err;
|
|
315
|
+
throw Object.assign(new Error('Could not reach the SurfCAD agent server.'), { code: 'unreachable' });
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
#dropSocket() {
|
|
320
|
+
const ws = this.#ws;
|
|
321
|
+
this.#ws = null;
|
|
322
|
+
this.#hello = null;
|
|
323
|
+
if (!ws) return;
|
|
324
|
+
ws.removeAllListeners();
|
|
325
|
+
try { ws.terminate(); } catch { /* noop */ }
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* @param {import('ws').RawData} raw
|
|
330
|
+
*/
|
|
331
|
+
#onMessage(raw) {
|
|
332
|
+
/** @type {any} */
|
|
333
|
+
let msg;
|
|
334
|
+
try {
|
|
335
|
+
msg = JSON.parse(String(raw));
|
|
336
|
+
} catch {
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
if (!msg || typeof msg !== 'object') return;
|
|
340
|
+
if (this.#hello) {
|
|
341
|
+
const hello = this.#hello;
|
|
342
|
+
this.#hello = null;
|
|
343
|
+
if (msg.type === 'hello') {
|
|
344
|
+
hello.resolve();
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
const text = typeof msg.error === 'string' ? msg.error : '';
|
|
348
|
+
hello.reject(asRemoteError({
|
|
349
|
+
code: text.includes(AGENT_HANDSHAKE_UPDATE_MESSAGE) ? 'client_update_required' : 'ws_blocked',
|
|
350
|
+
message: text || 'Agent handshake failed',
|
|
351
|
+
}));
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
if (msg.type === PAIR_MSG.AGENT_PROMPT) {
|
|
355
|
+
void this.#prompts.acceptPrompt(msg);
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
if (msg.type === PAIR_MSG.AGENT_PROMPT_CANCEL) {
|
|
359
|
+
const cancelId = typeof msg.id === 'string' ? msg.id : '';
|
|
360
|
+
void this.#prompts.cancel(cancelId).then((result) => {
|
|
361
|
+
Promise.resolve(this.#sendToTab({
|
|
362
|
+
type: PAIR_MSG.AGENT_PROMPT_CANCEL_RESULT,
|
|
363
|
+
v: 1,
|
|
364
|
+
id: result.id,
|
|
365
|
+
state: result.state,
|
|
366
|
+
})).catch(() => {
|
|
367
|
+
/* socket closed before the result could be sent */
|
|
368
|
+
});
|
|
369
|
+
}, () => {});
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
const id = msg.id == null ? '' : String(msg.id);
|
|
373
|
+
const waiter = id ? this.#pending.get(id) : undefined;
|
|
374
|
+
if (!waiter) return;
|
|
375
|
+
this.#pending.delete(id);
|
|
376
|
+
const outcome = resultFromCommandResponse(msg);
|
|
377
|
+
if (outcome.ok) waiter.resolve(outcome.result);
|
|
378
|
+
else waiter.reject(outcome.error);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* @param {number} code
|
|
383
|
+
* @param {Buffer | string} reason
|
|
384
|
+
*/
|
|
385
|
+
#onClose(code, reason) {
|
|
386
|
+
const why = Buffer.isBuffer(reason) ? reason.toString('utf8') : String(reason || '');
|
|
387
|
+
const hello = this.#hello;
|
|
388
|
+
this.#hello = null;
|
|
389
|
+
this.#ws = null;
|
|
390
|
+
if (code === TOKEN_CLOSE_CODE) {
|
|
391
|
+
this.#transport = null;
|
|
392
|
+
this.#state = 'pairing';
|
|
393
|
+
this.#connecting = null;
|
|
394
|
+
const err = tokenRevokedError();
|
|
395
|
+
if (hello) hello.reject(err);
|
|
396
|
+
this.#failPending(err);
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
if (code === 1008 || why.includes(AGENT_HANDSHAKE_UPDATE_MESSAGE)) {
|
|
400
|
+
this.#transport = null;
|
|
401
|
+
this.#state = 'pairing';
|
|
402
|
+
this.#connecting = null;
|
|
403
|
+
const err = clientUpdateError(why || AGENT_HANDSHAKE_UPDATE_MESSAGE);
|
|
404
|
+
if (hello) hello.reject(err);
|
|
405
|
+
this.#failPending(err);
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
if (hello) {
|
|
409
|
+
hello.reject(Object.assign(new Error(`WebSocket closed (${code})`), { code: 'ws_blocked' }));
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
if (this.#state === 'paired' && this.#transport === 'ws') {
|
|
413
|
+
this.#transport = 'http';
|
|
414
|
+
this.#log('websocket closed; later commands use https');
|
|
415
|
+
this.#failPending(pairingLostError('socket closed'));
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* @param {Error} err
|
|
421
|
+
*/
|
|
422
|
+
#failPending(err) {
|
|
423
|
+
for (const waiter of this.#pending.values()) waiter.reject(err);
|
|
424
|
+
this.#pending.clear();
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* Status and prompt frames. A paired WebSocket sends them on the socket.
|
|
429
|
+
* A paired HTTPS fallback (join-code login when wss is blocked, or the
|
|
430
|
+
* socket dropped) POSTs them. Either way a connected session is connected:
|
|
431
|
+
* the caller hears the transport's error, not a collapsed not_paired.
|
|
432
|
+
* @param {object} payload
|
|
433
|
+
*/
|
|
434
|
+
async #sendToTab(payload) {
|
|
435
|
+
if (!this.isPaired()) await this.connect();
|
|
436
|
+
if (this.#transport === 'ws' && this.#ws && this.#ws.readyState === WebSocket.OPEN) {
|
|
437
|
+
this.#ws.send(JSON.stringify(payload));
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
if (this.#state === 'paired' && this.#transport === 'http') {
|
|
441
|
+
await this.#postPrompt(payload);
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* @param {object} payload
|
|
449
|
+
*/
|
|
450
|
+
async #postPrompt(payload) {
|
|
451
|
+
let res;
|
|
452
|
+
try {
|
|
453
|
+
res = await this.#fetch(this.#urls.promptsUrl, {
|
|
454
|
+
method: 'POST',
|
|
455
|
+
headers: {
|
|
456
|
+
Authorization: `Bearer ${this.#token}`,
|
|
457
|
+
'Content-Type': 'application/json',
|
|
458
|
+
},
|
|
459
|
+
body: JSON.stringify(payload),
|
|
460
|
+
});
|
|
461
|
+
} catch {
|
|
462
|
+
throw Object.assign(new Error('Could not reach the SurfCAD agent server.'), { code: 'unreachable' });
|
|
463
|
+
}
|
|
464
|
+
if (!res.ok) {
|
|
465
|
+
let json = null;
|
|
466
|
+
try { json = await res.json(); } catch { json = null; }
|
|
467
|
+
if (res.status === 401) throw tokenRevokedError();
|
|
468
|
+
const code = typeof json?.error === 'string' && json.error ? json.error : 'bridge_error';
|
|
469
|
+
const message = typeof json?.message === 'string' && json.message
|
|
470
|
+
? json.message
|
|
471
|
+
: `Prompt send failed (${res.status})`;
|
|
472
|
+
throw Object.assign(new Error(message), { code });
|
|
473
|
+
}
|
|
474
|
+
try { await res.body?.cancel?.(); } catch { /* noop */ }
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* @param {string} command
|
|
479
|
+
* @param {Record<string, unknown>} [args]
|
|
480
|
+
*/
|
|
481
|
+
call(command, args = {}) {
|
|
482
|
+
return this.connect().then(() => this.#call(command, args));
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* @param {string} command
|
|
487
|
+
* @param {Record<string, unknown>} args
|
|
488
|
+
*/
|
|
489
|
+
#call(command, args) {
|
|
490
|
+
const id = `mcp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
491
|
+
const frame = commandRequest({ id, command, args });
|
|
492
|
+
if (this.#transport === 'ws' && this.#ws && this.#ws.readyState === WebSocket.OPEN) {
|
|
493
|
+
return new Promise((resolve, reject) => {
|
|
494
|
+
const timer = setTimeout(() => {
|
|
495
|
+
if (!this.#pending.has(id)) return;
|
|
496
|
+
this.#pending.delete(id);
|
|
497
|
+
reject(commandWaitTimeout());
|
|
498
|
+
}, this.#commandTimeoutMs);
|
|
499
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
500
|
+
const finish = (fn, value) => {
|
|
501
|
+
clearTimeout(timer);
|
|
502
|
+
fn(value);
|
|
503
|
+
};
|
|
504
|
+
this.#pending.set(id, {
|
|
505
|
+
resolve: (value) => finish(resolve, value),
|
|
506
|
+
reject: (err) => finish(reject, err),
|
|
507
|
+
});
|
|
508
|
+
try {
|
|
509
|
+
this.#ws.send(JSON.stringify(frame));
|
|
510
|
+
} catch {
|
|
511
|
+
this.#pending.delete(id);
|
|
512
|
+
finish(reject, pairingLostError('send failed'));
|
|
513
|
+
}
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
return callOverHttp({
|
|
517
|
+
commandsUrl: this.#urls.commandsUrl,
|
|
518
|
+
token: this.#token,
|
|
519
|
+
frame,
|
|
520
|
+
fetch: this.#fetch,
|
|
521
|
+
}).catch((err) => {
|
|
522
|
+
throw asRemoteError(err);
|
|
523
|
+
});
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
disconnect() {
|
|
527
|
+
this.#connecting = null;
|
|
528
|
+
this.#dropSocket();
|
|
529
|
+
this.#transport = null;
|
|
530
|
+
this.#state = 'unpaired';
|
|
531
|
+
this.#prompts.clear();
|
|
532
|
+
this.#failPending(Object.assign(new Error('Disconnected'), { code: 'not_paired' }));
|
|
533
|
+
}
|
|
534
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Saved remote login. The file mode is 0600 and the directory is 0700.
|
|
3
|
+
* Callers must not log the returned token.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import { configDir, tokenPath } from './config.mjs';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @typedef {{
|
|
12
|
+
* token: string,
|
|
13
|
+
* server: string,
|
|
14
|
+
* name: string,
|
|
15
|
+
* machine: string,
|
|
16
|
+
* savedAt: string,
|
|
17
|
+
* }} SavedLogin
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
22
|
+
* @returns {Promise<SavedLogin | null>}
|
|
23
|
+
*/
|
|
24
|
+
export async function readSavedLogin(env = process.env) {
|
|
25
|
+
const path = tokenPath(env);
|
|
26
|
+
/** @type {string} */
|
|
27
|
+
let text;
|
|
28
|
+
try {
|
|
29
|
+
text = await readFile(path, 'utf8');
|
|
30
|
+
} catch (err) {
|
|
31
|
+
if (err && typeof err === 'object' && err.code === 'ENOENT') return null;
|
|
32
|
+
throw Object.assign(new Error('Saved login could not be read.'), { code: 'bad_login_file' });
|
|
33
|
+
}
|
|
34
|
+
/** @type {unknown} */
|
|
35
|
+
let parsed;
|
|
36
|
+
try {
|
|
37
|
+
parsed = JSON.parse(text);
|
|
38
|
+
} catch {
|
|
39
|
+
throw Object.assign(new Error('Saved login could not be read.'), { code: 'bad_login_file' });
|
|
40
|
+
}
|
|
41
|
+
if (!parsed || typeof parsed !== 'object') return null;
|
|
42
|
+
const record = /** @type {Record<string, unknown>} */ (parsed);
|
|
43
|
+
if (typeof record.token !== 'string' || !record.token) return null;
|
|
44
|
+
return {
|
|
45
|
+
token: record.token,
|
|
46
|
+
server: typeof record.server === 'string' ? record.server : '',
|
|
47
|
+
name: typeof record.name === 'string' ? record.name : '',
|
|
48
|
+
machine: typeof record.machine === 'string' ? record.machine : '',
|
|
49
|
+
savedAt: typeof record.savedAt === 'string' ? record.savedAt : '',
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* @param {{ token: string, server: string, name?: string, machine?: string, savedAt?: string }} record
|
|
55
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
56
|
+
* @returns {Promise<string>} path written
|
|
57
|
+
*/
|
|
58
|
+
export async function saveLogin(record, env = process.env) {
|
|
59
|
+
if (typeof record.token !== 'string' || !record.token) {
|
|
60
|
+
throw Object.assign(new Error('Login did not return a token.'), { code: 'bad_login' });
|
|
61
|
+
}
|
|
62
|
+
const dir = configDir(env);
|
|
63
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
64
|
+
await chmod(dir, 0o700);
|
|
65
|
+
const path = tokenPath(env);
|
|
66
|
+
const tmp = join(dir, `.token-${process.pid}-${Date.now()}.tmp`);
|
|
67
|
+
const body = `${JSON.stringify({
|
|
68
|
+
token: record.token,
|
|
69
|
+
server: record.server,
|
|
70
|
+
name: record.name || '',
|
|
71
|
+
machine: record.machine || '',
|
|
72
|
+
savedAt: record.savedAt || new Date().toISOString(),
|
|
73
|
+
})}\n`;
|
|
74
|
+
try {
|
|
75
|
+
await writeFile(tmp, body, { mode: 0o600, flag: 'wx' });
|
|
76
|
+
await chmod(tmp, 0o600);
|
|
77
|
+
await rename(tmp, path);
|
|
78
|
+
await chmod(path, 0o600);
|
|
79
|
+
} catch (err) {
|
|
80
|
+
await rm(tmp, { force: true });
|
|
81
|
+
if (err && typeof err === 'object' && err.code === 'bad_login') throw err;
|
|
82
|
+
throw Object.assign(new Error('Could not save the login.'), { code: 'save_failed' });
|
|
83
|
+
}
|
|
84
|
+
return path;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
89
|
+
*/
|
|
90
|
+
export async function deleteSavedLogin(env = process.env) {
|
|
91
|
+
await rm(tokenPath(env), { force: true });
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Status text. Never includes the token.
|
|
96
|
+
* @param {SavedLogin | null} saved
|
|
97
|
+
* @param {string} serverUrl effective server (flag or env may override the saved one)
|
|
98
|
+
*/
|
|
99
|
+
export function formatLoginStatus(saved, serverUrl) {
|
|
100
|
+
if (!saved) return 'not logged in\n';
|
|
101
|
+
const lines = [
|
|
102
|
+
'logged in',
|
|
103
|
+
`server: ${serverUrl}`,
|
|
104
|
+
`name: ${saved.name || '(none)'}`,
|
|
105
|
+
`machine: ${saved.machine || '(none)'}`,
|
|
106
|
+
`saved: ${saved.savedAt || '(unknown)'}`,
|
|
107
|
+
];
|
|
108
|
+
return `${lines.join('\n')}\n`;
|
|
109
|
+
}
|