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
@@ -52,7 +52,7 @@ export const BUILDING_STATUS_GUIDANCE = 'Call set_status { state: "building" } o
52
52
  * Session presence. Kept short: it is part of the initialize instructions,
53
53
  * which hosts truncate past 2 KB.
54
54
  */
55
- export const SESSION_PRESENCE_GUIDANCE = 'Be interactive: post_progress while working, especially during long reasoning. A fresh process per tool call is normal and stays present. A long-lived process is optional, never required. Call close_session when done, never on exit.';
55
+ export const SESSION_PRESENCE_GUIDANCE = 'Be interactive: post_progress while working, especially during long reasoning. A fresh process per tool call is normal and stays present. A long-lived process is optional, never required. Never call close_session after a task.';
56
56
 
57
57
  /**
58
58
  * Short form of the in-viewer turn, for the initialize instructions (hosts
@@ -136,7 +136,7 @@ export function promptToolDefinitions() {
136
136
  },
137
137
  {
138
138
  name: 'read_messages',
139
- description: `Read queued user prompts, oldest first, and remove them from the in-memory queue (this acks them). Each prompt is plain text. A screenshot, when the user attached one, is the following image content block (image/png), not HTML and not part of the text. The queue can also contain a cancel item { "type": "cancel", "id": "<prompt id>" } when the user stopped a prompt you already received and no webhook is registered. Stop work on that id. Do not call reply_to_user or set_status for it. Every response includes recent: the last ${PROMPT_QUEUE_CAP} prompts this session received, oldest first, each { id, state } (queued, delivered, replied, or cancelled), held in memory only. A remote session returns that same recent list; an idle session that has not received a prompt has recent: []. acked is only the ids this call removed. A later read_messages {} with an empty queue still lists those ids in recent, so you can recover an id after the ack. status.last is only the newest id. ${USER_CONTENT} Do not render the text or the image as HTML. read_messages is a poll, not activity: with or without wait_ms it keeps the session connected but does not restart the stall window and does not change what the tab shows. When you finish the task from a prompt you received here, close that chat: ${CLOSING_REPLY_GUIDANCE} ${PROMPT_TURN_GUIDANCE}`,
139
+ description: `Read queued user prompts, oldest first, and remove them from the in-memory queue (this acks them). Each prompt is plain text. An image the user attached (a screenshot of the model, or a photo from their camera or library) is the following image content block (image/png), not HTML and not part of the text. A message can carry up to four images: they follow it as consecutive image blocks in the order the user attached them, and the message says image_count when there is more than one. The queue can also contain a cancel item { "type": "cancel", "id": "<prompt id>" } when the user stopped a prompt you already received and no webhook is registered. Stop work on that id. Do not call reply_to_user or set_status for it. Every response includes recent: the last ${PROMPT_QUEUE_CAP} prompts this session received, oldest first, each { id, state } (queued, delivered, replied, or cancelled), held in memory only. A remote session returns that same recent list; an idle session that has not received a prompt has recent: []. acked is only the ids this call removed. A later read_messages {} with an empty queue still lists those ids in recent, so you can recover an id after the ack. status.last is only the newest id. ${USER_CONTENT} Do not render the text or the image as HTML. read_messages is a poll, not activity: with or without wait_ms it keeps the session connected but does not restart the stall window and does not change what the tab shows. When you finish the task from a prompt you received here, close that chat: ${CLOSING_REPLY_GUIDANCE} ${PROMPT_TURN_GUIDANCE}`,
140
140
  inputSchema: {
141
141
  type: 'object',
142
142
  additionalProperties: false,
@@ -158,7 +158,7 @@ export function promptToolDefinitions() {
158
158
  },
159
159
  {
160
160
  name: 'reply_to_user',
161
- description: `${CLOSING_REPLY_GUIDANCE} The final reply is expected: it closes the task in the chat. Send a plain-text reply to the SurfCAD user for a prompt id this session received. Several replies may share one id, including non-final replies and a final reply after read_messages has acked that prompt. Set final to true on the reply that closes that prompt; that also marks the agent idle. Omit in_reply_to to post one plain-text message to this paired session when no prompt is waiting. That note is not a prompt id, is limited to one per second, and does not close a prompt. The text is delivered as text, never rendered as HTML. This does not write the model or git. An in_reply_to that was never delivered to this session is an error unknown_prompt and nothing is sent to the tab. A cancelled id returns { "ok": false, "error": "cancelled" } and is not delivered.`,
161
+ description: `${CLOSING_REPLY_GUIDANCE} The final reply is expected: it closes the task in the chat. Send a plain-text reply for a prompt id that belongs to this paired chat, including one read_messages returned in this process or in another (a wake run or a one-shot surfcad-mcp call). Several replies may share one id, including non-final replies and a final reply after read_messages has acked that prompt. Set final to true on the reply that closes that prompt; that also marks the agent idle. Omit in_reply_to to post one plain-text message to this paired session when no prompt is waiting. That note is not a prompt id, is limited to one per second, and does not close a prompt. The text is delivered as text, never rendered as HTML. This does not write the model or git. An in_reply_to that does not exist, or that belongs to someone else, is an error unknown_prompt and nothing is sent to the tab. A cancelled id returns { "ok": false, "error": "cancelled" } and is not delivered.`,
162
162
  inputSchema: {
163
163
  type: 'object',
164
164
  additionalProperties: false,
@@ -166,7 +166,7 @@ export function promptToolDefinitions() {
166
166
  properties: {
167
167
  in_reply_to: {
168
168
  type: 'string',
169
- description: 'Prompt id this reply answers. Omit it to post a session message with no prompt. When set, it must be a prompt this session received (the id you were given, or one listed in read_messages recent). Any other id is unknown_prompt.',
169
+ description: 'Prompt id this reply answers. Omit it to post a session message with no prompt. When set, it must belong to this paired chat: the id from read_messages, from the wake payload, or from an earlier session that read it. An id that does not exist, or that belongs to someone else, is unknown_prompt.',
170
170
  },
171
171
  text: {
172
172
  type: 'string',
@@ -224,7 +224,7 @@ export function promptToolDefinitions() {
224
224
  },
225
225
  {
226
226
  name: 'close_session',
227
- description: 'End this SurfCAD agent session. Call it once when you are done. The server marks the agent offline immediately. Do not call it on process exit, stdin end, or SIGTERM. A later tool call can start a new session.',
227
+ description: 'Rarely needed: do not call it after a task, the user may answer minutes later. It shows the agent offline in the tab now instead of after 10 minutes with no activity. Chat messages waiting for you are kept for the next agent call, not dropped. Never call it on process exit, stdin end, or SIGTERM. A later tool call starts a new session.',
228
228
  inputSchema: {
229
229
  type: 'object',
230
230
  additionalProperties: false,
@@ -255,7 +255,7 @@ export async function callPromptTool(prompts, name, args) {
255
255
  }
256
256
  if (wait > 0 && typeof prompts.waitForMessage === 'function') await prompts.waitForMessage(wait);
257
257
  }
258
- const { messages, images } = prompts.readMessages(args.max);
258
+ const { messages, images, extraImages } = prompts.readMessages(args.max);
259
259
  const recent = typeof prompts.recentPrompts === 'function' ? prompts.recentPrompts() : [];
260
260
  if (messages.length === 0) {
261
261
  return {
@@ -270,6 +270,10 @@ export async function callPromptTool(prompts, name, args) {
270
270
  content.push({ type: 'text', text: JSON.stringify(row, null, 2) });
271
271
  const image = images[i];
272
272
  if (image) content.push({ type: 'image', data: image.data, mimeType: image.mimeType });
273
+ // The message's other images, in the order the user attached them.
274
+ for (const extra of extraImages?.[i] || []) {
275
+ content.push({ type: 'image', data: extra.data, mimeType: extra.mimeType });
276
+ }
273
277
  }
274
278
  content.push({ type: 'text', text: JSON.stringify({ acked, recent }, null, 2) });
275
279
  return { content };
@@ -0,0 +1,69 @@
1
+ /**
2
+ * The relay answers `agent.reply` with `agent.reply.result`. A new process
3
+ * does not know which prompt ids this chat has sent, so it waits for that
4
+ * answer instead of trusting the id's shape. An older relay that never
5
+ * answers is treated as success after a short wait: it still forwards the
6
+ * reply, which is what those servers do for every id.
7
+ */
8
+ import { PAIR_MSG } from '../relayMessages.mjs';
9
+
10
+ export const REPLY_CONFIRM_MS = 800;
11
+
12
+ /**
13
+ * @param {Map<string, { resolve: () => void, reject: (err: Error) => void, timer: ReturnType<typeof setTimeout> }>} waiters
14
+ * @param {object} payload
15
+ * @param {number} [timeoutMs]
16
+ * @returns {Promise<void> | null}
17
+ */
18
+ export function armReplyConfirm(waiters, payload, timeoutMs = REPLY_CONFIRM_MS) {
19
+ if (!payload || payload.type !== PAIR_MSG.AGENT_REPLY || typeof payload.id !== 'string' || !payload.id) {
20
+ return null;
21
+ }
22
+ const id = payload.id;
23
+ return new Promise((resolve, reject) => {
24
+ const timer = setTimeout(() => {
25
+ waiters.delete(id);
26
+ resolve();
27
+ }, timeoutMs);
28
+ if (typeof timer.unref === 'function') timer.unref();
29
+ waiters.set(id, { resolve, reject, timer });
30
+ });
31
+ }
32
+
33
+ /**
34
+ * @param {Map<string, { resolve: () => void, reject: (err: Error) => void, timer: ReturnType<typeof setTimeout> }>} waiters
35
+ * @param {object} msg
36
+ * @returns {boolean} true when this frame was a reply result (handled or ignored)
37
+ */
38
+ export function settleReplyConfirm(waiters, msg) {
39
+ if (!msg || msg.type !== PAIR_MSG.AGENT_REPLY_RESULT) return false;
40
+ const id = typeof msg.id === 'string' ? msg.id : '';
41
+ if (!id) return true;
42
+ const waiter = waiters.get(id);
43
+ if (!waiter) return true;
44
+ waiters.delete(id);
45
+ clearTimeout(waiter.timer);
46
+ if (msg.ok === false) {
47
+ const code = typeof msg.error === 'string' && msg.error ? msg.error : 'unknown_prompt';
48
+ waiter.reject(Object.assign(new Error(
49
+ code === 'unknown_prompt'
50
+ ? 'in_reply_to is not a prompt in this paired chat'
51
+ : 'Reply was refused',
52
+ ), { code }));
53
+ } else {
54
+ waiter.resolve();
55
+ }
56
+ return true;
57
+ }
58
+
59
+ /**
60
+ * @param {Map<string, { resolve: () => void, reject: (err: Error) => void, timer: ReturnType<typeof setTimeout> }>} waiters
61
+ * @param {Error} err
62
+ */
63
+ export function failReplyConfirms(waiters, err) {
64
+ for (const waiter of waiters.values()) {
65
+ clearTimeout(waiter.timer);
66
+ waiter.reject(err);
67
+ }
68
+ waiters.clear();
69
+ }
@@ -1,7 +1,10 @@
1
1
  /**
2
2
  * Wire message types for the SurfCAD M1 agent-bridge relay (browser tab ↔ local peer).
3
- * Kept in sync with `src/agent/ws/relayHub.js` in the SurfCAD monorepo.
3
+ * Kept in sync with `src/agent/ws/relayMessages.js` in the SurfCAD monorepo.
4
4
  */
