surfcad-mcp 0.3.4 → 0.3.6

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.
@@ -125,13 +125,28 @@ function defaultSetTimer(fn, ms) {
125
125
  * rateLimitMs?: number,
126
126
  * idleMs?: number,
127
127
  * webhookTimeoutMs?: number,
128
+ * onTaken?: (ids: string[]) => void,
128
129
  * }} options
130
+ * `onTaken` fires with the prompt ids the agent now has (read_messages
131
+ * returned them, or the webhook POST succeeded). The server relay holds a
132
+ * prompt until it hears this, so a one-shot process that exits before
133
+ * reading does not lose it.
129
134
  */
130
135
  export function createPromptSession(options) {
131
136
  if (!options || typeof options.send !== 'function') {
132
137
  throw new TypeError('createPromptSession requires send');
133
138
  }
134
139
  const send = options.send;
140
+ const onTaken = typeof options.onTaken === 'function' ? options.onTaken : null;
141
+ /** @param {string[]} ids */
142
+ function noteTaken(ids) {
143
+ if (!onTaken || ids.length === 0) return;
144
+ try {
145
+ onTaken(ids);
146
+ } catch {
147
+ /* advisory */
148
+ }
149
+ }
135
150
  const now = options.now || (() => Date.now());
136
151
  const setTimer = options.setTimer || defaultSetTimer;
137
152
  const clearTimer = options.clearTimer || ((timer) => clearTimeout(/** @type {ReturnType<typeof setTimeout>} */ (timer)));
@@ -173,6 +188,8 @@ export function createPromptSession(options) {
173
188
  let promptEpoch = 0;
174
189
  let workedEpoch = 0;
175
190
  let lastAcceptedAt = -Infinity;
191
+ /** Last unsolicited session message. Separate from prompt accepts. */
192
+ let lastSessionAt = -Infinity;
176
193
  /** @type {string | null} */
177
194
  let lastId = null;
178
195
  /** @type {unknown} */
@@ -485,6 +502,7 @@ export function createPromptSession(options) {
485
502
  if (posted === 'sent') {
486
503
  remember(prompt.id, 'delivered');
487
504
  emit(ack(prompt.id, 'webhook'));
505
+ noteTaken([prompt.id]);
488
506
  return;
489
507
  }
490
508
  }
@@ -535,6 +553,15 @@ export function createPromptSession(options) {
535
553
  }
536
554
  screenshot = shot.value;
537
555
  }
556
+ // The server relay offers a held prompt to every new socket or pull
557
+ // session until one reports it taken, so the same id can arrive again
558
+ // (a reconnect in this process). Keep the copy this process has.
559
+ const known = states.get(id);
560
+ if (known) {
561
+ if (known === 'queued') emit(ack(id, 'queued'));
562
+ else if (known === 'delivered' || known === 'replied') noteTaken([id]);
563
+ return;
564
+ }
538
565
  const at = now();
539
566
  if (at - lastAcceptedAt < rateLimitMs) {
540
567
  failAck('rate_limited');
@@ -610,6 +637,7 @@ export function createPromptSession(options) {
610
637
  const taken = queue.splice(0, count);
611
638
  const messages = [];
612
639
  const images = [];
640
+ const takenIds = [];
613
641
  for (const item of taken) {
614
642
  if (item.kind === 'cancel') {
615
643
  messages.push({ type: 'cancel', id: item.id });
@@ -617,6 +645,7 @@ export function createPromptSession(options) {
617
645
  continue;
618
646
  }
619
647
  if (states.get(item.id) === 'queued') states.set(item.id, 'delivered');
648
+ takenIds.push(item.id);
620
649
  messages.push({
621
650
  v: 1,
622
651
  id: item.id,
@@ -638,29 +667,83 @@ export function createPromptSession(options) {
638
667
  : null);
639
668
  }
640
669
  noteActivity();
670
+ noteTaken(takenIds);
641
671
  return { messages, images };
642
672
  }
643
673
 
644
674
  /**
645
- * @param {{ in_reply_to?: unknown, text?: unknown, final?: unknown }} args
675
+ * Plain text for a reply or a session note. Not parsed as HTML.
676
+ * @param {unknown} text
646
677
  */
647
- function reply(args) {
648
- const inReplyTo = args?.in_reply_to;
649
- const text = args?.text;
650
- if (typeof inReplyTo !== 'string' || !inReplyTo || inReplyTo.length > 80) {
651
- throw Object.assign(new Error('in_reply_to is required'), { code: 'bad_args' });
652
- }
678
+ function requireReplyText(text) {
653
679
  if (typeof text !== 'string' || text.length === 0) {
654
680
  throw Object.assign(new Error('Reply text is required'), { code: 'bad_args' });
655
681
  }
656
682
  if (text.length > PROMPT_REPLY_MAX) {
657
683
  throw Object.assign(new Error('Reply text is too long'), { code: 'reply_too_long' });
658
684
  }
659
- // Only a prompt this session accepted. Checked before any send, so an
660
- // invented id never becomes an agent.reply on the tab.
661
- const state = states.get(inReplyTo);
685
+ return text;
686
+ }
687
+
688
+ /**
689
+ * A note for this paired session, with no prompt id. The page shows it
690
+ * as its own chat bubble. One per rate window. Does not touch prompt state.
691
+ * @param {unknown} raw
692
+ */
693
+ function postSessionMessage(raw) {
694
+ const run = chain.then(() => postSessionNow(raw));
695
+ chain = run.then(() => {}, () => {});
696
+ return run;
697
+ }
698
+
699
+ /**
700
+ * @param {unknown} raw
701
+ */
702
+ function postSessionNow(raw) {
703
+ const text = requireReplyText(raw);
704
+ const at = now();
705
+ if (at - lastSessionAt < rateLimitMs) {
706
+ throw Object.assign(new Error('Too many messages'), { code: 'rate_limited' });
707
+ }
708
+ const sent = emit({
709
+ type: PAIR_MSG.AGENT_MESSAGE,
710
+ v: 1,
711
+ text,
712
+ ts: new Date(at).toISOString(),
713
+ }, { required: true });
714
+ const finish = () => {
715
+ lastSessionAt = at;
716
+ return { ok: true, session: true };
717
+ };
718
+ if (sent && typeof sent.then === 'function') {
719
+ return sent.then(finish);
720
+ }
721
+ if (!sent) throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
722
+ return finish();
723
+ }
724
+
725
+ /**
726
+ * @param {{ in_reply_to?: unknown, text?: unknown, final?: unknown }} args
727
+ */
728
+ function reply(args) {
729
+ if (args?.in_reply_to == null) return postSessionMessage(args?.text);
730
+ const inReplyTo = args.in_reply_to;
731
+ const text = requireReplyText(args?.text);
732
+ if (typeof inReplyTo !== 'string' || !inReplyTo || inReplyTo.length > 80) {
733
+ throw Object.assign(new Error('in_reply_to is required'), { code: 'bad_args' });
734
+ }
735
+ // A prompt this session accepted, or a prompt id from an earlier
736
+ // one-shot process (a fresh surfcad-mcp per tool call reads in one
737
+ // process and replies from the next). Anything that is not a prompt id
738
+ // is refused before any send. The page drops a reply for an id it never
739
+ // sent, so an invented UUID cannot become a bubble.
740
+ let state = states.get(inReplyTo);
662
741
  if (!state) {
663
- throw Object.assign(new Error('in_reply_to is not a prompt delivered to this session'), { code: 'unknown_prompt' });
742
+ if (!UUID_RE.test(inReplyTo)) {
743
+ throw Object.assign(new Error('in_reply_to is not a prompt delivered to this session'), { code: 'unknown_prompt' });
744
+ }
745
+ remember(inReplyTo, 'delivered');
746
+ state = 'delivered';
664
747
  }
665
748
  if (state === 'cancelled') {
666
749
  return { ok: false, error: 'cancelled' };
@@ -733,6 +816,36 @@ export function createPromptSession(options) {
733
816
  return payload;
734
817
  }
735
818
 
819
+ /**
820
+ * Working signal only. Optional text is accepted and never sent.
821
+ * @param {{ text?: unknown }} [args]
822
+ */
823
+ function postProgress(args = {}) {
824
+ if (args?.text != null && typeof args.text !== 'string') {
825
+ throw Object.assign(new Error('text must be a string'), { code: 'bad_args' });
826
+ }
827
+ if (typeof args?.text === 'string' && args.text.length > 500) {
828
+ throw Object.assign(new Error('text must be at most 500 characters'), { code: 'bad_args' });
829
+ }
830
+ const sent = emit({ type: PAIR_MSG.AGENT_PROGRESS, v: 1, working: true }, { required: true });
831
+ const payload = { ok: true, working: true };
832
+ if (sent && typeof sent.then === 'function') return sent.then(() => payload);
833
+ if (!sent) throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
834
+ return payload;
835
+ }
836
+
837
+ /**
838
+ * Deliberate end of the session. Not called from process exit, stdin
839
+ * end, or SIGTERM.
840
+ */
841
+ function closeSession() {
842
+ const sent = emit({ type: PAIR_MSG.AGENT_CLOSE_SESSION, v: 1 }, { required: true });
843
+ const payload = { ok: true, closed: true };
844
+ if (sent && typeof sent.then === 'function') return sent.then(() => payload);
845
+ if (!sent) throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
846
+ return payload;
847
+ }
848
+
736
849
  /**
737
850
  * A tool call after a prompt. A call that changes the model (`mutates`)
738
851
  * enters building if the agent has not already, so a missed set_status
@@ -809,6 +922,7 @@ export function createPromptSession(options) {
809
922
  promptEpoch = 0;
810
923
  workedEpoch = 0;
811
924
  lastAcceptedAt = -Infinity;
925
+ lastSessionAt = -Infinity;
812
926
  lastId = null;
813
927
  clearIdle();
814
928
  }
@@ -821,6 +935,8 @@ export function createPromptSession(options) {
821
935
  recentPrompts,
822
936
  reply,
823
937
  setStatus,
938
+ postProgress,
939
+ closeSession,
824
940
  noteToolCall,
825
941
  holdWork,
826
942
  registerWebhook,
@@ -25,11 +25,17 @@ export const CLOSING_REPLY_GUIDANCE = 'When you finish a task started from the S
25
25
  */
26
26
  export const BUILDING_STATUS_GUIDANCE = 'Call set_status { state: "building" } only once you have everything you need and are actually creating or editing geometry.';
27
27
 
28
+ /**
29
+ * Session presence. Kept short: it is part of the initialize instructions,
30
+ * which hosts truncate past 2 KB.
31
+ */
32
+ 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.';
33
+
28
34
  /**
29
35
  * First paragraph of the MCP initialize `instructions`.
30
36
  * Goldens pin the webhook sentence as the prefix.
31
37
  */
32
- export const PROMPT_SERVER_INSTRUCTIONS = `call register_webhook { url, bearer? } if you can receive https webhooks, otherwise poll read_messages. ${CLOSING_REPLY_GUIDANCE} ${BUILDING_STATUS_GUIDANCE}`;
38
+ export const PROMPT_SERVER_INSTRUCTIONS = `call register_webhook { url, bearer? } if you can receive https webhooks, otherwise poll read_messages. ${CLOSING_REPLY_GUIDANCE} ${BUILDING_STATUS_GUIDANCE} ${SESSION_PRESENCE_GUIDANCE}`;
33
39
 
34
40
  /** Exact wording the agent should relay when asking the user for a webhook. */
35
41
  export const PROMPT_ONBOARDING_ASK = 'To get SurfCAD messages instantly, send me your webhook URL and key. This only needs to be done once. Otherwise I\'ll check for SurfCAD messages between steps, so replies may lag.';
@@ -49,6 +55,8 @@ export const PROMPT_TOOL_NAMES = Object.freeze([
49
55
  'read_messages',
50
56
  'reply_to_user',
51
57
  'set_status',
58
+ 'post_progress',
59
+ 'close_session',
52
60
  ]);
53
61
 
54
62
  const PROMPT_TOOL_SET = new Set(PROMPT_TOOL_NAMES);
@@ -94,7 +102,7 @@ export function promptToolDefinitions() {
94
102
  },
95
103
  {
96
104
  name: 'read_messages',
97
- 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. 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. When you finish the task from a prompt you received here, close that chat: ${CLOSING_REPLY_GUIDANCE}`,
105
+ 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. When you finish the task from a prompt you received here, close that chat: ${CLOSING_REPLY_GUIDANCE}`,
98
106
  inputSchema: {
99
107
  type: 'object',
100
108
  additionalProperties: false,
@@ -116,15 +124,15 @@ export function promptToolDefinitions() {
116
124
  },
117
125
  {
118
126
  name: 'reply_to_user',
119
- 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. 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.`,
127
+ 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.`,
120
128
  inputSchema: {
121
129
  type: 'object',
122
130
  additionalProperties: false,
123
- required: ['in_reply_to', 'text'],
131
+ required: ['text'],
124
132
  properties: {
125
133
  in_reply_to: {
126
134
  type: 'string',
127
- description: 'Prompt id this reply answers. 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.',
135
+ 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.',
128
136
  },
129
137
  text: {
130
138
  type: 'string',
@@ -139,7 +147,7 @@ export function promptToolDefinitions() {
139
147
  },
140
148
  {
141
149
  name: 'set_status',
142
- description: `Tell the SurfCAD tab which phase the user's prompt is in. responding (alias typing): you are reading or writing an answer; the chat stays open with bouncing dots. building (alias working): you are creating or editing geometry; the chat collapses and the field shows "Agent is working...". ${BUILDING_STATUS_GUIDANCE} Do not call building to list parts, faces, edges, or transforms, or for status or read_messages. A model-changing tool also enters building if you skip this call. A read never does. set_status is for progress and does not close the task. A partial reply does not leave building; the final reply, Stop, or a disconnect does. No activity for ${agentPromptStallMinutes()} minutes, while responding or building, shows the stall notice and leaves Stop up. The result state is the tab value (responding and typing are typing; building and working are working). Without id it targets the latest prompt. A cancelled id returns { ok: false, error: cancelled }. ${CLOSING_REPLY_GUIDANCE}`,
150
+ description: `Tell the SurfCAD tab which phase the user's prompt is in. responding (alias typing): you are reading or writing an answer; the chat stays open with bouncing dots. building (alias working): you are creating or editing geometry; the chat collapses and the field shows "Agent is working...". ${BUILDING_STATUS_GUIDANCE} Do not call building to list parts, faces, edges, or transforms, or for status or read_messages. A model-changing tool also enters building if you skip this call. A read never does. set_status is for progress and does not close the task. A partial reply does not leave building; the final reply, Stop, or a disconnect does. No activity for ${agentPromptStallMinutes()} minutes, while responding or building, shows the stall notice and leaves Stop up. The result state is the tab value (responding and typing are typing; building and working are working). Without id it targets the latest prompt. With no prompt at all (a build you started yourself, or a prompt an earlier one-shot process read) the tab still shows the state: it keeps a session-level state fed by this call, by every model-changing tool you call, and by post_progress, and it returns to idle 60 s after the last of those. A cancelled id returns { ok: false, error: cancelled }. ${CLOSING_REPLY_GUIDANCE}`,
143
151
  inputSchema: {
144
152
  type: 'object',
145
153
  additionalProperties: false,
@@ -165,6 +173,30 @@ export function promptToolDefinitions() {
165
173
  },
166
174
  },
167
175
  },
176
+ {
177
+ name: 'post_progress',
178
+ description: 'Tell SurfCAD you are working, without showing thinking text. Call it while you work, especially during long reasoning, so the phone folds the chat and the bot button spins. Optional text is accepted and discarded; it is never shown. This also keeps the session present. It does not close the task.',
179
+ inputSchema: {
180
+ type: 'object',
181
+ additionalProperties: false,
182
+ properties: {
183
+ text: {
184
+ type: 'string',
185
+ maxLength: 500,
186
+ description: 'Optional note for yourself. It is not sent to the tab and is not shown.',
187
+ },
188
+ },
189
+ },
190
+ },
191
+ {
192
+ name: 'close_session',
193
+ 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.',
194
+ inputSchema: {
195
+ type: 'object',
196
+ additionalProperties: false,
197
+ properties: {},
198
+ },
199
+ },
168
200
  ];
169
201
  }
170
202
 
@@ -216,5 +248,13 @@ export async function callPromptTool(prompts, name, args) {
216
248
  const result = await prompts.setStatus(args);
217
249
  return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
218
250
  }
251
+ if (name === 'post_progress') {
252
+ const result = await prompts.postProgress(args);
253
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
254
+ }
255
+ if (name === 'close_session') {
256
+ const result = await prompts.closeSession();
257
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
258
+ }
219
259
  throw Object.assign(new Error(`Unknown tool: ${name}`), { code: 'unknown_tool' });
220
260
  }
@@ -19,12 +19,24 @@ export const PAIR_MSG = Object.freeze({
19
19
  AGENT_PROMPT_ACK: 'agent.prompt.ack',
20
20
  /** Agent → page. Contract v:1. Several replies may share one prompt id. */
21
21
  AGENT_REPLY: 'agent.reply',
22
+ /** Agent → page. Contract v:1. A plain-text note for this paired session, with no prompt id. */
23
+ AGENT_MESSAGE: 'agent.message',
22
24
  /** Agent → page. Contract v:1. */
23
25
  AGENT_STATUS: 'agent.status',
24
26
  /** Agent → page. Contract v:1. Refreshes the working deadline without changing state. */
25
27
  AGENT_ACTIVITY: 'agent.activity',
28
+ /** Agent → page. Contract v:1. Working signal only. No thinking text. */
29
+ AGENT_PROGRESS: 'agent.progress',
30
+ /** Agent → server. Ends the session. Not sent on process exit. */
31
+ AGENT_CLOSE_SESSION: 'agent.close_session',
26
32
  /** Page → paired agent. Contract v:1. `{ id }`. */
27
33
  AGENT_PROMPT_CANCEL: 'agent.prompt.cancel',
28
34
  /** Agent → page. Contract v:1. `{ id, state }`. */
29
35
  AGENT_PROMPT_CANCEL_RESULT: 'agent.prompt.cancel.result',
36
+ /**
37
+ * Agent → server relay only. Contract v:1. `{ ids }`: prompts the agent
38
+ * has now (read_messages returned them, or the webhook POST succeeded),
39
+ * so the server stops holding them for the next process. Not forwarded.
40
+ */
41
+ AGENT_PROMPT_TAKEN: 'agent.prompt.taken',
30
42
  });
@@ -5,7 +5,7 @@
5
5
  */
6
6
 
7
7
  import { readCommandResponse } from '../commandProtocol.mjs';
8
- import { asRemoteError, tokenRevokedError } from '../errors.mjs';
8
+ import { asRemoteError, authErrorFromBody } from '../errors.mjs';
9
9
 
10
10
  /** How long a command may sit unanswered, on the WebSocket and on HTTPS. */
11
11
  export const COMMAND_WAIT_MS = 10 * 60 * 1000;
@@ -24,7 +24,7 @@ export function commandWaitTimeout() {
24
24
  * @param {any} json
25
25
  */
26
26
  function httpFailure(status, json) {
27
- if (status === 401) return tokenRevokedError();
27
+ if (status === 401) return authErrorFromBody(json);
28
28
  const code = typeof json?.error === 'string' ? json.error : '';
29
29
  const message = typeof json?.message === 'string' ? json.message : '';
30
30
  return asRemoteError({ code, message: message || code });
@@ -189,7 +189,7 @@ export async function callOverHttp(options) {
189
189
  } catch {
190
190
  posted = null;
191
191
  }
192
- if (post.status === 401) throw tokenRevokedError();
192
+ if (post.status === 401) throw authErrorFromBody(posted);
193
193
  if (post.status !== 202) throw httpFailure(post.status, posted);
194
194
 
195
195
  const deadline = now() + COMMAND_WAIT_MS;
@@ -221,8 +221,10 @@ export async function callOverHttp(options) {
221
221
  function isTerminal(err) {
222
222
  const code = err && typeof err === 'object' ? /** @type {{ code?: string }} */ (err).code : '';
223
223
  return code === 'tab_asleep'
224
+ || code === 'command_timeout'
224
225
  || code === 'too_many_pending'
225
226
  || code === 'token_revoked'
227
+ || code === 'expired'
226
228
  || code === 'client_update_required'
227
229
  || code === 'not_found';
228
230
  }
@@ -242,7 +244,11 @@ async function waitViaSse(options, fetchImpl, signal) {
242
244
  },
243
245
  signal,
244
246
  });
245
- if (res.status === 401) throw tokenRevokedError();
247
+ if (res.status === 401) {
248
+ let json = null;
249
+ try { json = await res.json(); } catch { json = null; }
250
+ throw authErrorFromBody(json);
251
+ }
246
252
  if (!res.ok) {
247
253
  try { await res.body?.cancel?.(); } catch { /* noop */ }
248
254
  throw Object.assign(new Error(`Event stream failed (${res.status})`), { code: 'sse_failed' });
@@ -274,7 +280,7 @@ async function waitViaPoll(options, fetchImpl, signal) {
274
280
  } catch {
275
281
  json = null;
276
282
  }
277
- if (res.status === 401) throw tokenRevokedError();
283
+ if (res.status === 401) throw authErrorFromBody(json);
278
284
  if (res.status === 404) {
279
285
  throw Object.assign(new Error('That command is no longer waiting.'), { code: 'not_found' });
280
286
  }
@@ -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
+ }