surfcad-mcp 0.3.3 → 0.3.5

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.
@@ -31,12 +31,34 @@ export function loginStatusError(status) {
31
31
  return 'Login ended before approval. Run npx surfcad-mcp login again.';
32
32
  }
33
33
 
34
+ export const LOGIN_STALE_MESSAGE = 'That login code is stale. Run npx surfcad-mcp login again for a new one.';
35
+
36
+ /**
37
+ * @param {unknown} retryAfterSec
38
+ * @returns {string} empty, or ` try again in N s.`
39
+ */
40
+ export function formatRetryAfter(retryAfterSec) {
41
+ const sec = Number(retryAfterSec);
42
+ if (!Number.isFinite(sec) || sec <= 0) return '';
43
+ return ` try again in ${Math.ceil(sec)} s.`;
44
+ }
45
+
46
+ /**
47
+ * @param {string} lead sentence ending in a period
48
+ * @param {unknown} retryAfterSec
49
+ * @param {string} again
50
+ */
51
+ function rateLimitMessage(lead, retryAfterSec, again) {
52
+ return `${lead}${formatRetryAfter(retryAfterSec)} ${again}`;
53
+ }
54
+
34
55
  /**
35
56
  * @param {string} url
36
57
  * @param {object} body
37
58
  * @param {typeof fetch} fetchImpl
59
+ * @param {AbortSignal} [signal]
38
60
  */
39
- async function postJson(url, body, fetchImpl) {
61
+ async function postJson(url, body, fetchImpl, signal) {
40
62
  /** @type {Response} */
41
63
  let res;
42
64
  try {
@@ -47,8 +69,12 @@ async function postJson(url, body, fetchImpl) {
47
69
  Accept: 'application/json',
48
70
  },
49
71
  body: JSON.stringify(body),
72
+ signal,
50
73
  });
51
- } catch {
74
+ } catch (err) {
75
+ if (err?.name === 'AbortError') {
76
+ throw Object.assign(new Error('aborted'), { code: 'aborted' });
77
+ }
52
78
  throw Object.assign(new Error('Could not reach the SurfCAD agent server.'), { code: 'unreachable' });
53
79
  }
54
80
  /** @type {any} */
@@ -93,7 +119,11 @@ export async function loginDevice(options) {
93
119
  if (started.status !== 201 || !started.json?.userCode) {
94
120
  const code = started.json?.error === 'rate_limited' ? 'rate_limited' : 'pair_failed';
95
121
  const message = code === 'rate_limited'
96
- ? 'Too many login attempts. Wait and run npx surfcad-mcp login again.'
122
+ ? rateLimitMessage(
123
+ 'Too many login attempts.',
124
+ started.json?.retryAfterSec,
125
+ 'Run npx surfcad-mcp login again.',
126
+ )
97
127
  : 'Could not start login.';
98
128
  throw Object.assign(new Error(message), { code });
99
129
  }
@@ -107,12 +137,47 @@ export async function loginDevice(options) {
107
137
  interval: Number.isFinite(intervalSec) && intervalSec > 0 ? intervalSec : 5,
108
138
  });
109
139
  }
110
- const deadline = now() + (options.timeoutMs ?? 10 * 60 * 1000);
140
+ const expiresAtMs = Date.parse(started.json.expiresAt);
141
+ const deadline = Number.isFinite(expiresAtMs)
142
+ ? expiresAtMs
143
+ : now() + (options.timeoutMs ?? 10 * 60 * 1000);
111
144
  let first = true;