5
+ /** Largest agent.prompt frame the server will forward, in characters. */
6
+ export const DEFAULT_MAX_AGENT_PROMPT_FRAME_CHARS = 4 * 1024 * 1024;
7
+
5
8
  export const PAIR_MSG = Object.freeze({
6
9
  ERROR: 'error',
7
10
  REGISTER_TAB: 'register_tab',
@@ -19,6 +22,12 @@ export const PAIR_MSG = Object.freeze({
19
22
  AGENT_PROMPT_ACK: 'agent.prompt.ack',
20
23
  /** Agent → page. Contract v:1. Several replies may share one prompt id. */
21
24
  AGENT_REPLY: 'agent.reply',
25
+ /**
26
+ * Relay → agent. Contract v:1. `{ id, ok, error? }`. The reply was
27
+ * forwarded (`ok`) or refused (`unknown_prompt`) because the id is not
28
+ * in this paired chat. Not forwarded to the page.
29
+ */
30
+ AGENT_REPLY_RESULT: 'agent.reply.result',
22
31
  /** Agent → page. Contract v:1. A plain-text note for this paired session, with no prompt id. */
23
32
  AGENT_MESSAGE: 'agent.message',
24
33
  /** Agent → page. Contract v:1. */
@@ -40,3 +49,36 @@ export const PAIR_MSG = Object.freeze({
40
49
  */
41
50
  AGENT_PROMPT_TAKEN: 'agent.prompt.taken',
42
51
  });
52
+
53
+ /**
54
+ * Newest prompt ids kept per paired chat. Older than this, a reply is
55
+ * `unknown_prompt`. The text is not stored. Lives in this file because the
56
+ * backend deploy already ships it (BE_SHARED); a new module would not.
57
+ */
58
+ export const KNOWN_PROMPT_CAP = 2000;
59
+
60
+ /**
61
+ * @param {Map<string, true> | null | undefined} ids
62
+ * @param {unknown} id
63
+ * @param {number} [cap]
64
+ * @returns {boolean}
65
+ */
66
+ export function rememberPromptId(ids, id, cap = KNOWN_PROMPT_CAP) {
67
+ if (!(ids instanceof Map)) return false;
68
+ if (typeof id !== 'string' || !id || id.length > 80) return false;
69
+ ids.delete(id);
70
+ ids.set(id, true);
71
+ while (ids.size > cap) {
72
+ const oldest = ids.keys().next().value;
73
+ ids.delete(oldest);
74
+ }
75
+ return true;
76
+ }
77
+
78
+ /**
79
+ * @param {Map<string, true> | null | undefined} ids
80
+ * @param {unknown} id
81
+ */
82
+ export function promptIdKnown(ids, id) {
83
+ return ids instanceof Map && typeof id === 'string' && id.length > 0 && ids.has(id);
84
+ }
@@ -1,6 +1,9 @@
1
1
  /**
2
- * Remote relay address, agent name, and local-vs-remote selection.
2
+ * Server relay address and agent name.
3
3
  * The token never appears in these helpers.
4
+ *
5
+ * The loopback relay was removed in 0.4.0. `--local` and the old loopback
6
+ * env vars are refused so a saved config does not silently do nothing.
4
7
  */
5
8
 
6
9
  import { homedir } from 'node:os';
@@ -150,29 +153,30 @@ function explicitLocalRelay(env) {
150
153
  return false;
151
154
  }
152
155
 
156
+ const LOCAL_RELAY_REMOVED = 'The local relay was removed in surfcad-mcp 0.4.0. Run npx surfcad-mcp login --code CODE.';
157
+
153
158
  /**
154
- * First match wins:
155
- * 1. `--remote` → remote
156
- * 2. `--local` → local
157
- * 3. an explicit loopback URL, port, or pairing code → local
158
- * 4. a saved login → remote
159
- * 5. local
159
+ * Stdio always uses the server relay. A saved login is required; the CLI
160
+ * reports a missing one. `--local` and the old loopback env vars are errors.
161
+ * `--remote` is accepted and changes nothing.
160
162
  * @param {{
161
163
  * remote?: boolean,
162
164
  * local?: boolean,
163
165
  * loggedIn?: boolean,
164
166
  * env?: NodeJS.ProcessEnv,
165
167
  * }} [options]
166
- * @returns {{ ok: true, mode: 'local' | 'remote' } | { ok: false, error: string }}
168
+ * @returns {{ ok: true, mode: 'remote' } | { ok: false, error: string }}
167
169
  */
168
170
  export function selectRelayMode(options = {}) {
169
171
  const env = options.env || process.env;
170
172
  if (options.remote && options.local) {
171
173
  return { ok: false, error: 'Pass either --remote or --local, not both.' };
172
174
  }
173
- if (options.remote) return { ok: true, mode: 'remote' };
174
- if (options.local) return { ok: true, mode: 'local' };
175
- if (explicitLocalRelay(env)) return { ok: true, mode: 'local' };
176
- if (options.loggedIn) return { ok: true, mode: 'remote' };
177
- return { ok: true, mode: 'local' };
175
+ const transport = typeof env.SURFCAD_MCP_TRANSPORT === 'string'
176
+ ? env.SURFCAD_MCP_TRANSPORT.trim().toLowerCase()
177
+ : '';
178
+ if (options.local || transport === 'local' || explicitLocalRelay(env)) {
179
+ return { ok: false, error: LOCAL_RELAY_REMOVED };
180
+ }
181
+ return { ok: true, mode: 'remote' };
178
182
  }
@@ -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 { releaseOwner } from '../listen/owner.mjs';
7
8
  import { randomUUID } from 'node:crypto';
8
9
  import { WebSocket } from 'ws';
9
10
  import {
@@ -21,12 +22,24 @@ import {
21
22
  } from '../errors.mjs';
22
23
  import { PAIR_MSG } from '../relayMessages.mjs';
23
24
  import { createPromptSession } from '../prompt/promptSession.mjs';
25
+ import { armReplyConfirm, failReplyConfirms, settleReplyConfirm } from '../prompt/replyConfirm.mjs';
24
26
  import { agentUrls, resolveAgentName } from './config.mjs';
25
27
  import { callOverHttp, COMMAND_WAIT_MS, commandWaitTimeout, resultFromCommandResponse } from './httpFallback.mjs';
26
28
 
27
29
  /** Server relay closes a revoked or expired token with this code. */
28
30
  const TOKEN_CLOSE_CODE = 4001;
29
31
  const HELLO_TIMEOUT_MS = 8000;
32
+ /**
33
+ * Incoming frame cap on this client. The server relay's cap is the one that
34
+ * drops a tab socket; this stays above it so a `list_edges` result the
35
+ * server accepted is not dropped here. `ws` defaults to 100 MB.
36
+ */
37
+ const AGENT_WS_MAX_PAYLOAD = 64 * 1024 * 1024;
38
+ /**
39
+ * How long `close()` waits for frames on their way out (the "taken" report,
40
+ * the close handshake) before it drops the socket anyway.
41
+ */
42
+ const CLOSE_FLUSH_MS = 3000;
30
43
 
31
44
  /**
32
45
  * @param {string} wsUrl
@@ -37,6 +50,7 @@ function openAuthorizedSocket(wsUrl, token) {
37
50
  const ws = new WebSocket(wsUrl, {
38
51
  headers: { Authorization: `Bearer ${token}` },
39
52
  handshakeTimeout: HELLO_TIMEOUT_MS,
53
+ maxPayload: AGENT_WS_MAX_PAYLOAD,
40
54
  });
41
55
  let settled = false;
42
56
  const fail = (err) => {
@@ -171,6 +185,14 @@ export class RemoteSession {
171
185
  #promptAbort = null;
172
186
  /** @type {Map<string, { resolve: (v: unknown) => void, reject: (e: Error) => void }>} */
173
187
  #pending = new Map();
188
+ /** @type {Map<string, { resolve: () => void, reject: (err: Error) => void, timer: ReturnType<typeof setTimeout> }>} */
189
+ #replyWaiters = new Map();
190
+ /**
191
+ * Sends nobody awaits (the "taken" report, a cancel result). `close()`
192
+ * waits for them, so a one-shot process does not exit with one unsent.
193
+ * @type {Set<Promise<void>>}
194
+ */
195
+ #outbound = new Set();
174
196
  #log;
175
197
  #fetch;
176
198
  #commandTimeoutMs;
@@ -205,11 +227,12 @@ export class RemoteSession {
205
227
  : COMMAND_WAIT_MS;
206
228
  this.#prompts = options.promptSession || createPromptSession({
207
229
  send: (payload) => this.#sendToTab(payload),
230
+ confirmReplies: true,
208
231
  // The server holds a tab prompt until a process reports it taken.
209
232
  onTaken: (ids) => {
210
- Promise.resolve()
233
+ this.#track(Promise.resolve()
211
234
  .then(() => this.#sendToTab({ type: PAIR_MSG.AGENT_PROMPT_TAKEN, v: 1, ids }))
212
- .catch(() => { /* advisory; the next hello or pull offers them again */ });
235
+ .catch(() => { /* advisory; the next hello or pull offers them again */ }));
213
236
  },
214
237
  onUnread: options.onUnread,
215
238
  });
@@ -438,6 +461,7 @@ export class RemoteSession {
438
461
  }));
439
462
  return;
440
463
  }
464
+ if (settleReplyConfirm(this.#replyWaiters, msg)) return;
441
465
  if (this.#dispatchInbound(msg)) return;
442
466
  const id = msg.id == null ? '' : String(msg.id);
443
467
  const waiter = id ? this.#pending.get(id) : undefined;
@@ -500,13 +524,19 @@ export class RemoteSession {
500
524
  * @returns {boolean} true when this frame was a prompt
501
525
  */
502
526
  #dispatchInbound(msg) {
527
+ if (msg.type === 'agent.chat.reset') {
528
+ // The person deleted the chat history: this machine's chat owner lets
529
+ // go, and the next message starts a new session.
530
+ void releaseOwner(process.env).catch(() => {});
531
+ return true;
532
+ }
503
533
  if (msg.type === PAIR_MSG.AGENT_PROMPT) {
504
534
  void this.#prompts.acceptPrompt(msg);
505
535
  return true;
506
536
  }
507
537
  if (msg.type === PAIR_MSG.AGENT_PROMPT_CANCEL) {
508
538
  const cancelId = typeof msg.id === 'string' ? msg.id : '';
509
- void this.#prompts.cancel(cancelId).then((result) => {
539
+ this.#track(this.#prompts.cancel(cancelId).then((result) => (
510
540
  Promise.resolve(this.#sendToTab({
511
541
  type: PAIR_MSG.AGENT_PROMPT_CANCEL_RESULT,
512
542
  v: 1,
@@ -514,8 +544,8 @@ export class RemoteSession {
514
544
  state: result.state,
515
545
  })).catch(() => {
516
546
  /* socket closed before the result could be sent */
517
- });
518
- }, () => {});
547
+ })
548
+ ), () => {}));
519
549
  return true;