112
145
  while (now() < deadline) {
113
- if (!first) await sleep(pollMs);
146
+ if (!first) {
147
+ const wait = Math.min(pollMs, deadline - now());
148
+ if (wait > 0) await sleep(wait);
149
+ if (now() >= deadline) break;
150
+ }
114
151
  first = false;
115
- const polled = await postJson(urls.pollUrl, { deviceSecret, userCode }, fetchImpl);
152
+ const controller = typeof AbortController === 'function' ? new AbortController() : null;
153
+ const remaining = Math.max(0, deadline - now());
154
+ /** @type {ReturnType<typeof setTimeout> | undefined} */
155
+ let timeoutId;
156
+ const timeout = new Promise((resolve) => {
157
+ timeoutId = setTimeout(() => {
158
+ controller?.abort();
159
+ resolve({ timedOut: true });
160
+ }, remaining);
161
+ });
162
+ const pending = postJson(urls.pollUrl, { deviceSecret, userCode }, fetchImpl, controller?.signal)
163
+ .catch((err) => {
164
+ if (err?.code === 'aborted') return { timedOut: true };
165
+ throw err;
166
+ });
167
+ let polled;
168
+ try {
169
+ polled = await Promise.race([pending, timeout]);
170
+ } finally {
171
+ clearTimeout(timeoutId);
172
+ }
173
+ if (polled?.timedOut) break;
174
+ if (polled.status === 429) {
175
+ throw Object.assign(new Error(rateLimitMessage(
176
+ 'Too many login attempts.',
177
+ polled.json?.retryAfterSec,
178
+ 'Run npx surfcad-mcp login again.',
179
+ )), { code: 'rate_limited' });
180
+ }
116
181
  if (polled.status !== 200 || !polled.json?.status) {
117
182
  throw Object.assign(new Error('Could not check the login code.'), { code: 'poll_failed' });
118
183
  }
@@ -136,10 +201,7 @@ export async function loginDevice(options) {
136
201
  }
137
202
  throw Object.assign(new Error(loginStatusError(status)), { code: status });
138
203
  }
139
- throw Object.assign(
140
- new Error('Timed out waiting for approval. Run npx surfcad-mcp login again.'),
141
- { code: 'expired' },
142
- );
204
+ throw Object.assign(new Error(LOGIN_STALE_MESSAGE), { code: 'expired' });
143
205
  }
144
206
 