520
550
  }
521
551
  return false;
@@ -597,6 +627,7 @@ export class RemoteSession {
597
627
  #failPending(err) {
598
628
  for (const waiter of this.#pending.values()) waiter.reject(err);
599
629
  this.#pending.clear();
630
+ failReplyConfirms(this.#replyWaiters, err);
600
631
  }
601
632
 
602
633
  /**
@@ -609,7 +640,9 @@ export class RemoteSession {
609
640
  async #sendToTab(payload) {
610
641
  if (!this.isPaired()) await this.connect();
611
642
  if (this.#transport === 'ws' && this.#ws && this.#ws.readyState === WebSocket.OPEN) {
643
+ const pending = armReplyConfirm(this.#replyWaiters, payload);
612
644
  this.#ws.send(JSON.stringify(payload));
645
+ if (pending) await pending;
613
646
  return;
614
647
  }
615
648
  if (this.#state === 'paired' && this.#transport === 'http') {
@@ -698,6 +731,71 @@ export class RemoteSession {
698
731
  });
699
732
  }
700
733
 
734
+ /**
735
+ * @param {Promise<unknown>} sending never rejects
736
+ */
737
+ #track(sending) {
738
+ const entry = sending.then(() => {}, () => {});
739
+ this.#outbound.add(entry);
740
+ void entry.then(() => this.#outbound.delete(entry));
741
+ }
742
+
743
+ /**
744
+ * Everything on its way to the server has arrived: the untracked sends
745
+ * have settled (over HTTPS that is the POST's answer), and on a websocket
746
+ * the closing handshake is done. `ws` writes the close frame after every
747
+ * queued frame and the server answers it after reading up to it, so its
748
+ * close is the receipt for all of them.
749
+ */
750
+ async #flushOutbound() {
751
+ while (this.#outbound.size > 0) {
752
+ await Promise.all([...this.#outbound]);
753
+ }
754
+ const ws = this.#ws;
755
+ if (!ws || ws.readyState !== WebSocket.OPEN) return;
756
+ // This session is leaving: its own close handler would fall back to
757
+ // HTTPS and start a prompt pull.
758
+ ws.removeAllListeners('close');
759
+ await new Promise((resolve) => {
760
+ ws.once('close', () => resolve(undefined));
761
+ try {
762
+ ws.close(1000);
763
+ } catch {
764
+ resolve(undefined);
765
+ }
766
+ });
767
+ }
768
+
769
+ /**
770
+ * Leave without losing a frame. `disconnect()` alone terminates the
771
+ * socket, and a one-shot process (`surfcad-mcp call`) then exits: a
772
+ * "taken" report sent a moment earlier could be dropped, and the server
773
+ * offered the same prompt to the next process. This waits, up to
774
+ * `timeoutMs`, for the pending sends and the closing handshake, then
775
+ * disconnects (the hard close is the fallback).
776
+ * @param {{ timeoutMs?: number }} [options]
777
+ */
778
+ async close(options = {}) {
779
+ const timeoutMs = Number.isFinite(options.timeoutMs) && options.timeoutMs >= 0
780
+ ? options.timeoutMs
781
+ : CLOSE_FLUSH_MS;
782
+ /** @type {ReturnType<typeof setTimeout> | undefined} */
783
+ let timer;
784
+ const expired = new Promise((resolve) => {
785
+ timer = setTimeout(() => resolve('timeout'), timeoutMs);
786
+ });
787
+ let flushed = false;
788
+ try {
789
+ flushed = (await Promise.race([this.#flushOutbound().then(() => 'flushed'), expired])) === 'flushed';
790
+ } catch {
791
+ /* the hard close below is the fallback */
792
+ } finally {
793
+ clearTimeout(timer);
794
+ this.disconnect();
795
+ }
796
+ return { flushed };
797
+ }
798
+
701
799
  disconnect() {
702
800
  this.#connecting = null;
703
801
  this.#stopPromptPull();