145
207
  /**
@@ -171,7 +233,11 @@ export async function loginWithCode(options) {
171
233
  }, fetchImpl);
172
234
  if (redeemed.status === 429) {
173
235
  throw Object.assign(
174
- new Error('Too many attempts. Wait and run npx surfcad-mcp login --code again.'),
236
+ new Error(rateLimitMessage(
237
+ 'Too many attempts.',
238
+ redeemed.json?.retryAfterSec,
239
+ 'Run npx surfcad-mcp login --code again.',
240
+ )),
175
241
  { code: 'rate_limited' },
176
242
  );
177
243
  }
@@ -0,0 +1,137 @@
1
+ import { writeSync } from 'node:fs';
2
+
3
+ /**
4
+ * Stderr lines for a remote stdio process that is about to exit.
5
+ * stdout stays empty so MCP JSON-RPC is not mixed with diagnostics.
6
+ * The bearer, a join code, and a long token-shaped run are not written.
7
+ */
8
+
9
+ /**
10
+ * Newlines and other controls become spaces so one exit stays one log line.
11
+ * @param {string} text
12
+ */
13
+ function singleLine(text) {
14
+ let out = '';
15
+ for (let i = 0; i < text.length; i += 1) {
16
+ out += text.charCodeAt(i) < 32 ? ' ' : text[i];
17
+ }
18
+ return out;
19
+ }
20
+
21
+ /**
22
+ * @param {unknown} value
23
+ * @param {number} [max]
24
+ */
25
+ export function clipExitDetail(value, max = 160) {
26
+ let text = value instanceof Error ? (value.message || '') : String(value ?? '');
27
+ text = text.replace(/Bearer\s+\S+/gi, '');
28
+ text = text.replace(/\b[A-Z0-9]{4}-[A-Z0-9]{4}\b/g, '');
29
+ text = text.replace(/\b[A-Za-z0-9_-]{32,}\b/g, '');
30
+ text = singleLine(text).replace(/\s+/g, ' ').trim();
31
+ if (text.length > max) text = text.slice(0, max);
32
+ return text;
33
+ }
34
+
35
+ /**
36
+ * @param {string} cause
37
+ * @param {unknown} [detail]
38
+ */
39
+ export function formatProcessExitLine(cause, detail) {
40
+ const name = clipExitDetail(cause) || 'unknown';
41
+ const extra = detail == null || detail === '' ? '' : ` ${clipExitDetail(detail)}`;
42
+ return `${new Date().toISOString()} [surfcad-mcp] process exit: ${name}${extra}\n`;
43
+ }
44
+
45
+ /**
46
+ * @param {string} cause
47
+ * @param {unknown} [detail]
48
+ * @param {(fd: number, line: string) => void} [write]
49
+ */
50
+ export function logProcessExit(cause, detail, write = writeSync) {
51
+ try {
52
+ write(2, formatProcessExitLine(cause, detail));
53
+ } catch {
54
+ /* stderr is already closed */
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Same exit as the previous stdin handler: disconnect, then leave the
60
+ * process on the next turn so a socket teardown can finish.
61
+ * @param {{ disconnect?: () => void } | null | undefined} remote
62
+ * @param {{
63
+ * log?: (cause: string, detail?: unknown) => void,
64
+ * exit?: (code: number) => void,
65
+ * }} [deps]
66
+ */
67
+ export function handleRemoteStdinEnd(remote, deps = {}) {
68
+ const log = deps.log || logProcessExit;
69
+ const exit = deps.exit || (() => {
70
+ setTimeout(() => process.exit(0), 0).unref();
71
+ });
72
+ log('stdin end');
73
+ remote?.disconnect?.();
74
+ exit(0);
75
+ }
76
+
77
+ /**
78
+ * @param {{
79
+ * log?: (cause: string, detail?: unknown) => void,
80
+ * kill?: (pid: number, signal: NodeJS.Signals) => void,
81
+ * exit?: (code: number) => void,
82
+ * }} [deps]
83
+ */
84
+ export function createRemoteExitHandlers(deps = {}) {
85
+ const log = deps.log || logProcessExit;
86
+ const kill = deps.kill || ((pid, signal) => process.kill(pid, signal));
87
+ const exit = deps.exit || ((code) => process.exit(code));
88
+ return {
89
+ /**
90
+ * Log, then raise the signal again with this handler gone so the
91
+ * default disposition still ends the process.
92
+ * @param {NodeJS.Signals} signal
93
+ */
94
+ onSignal(signal) {
95
+ log(signal);
96
+ kill(process.pid, signal);
97
+ },
98
+ /**
99
+ * A listener replaces Node's default print-and-exit. The message is
100
+ * clipped; the stack is not written because it can carry a request URL.
101
+ * @param {unknown} err
102
+ */
103
+ onUncaught(err) {
104
+ const message = err instanceof Error ? err.message : String(err ?? '');
105
+ log('uncaughtException', message);
106
+ exit(1);
107
+ },
108
+ };
109
+ }
110
+
111
+ /**
112
+ * @param {{
113
+ * log?: (cause: string, detail?: unknown) => void,
114
+ * kill?: (pid: number, signal: NodeJS.Signals) => void,
115
+ * exit?: (code: number) => void,
116
+ * }} [deps]
117
+ * @returns {() => void} remove the listeners
118
+ */
119
+ export function installRemoteProcessExitLogs(deps = {}) {
120
+ const handlers = createRemoteExitHandlers(deps);
121
+ const onTerm = () => {
122
+ process.removeListener('SIGTERM', onTerm);
123
+ handlers.onSignal('SIGTERM');
124
+ };
125
+ const onInt = () => {
126
+ process.removeListener('SIGINT', onInt);
127
+ handlers.onSignal('SIGINT');
128
+ };
129
+ process.once('SIGTERM', onTerm);
130
+ process.once('SIGINT', onInt);
131
+ process.once('uncaughtException', handlers.onUncaught);
132
+ return function uninstall() {
133
+ process.removeListener('SIGTERM', onTerm);
134
+ process.removeListener('SIGINT', onInt);
135
+ process.removeListener('uncaughtException', handlers.onUncaught);
136
+ };
137
+ }
@@ -4,6 +4,7 @@
4
4
  * The bearer token is never logged and is never placed in the URL.
5
5
  */
6
6
 
7
+ import { randomUUID } from 'node:crypto';
7
8
  import { WebSocket } from 'ws';
8
9
  import {
9
10
  AGENT_HANDSHAKE_UPDATE_MESSAGE,
@@ -13,7 +14,9 @@ import {
13
14
  import {
14
15
  asRemoteError,
15
16
  clientUpdateError,
17
+ authErrorFromBody,
16
18
  pairingLostError,
19
+ tokenExpiredError,
17
20
  tokenRevokedError,
18
21
  } from '../errors.mjs';
19
22
  import { PAIR_MSG } from '../relayMessages.mjs';
@@ -44,15 +47,30 @@ function openAuthorizedSocket(wsUrl, token) {
44
47
  };
45
48
  ws.once('unexpected-response', (_req, res) => {
46
49
  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
- }));
50
+ const chunks = [];
51
+ const failStatus = (json) => {
52
+ if (status === 401) {
53
+ fail(authErrorFromBody(json));
54
+ return;
55
+ }
56
+ fail(Object.assign(new Error(`WebSocket upgrade failed (${status})`), {
57
+ code: 'ws_blocked',
58
+ statusCode: status,
59
+ }));
60
+ };
61
+ res.on('data', (chunk) => {
62
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
63
+ });
64
+ res.on('error', () => failStatus(null));
65
+ res.on('end', () => {
66
+ let json = null;
67
+ try {
68
+ json = JSON.parse(Buffer.concat(chunks).toString('utf8'));
69
+ } catch {
70
+ json = null;
71
+ }
72
+ failStatus(json);
73
+ });
56
74
  });
57
75
  ws.once('error', (error) => {
58
76
  const errno = error && typeof error === 'object' ? error.code : '';
@@ -86,6 +104,48 @@ function defaultLog(line) {
86
104
  console.error(`${new Date().toISOString()} [surfcad-mcp] ${line}`);
87
105
  }
88
106
 
107
+ /**
108
+ * Newlines and other controls become spaces so one close stays one log line.
109
+ * @param {string} text
110
+ */
111
+ function singleLine(text) {
112
+ let out = '';
113
+ for (let i = 0; i < text.length; i += 1) {
114
+ out += text.charCodeAt(i) < 32 ? ' ' : text[i];
115
+ }
116
+ return out;
117
+ }
118
+
119
+ /**
120
+ * Close reason for stderr. The bearer, this session's token, a join code,
121
+ * and any other long token-shaped run are removed. Newlines cannot break
122
+ * the line into a second record.
123
+ * @param {Buffer | string | undefined} reason
124
+ * @param {string} [token]
125
+ */
126
+ function clipCloseReason(reason, token) {
127
+ let text = Buffer.isBuffer(reason) ? reason.toString('utf8') : String(reason || '');
128
+ if (token) text = text.split(token).join('');
129
+ text = text.replace(/Bearer\s+\S+/gi, '');
130
+ text = text.replace(/\b[A-Z0-9]{4}-[A-Z0-9]{4}\b/g, '');
131
+ text = text.replace(/\b[A-Za-z0-9_-]{32,}\b/g, '');
132
+ text = singleLine(text).replace(/\s+/g, ' ').trim();
133
+ if (text.length > 120) text = text.slice(0, 120);
134
+ return text;
135
+ }
136
+
137
+ /**
138
+ * @param {number} code
139
+ * @param {Buffer | string | undefined} reason
140
+ * @param {string} [token]
141
+ */
142
+ function formatClose(code, reason, token) {
143
+ const numeric = Number(code);
144
+ const shown = Number.isInteger(numeric) ? numeric : 1006;
145
+ const why = clipCloseReason(reason, token);
146
+ return { code: shown, why };
147
+ }
148
+
89
149
  export class RemoteSession {
90
150
  /** @type {WebSocket | null} */
91
151
  #ws = null;
@@ -102,6 +162,13 @@ export class RemoteSession {
102
162
  #connecting = null;
103
163
  /** @type {{ resolve: () => void, reject: (err: Error) => void } | null} */
104
164
  #hello = null;
165
+ /** Frames that arrived before the hello ack. A prompt must not fail the handshake. */
166
+ #early = [];
167
+ #promptPull = 0;
168
+ /** This process's pull session: GET /agent/prompts offers each held prompt to it once. */
169
+ #pullSession = randomUUID().replace(/-/g, '');
170
+ /** @type {AbortController | null} */
171
+ #promptAbort = null;
105
172
  /** @type {Map<string, { resolve: (v: unknown) => void, reject: (e: Error) => void }>} */
106
173
  #pending = new Map();
107
174
  #log;
@@ -138,6 +205,12 @@ export class RemoteSession {
138
205
  : COMMAND_WAIT_MS;
139
206
  this.#prompts = options.promptSession || createPromptSession({
140
207
  send: (payload) => this.#sendToTab(payload),
208
+ // The server holds a tab prompt until a process reports it taken.
209
+ onTaken: (ids) => {
210
+ Promise.resolve()
211
+ .then(() => this.#sendToTab({ type: PAIR_MSG.AGENT_PROMPT_TAKEN, v: 1, ids }))
212
+ .catch(() => { /* advisory; the next hello or pull offers them again */ });
213
+ },
141
214
  });
142
215
  }
143
216
 
@@ -240,6 +313,7 @@ export class RemoteSession {
240
313
  try {
241
314
  try {
242
315
  await this.#openWebSocket();
316
+ this.#stopPromptPull();
243
317
  this.#transport = 'ws';
244
318
  this.#state = 'paired';
245
319
  this.#log('remote agent connected via websocket');
@@ -247,7 +321,7 @@ export class RemoteSession {
247
321
  } catch (err) {
248
322
  this.#dropSocket();
249
323
  const code = err && typeof err === 'object' ? err.code : '';
250
- if (code === 'token_revoked' || code === 'client_update_required') {
324
+ if (code === 'token_revoked' || code === 'expired' || code === 'client_update_required') {
251
325
  // Stay 'pairing' so a later tool call reaches `call()` and surfaces this error.
252
326
  this.#state = 'pairing';
253
327
  throw err;
@@ -261,6 +335,7 @@ export class RemoteSession {
261
335
  this.#transport = 'http';
262
336
  this.#state = 'paired';
263
337
  this.#log('remote agent connected via https fallback');
338
+ this.#startPromptPull();
264
339
  }
265
340
  } finally {
266
341
  // Success used to leave the settled promise here, so a later connect()
@@ -320,6 +395,7 @@ export class RemoteSession {
320
395
  const ws = this.#ws;
321
396
  this.#ws = null;
322
397
  this.#hello = null;
398
+ this.#early = [];
323
399
  if (!ws) return;
324
400
  ws.removeAllListeners();
325
401
  try { ws.terminate(); } catch { /* noop */ }
@@ -338,12 +414,22 @@ export class RemoteSession {
338
414
  }
339
415
  if (!msg || typeof msg !== 'object') return;
340
416
  if (this.#hello) {
341
- const hello = this.#hello;
342
- this.#hello = null;
343
417
  if (msg.type === 'hello') {
418
+ const hello = this.#hello;
419
+ this.#hello = null;
344
420
  hello.resolve();
421
+ const early = this.#early.splice(0);
422
+ for (const frame of early) this.#dispatchInbound(frame);
345
423
  return;
346
424
  }
425
+ if (msg.type === PAIR_MSG.AGENT_PROMPT || msg.type === PAIR_MSG.AGENT_PROMPT_CANCEL) {
426
+ this.#early.push(msg);
427
+ if (this.#early.length > 20) this.#early.shift();
428
+ return;
429
+ }
430
+ const hello = this.#hello;
431
+ this.#hello = null;
432
+ this.#early = [];
347
433
  const text = typeof msg.error === 'string' ? msg.error : '';
348
434
  hello.reject(asRemoteError({
349
435
  code: text.includes(AGENT_HANDSHAKE_UPDATE_MESSAGE) ? 'client_update_required' : 'ws_blocked',
@@ -351,26 +437,7 @@ export class RemoteSession {
351
437
  }));
352
438
  return;
353
439
  }
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
- try {
362
- this.#sendToTab({
363
- type: PAIR_MSG.AGENT_PROMPT_CANCEL_RESULT,
364
- v: 1,
365
- id: result.id,
366
- state: result.state,
367
- });
368
- } catch {
369
- /* socket closed before the result could be sent */
370
- }
371
- }, () => {});
372
- return;
373
- }
440
+ if (this.#dispatchInbound(msg)) return;
374
441
  const id = msg.id == null ? '' : String(msg.id);
375
442
  const waiter = id ? this.#pending.get(id) : undefined;
376
443
  if (!waiter) return;
@@ -387,13 +454,19 @@ export class RemoteSession {
387
454
  #onClose(code, reason) {
388
455
  const why = Buffer.isBuffer(reason) ? reason.toString('utf8') : String(reason || '');
389
456
  const hello = this.#hello;
457
+ const closed = formatClose(code, reason, this.#token);
458
+ if (hello) {
459
+ const detail = closed.why ? ` ${closed.why}` : '';
460
+ this.#log(`websocket closed before hello (${closed.code})${detail}`);
461
+ }
390
462
  this.#hello = null;
463
+ this.#early = [];
391
464
  this.#ws = null;
392
465
  if (code === TOKEN_CLOSE_CODE) {
393
466
  this.#transport = null;
394
467
  this.#state = 'pairing';
395
468
  this.#connecting = null;
396
- const err = tokenRevokedError();
469
+ const err = why.trim() === 'token expired' ? tokenExpiredError() : tokenRevokedError();
397
470
  if (hello) hello.reject(err);
398
471
  this.#failPending(err);
399
472
  return;
@@ -413,11 +486,110 @@ export class RemoteSession {
413
486
  }
414
487
  if (this.#state === 'paired' && this.#transport === 'ws') {
415
488
  this.#transport = 'http';
416
- this.#log('websocket closed; later commands use https');
489
+ const detail = closed.why ? ` ${closed.why}` : '';
490
+ this.#log(`websocket closed (${closed.code})${detail}; later commands use https`);
417
491
  this.#failPending(pairingLostError('socket closed'));
492
+ this.#startPromptPull();
418
493
  }
419
494
  }
420
495
 
496
+ /**
497
+ * Prompt frames from the agent socket or from GET /agent/prompts.
498
+ * @param {object} msg
499
+ * @returns {boolean} true when this frame was a prompt
500
+ */
501
+ #dispatchInbound(msg) {
502
+ if (msg.type === PAIR_MSG.AGENT_PROMPT) {
503
+ void this.#prompts.acceptPrompt(msg);
504
+ return true;
505
+ }
506
+ if (msg.type === PAIR_MSG.AGENT_PROMPT_CANCEL) {
507
+ const cancelId = typeof msg.id === 'string' ? msg.id : '';
508
+ void this.#prompts.cancel(cancelId).then((result) => {
509
+ Promise.resolve(this.#sendToTab({
510
+ type: PAIR_MSG.AGENT_PROMPT_CANCEL_RESULT,
511
+ v: 1,
512
+ id: result.id,
513
+ state: result.state,
514
+ })).catch(() => {
515
+ /* socket closed before the result could be sent */
516
+ });
517
+ }, () => {});
518
+ return true;
519
+ }
520
+ return false;
521
+ }
522
+
523
+ #stopPromptPull() {
524
+ this.#promptPull += 1;
525
+ const abort = this.#promptAbort;
526
+ this.#promptAbort = null;
527
+ try { abort?.abort(); } catch { /* noop */ }
528
+ }
529
+
530
+ /**
531
+ * HTTPS fallback has no agent socket, so tab prompts are pulled.
532
+ * A websocket session receives them on the socket instead.
533
+ */
534
+ #startPromptPull() {
535
+ this.#log('prompt poll started');
536
+ this.#stopPromptPull();
537
+ const generation = this.#promptPull;
538
+ const run = async () => {
539
+ while (generation === this.#promptPull && this.#state === 'paired' && this.#transport === 'http') {
540
+ try {
541
+ const frames = await this.#pullPromptBatch();
542
+ if (generation !== this.#promptPull) return;
543
+ for (const frame of frames) this.#dispatchInbound(frame);
544
+ } catch (err) {
545
+ if (generation !== this.#promptPull) return;
546
+ const code = err && typeof err === 'object' ? err.code : '';
547
+ if (code === 'token_revoked' || code === 'expired' || code === 'client_update_required') return;
548
+ await new Promise((resolve) => {
549
+ const timer = setTimeout(resolve, 400);
550
+ if (typeof timer.unref === 'function') timer.unref();
551
+ });
552
+ }
553
+ }
554
+ };
555
+ void run();
556
+ }
557
+
558
+ /**
559
+ * @returns {Promise<object[]>}
560
+ */
561
+ async #pullPromptBatch() {
562
+ const ac = new AbortController();
563
+ this.#promptAbort = ac;
564
+ const url = new URL(this.#urls.promptsUrl);
565
+ url.searchParams.set('timeout', '25000');
566
+ url.searchParams.set('session', this.#pullSession);
567
+ let res;
568
+ try {
569
+ res = await this.#fetch(url, {
570
+ method: 'GET',
571
+ headers: { Authorization: `Bearer ${this.#token}` },
572
+ signal: ac.signal,
573
+ });
574
+ } catch {
575
+ if (ac.signal.aborted) return [];
576
+ throw Object.assign(new Error('Could not reach the SurfCAD agent server.'), { code: 'unreachable' });
577
+ }
578
+ if (res.status === 401) {
579
+ let json = null;
580
+ try { json = await res.json(); } catch { json = null; }
581
+ throw authErrorFromBody(json);
582
+ }
583
+ if (!res.ok) {
584
+ try { await res.body?.cancel?.(); } catch { /* noop */ }
585
+ throw Object.assign(new Error(`Prompt pull failed (${res.status})`), { code: 'bridge_error' });
586
+ }
587
+ let json = null;
588
+ try { json = await res.json(); } catch { json = null; }
589
+ const messages = json && Array.isArray(json.messages) ? json.messages : [];
590
+ return messages.filter((frame) => frame && typeof frame === 'object');
591
+ }
592
+
421
593
  /**
422
594
  * @param {Error} err
423
595
  */
@@ -426,20 +598,54 @@ export class RemoteSession {
426
598
  this.#pending.clear();
427
599
  }
428
600
 
601
+ /**
602
+ * Status and prompt frames. A paired WebSocket sends them on the socket.
603
+ * A paired HTTPS fallback (join-code login when wss is blocked, or the
604
+ * socket dropped) POSTs them. Either way a connected session is connected:
605
+ * the caller hears the transport's error, not a collapsed not_paired.
606
+ * @param {object} payload
607
+ */
608
+ async #sendToTab(payload) {
609
+ if (!this.isPaired()) await this.connect();
610
+ if (this.#transport === 'ws' && this.#ws && this.#ws.readyState === WebSocket.OPEN) {
611
+ this.#ws.send(JSON.stringify(payload));
612
+ return;
613
+ }
614
+ if (this.#state === 'paired' && this.#transport === 'http') {
615
+ await this.#postPrompt(payload);
616
+ return;
617
+ }
618
+ throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
619
+ }
620
+
429
621
  /**
430
622
  * @param {object} payload
431
623
  */
432
- #sendToTab(payload) {
433
- if (this.#transport !== 'ws' || !this.#ws || this.#ws.readyState !== WebSocket.OPEN) {
434
- throw Object.assign(
435
- new Error('In-viewer prompts need the agent WebSocket. This session is using the HTTPS fallback.'),
436
- {
437
- code: 'prompts_need_websocket',
438
- hint: 'This session is on the HTTPS fallback because WebSocket was blocked. In-viewer prompts need the WebSocket; retry where the agent server allows wss.',
624
+ async #postPrompt(payload) {
625
+ let res;
626
+ try {
627
+ res = await this.#fetch(this.#urls.promptsUrl, {
628
+ method: 'POST',
629
+ headers: {
630
+ Authorization: `Bearer ${this.#token}`,
631
+ 'Content-Type': 'application/json',
439
632
  },
440
- );
633
+ body: JSON.stringify(payload),
634
+ });
635
+ } catch {
636
+ throw Object.assign(new Error('Could not reach the SurfCAD agent server.'), { code: 'unreachable' });
637
+ }
638
+ if (!res.ok) {
639
+ let json = null;
640
+ try { json = await res.json(); } catch { json = null; }
641
+ if (res.status === 401) throw authErrorFromBody(json);
642
+ const code = typeof json?.error === 'string' && json.error ? json.error : 'bridge_error';
643
+ const message = typeof json?.message === 'string' && json.message
644
+ ? json.message
645
+ : `Prompt send failed (${res.status})`;
646
+ throw Object.assign(new Error(message), { code });
441
647
  }
442
- this.#ws.send(JSON.stringify(payload));
648
+ try { await res.body?.cancel?.(); } catch { /* noop */ }
443
649
  }
444
650
 
445
651
  /**
@@ -493,6 +699,7 @@ export class RemoteSession {
493
699
 
494
700
  disconnect() {
495
701
  this.#connecting = null;
702
+ this.#stopPromptPull();
496
703
  this.#dropSocket();
497
704
  this.#transport = null;
498
705
  this.#state = 'unpaired';