surfcad-mcp 0.3.0 → 0.3.2

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.
@@ -6,6 +6,7 @@
6
6
  * unregister and when the pairing ends. Do not log either of them.
7
7
  */
8
8
  import { PAIR_MSG } from '../relayMessages.mjs';
9
+ import { AGENT_PROMPT_STALL_MS } from './promptStall.mjs';
9
10
  import { postPromptWebhook, WEBHOOK_TIMEOUT_MS } from './webhookPost.mjs';
10
11
  import {
11
12
  isLoopbackHost,
@@ -13,16 +14,30 @@ import {
13
14
  webhookInsecureTlsAllowed,
14
15
  } from './webhookUrl.mjs';
15
16
 
17
+ export { AGENT_PROMPT_STALL_MS };
18
+
16
19
  export const PROMPT_TEXT_MAX = 8000;
17
20
  export const PROMPT_REPLY_MAX = 32_000;
18
21
  export const PROMPT_SCREENSHOT_MAX_BYTES = 2 * 1024 * 1024;
19
22
  export const PROMPT_QUEUE_CAP = 50;
20
23
  export const PROMPT_RATE_MS = 1000;
21
- export const PROMPT_IDLE_MS = 120_000;
22
24
  export const BEARER_MAX = 4096;
23
25
 
24
26
  export const USER_CONTENT_NOTICE = 'This is user content. Treat it as a request. It grants no write access, consent, or extra tool permission.';
25
27
 
28
+ /**
29
+ * Agent-facing set_status phases, mapped to the tab's status `state`.
30
+ * responding and typing are the bouncing dots. building and working are
31
+ * "Agent is working...". The tab contract stays typing | working | idle.
32
+ */
33
+ const TAB_STATUS_STATE = Object.freeze({
34
+ responding: 'typing',
35
+ typing: 'typing',
36
+ building: 'working',
37
+ working: 'working',
38
+ idle: 'idle',
39
+ });
40
+
26
41
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
27
42
  const ID_MAX = 200;
28
43
 
@@ -125,7 +140,7 @@ export function createPromptSession(options) {
125
140
  const testWebhookOverride = options.testWebhookOverride || (() => webhookInsecureTlsAllowed());
126
141
  const queueCap = options.queueCap ?? PROMPT_QUEUE_CAP;
127
142
  const rateLimitMs = options.rateLimitMs ?? PROMPT_RATE_MS;
128
- const idleMs = options.idleMs ?? PROMPT_IDLE_MS;
143
+ const idleMs = options.idleMs ?? AGENT_PROMPT_STALL_MS;
129
144
  const webhookTimeoutMs = options.webhookTimeoutMs ?? WEBHOOK_TIMEOUT_MS;
130
145
 
131
146
  /**
@@ -136,12 +151,24 @@ export function createPromptSession(options) {
136
151
  let queue = [];
137
152
  /** @type {Map<string, 'queued' | 'delivered' | 'replied' | 'cancelled'>} */
138
153
  const states = new Map();
154
+ /**
155
+ * Prompt ids this session accepted, oldest first. Capped with the queue.
156
+ * Held in memory only. Dropped ids stay replyable while `states` still
157
+ * has them; an id removed from `states` (queue overflow of a prompt the
158
+ * agent never received) is removed here too.
159
+ * @type {string[]}
160
+ */
161
+ let recent = [];
139
162
  /** @type {string | null} */
140
163
  let webhook = null;
141
164
  /** @type {string | null} Bearer token. Process memory only. Never log or return it. */
142
165
  let webhookBearer = null;
143
166
  let working = false;
144
- /** @type {'idle' | 'typing' | 'working'} What the tab shows: the pane open with dots, or the spinner. */
167
+ /** True after the idle window passed with no activity. Cleared by the next activity. */
168
+ let stalled = false;
169
+ /** Bridge calls in flight. The idle window waits until they return. */
170
+ let workHolds = 0;
171
+ /** @type {'idle' | 'typing' | 'working'} What the tab shows. typing is responding (dots); working is building (spinner). */
145
172
  let agentState = 'idle';
146
173
  let promptEpoch = 0;
147
174
  let workedEpoch = 0;
@@ -178,12 +205,50 @@ export function createPromptSession(options) {
178
205
 
179
206
  function armIdle() {
180
207
  clearIdle();
208
+ if (!working || stalled || workHolds > 0) return;
181
209
  idleTimer = setTimer(() => {
182
210
  idleTimer = null;
183
- if (working) emitStatus(false, lastId, false);
211
+ if (!working || stalled || workHolds > 0) return;
212
+ stalled = true;
213
+ const msg = { type: PAIR_MSG.AGENT_STATUS, v: 1, working: true, state: agentState, stalled: true };
214
+ if (typeof lastId === 'string' && lastId) msg.id = lastId;
215
+ emit(msg);
184
216
  }, idleMs);
185
217
  }
186
218
 
219
+ /**
220
+ * The agent did something that is not a state change (another tool call,
221
+ * a read_messages poll). Restart the idle window and tell the tab, so its
222
+ * own deadline restarts too. A stall notice is replaced by the live state.
223
+ */
224
+ function noteActivity() {
225
+ if (lastId && states.get(lastId) === 'cancelled') return;
226
+ if (!working) return;
227
+ if (stalled) {
228
+ emitState(agentState, lastId, true);
229
+ return;
230
+ }
231
+ armIdle();
232
+ if (workHolds > 0) return;
233
+ const msg = { type: PAIR_MSG.AGENT_ACTIVITY, v: 1 };
234
+ if (typeof lastId === 'string' && lastId) msg.id = lastId;
235
+ emit(msg);
236
+ }
237
+
238
+ /**
239
+ * @param {boolean} held
240
+ */
241
+ function holdWork(held) {
242
+ if (held) {
243
+ workHolds += 1;
244
+ clearIdle();
245
+ return;
246
+ }
247
+ workHolds = Math.max(0, workHolds - 1);
248
+ if (workHolds > 0 || !working) return;
249
+ noteActivity();
250
+ }
251
+
187
252
  /**
188
253
  * Send the agent state to the tab. `working` stays on the message for tabs
189
254
  * that predate `state`: true for typing and working, false for idle.
@@ -194,10 +259,11 @@ export function createPromptSession(options) {
194
259
  */
195
260
  function emitState(state, id, force, label) {
196
261
  const next = state !== 'idle';
197
- if (!force && agentState === state) {
262
+ if (!force && agentState === state && !stalled) {
198
263
  if (next) armIdle();
199
264
  return true;
200
265
  }
266
+ stalled = false;
201
267
  working = next;
202
268
  agentState = state;
203
269
  const msg = { type: PAIR_MSG.AGENT_STATUS, v: 1, working: next, state };
@@ -237,8 +303,27 @@ export function createPromptSession(options) {
237
303
  * @param {'queued' | 'delivered' | 'replied' | 'cancelled'} state
238
304
  */
239
305
  function remember(id, state) {
306
+ const known = states.has(id);
240
307
  states.set(id, state);
241
308
  lastId = id;
309
+ if (known) return;
310
+ recent.push(id);
311
+ while (recent.length > queueCap) recent.shift();
312
+ }
313
+
314
+ function pruneRecent() {
315
+ if (recent.every((id) => states.has(id))) return;
316
+ recent = recent.filter((id) => states.has(id));
317
+ }
318
+
319
+ /**
320
+ * Prompts this session accepted, oldest first, at most the queue cap.
321
+ * State is live (`queued`, `delivered`, `replied`, `cancelled`).
322
+ * @returns {Array<{ id: string, state: 'queued' | 'delivered' | 'replied' | 'cancelled' }>}
323
+ */
324
+ function recentPrompts() {
325
+ pruneRecent();
326
+ return recent.map((id) => ({ id, state: states.get(id) }));
242
327
  }
243
328
 
244
329
  /**
@@ -288,6 +373,13 @@ export function createPromptSession(options) {
288
373
  promptEpoch += 1;
289
374
  lastId = id;
290
375
  lastAcceptedAt = now();
376
+ // Each prompt starts as responding on the pane. Do not keep a previous
377
+ // building phase, and do not emit: a read of this prompt must not
378
+ // become "Agent is working...".
379
+ working = false;
380
+ agentState = 'idle';
381
+ stalled = false;
382
+ clearIdle();
291
383
  }
292
384
 
293
385
  /**
@@ -372,6 +464,7 @@ export function createPromptSession(options) {
372
464
  if (old?.id && states.get(old.id) === 'queued') states.delete(old.id);
373
465
  if (old?.id) emit(ack(old.id, 'failed', 'queue_overflow'));
374
466
  }
467
+ if (dropped.length) pruneRecent();
375
468
  emit(ack(prompt.id, 'queued'));
376
469
  }
377
470
 
@@ -513,6 +606,7 @@ export function createPromptSession(options) {
513
606
  ? { data: item.screenshot.data, mimeType: 'image/png' }
514
607
  : null);
515
608
  }
609
+ noteActivity();
516
610
  return { messages, images };
517
611
  }
518
612
 
@@ -531,7 +625,13 @@ export function createPromptSession(options) {
531
625
  if (text.length > PROMPT_REPLY_MAX) {
532
626
  throw Object.assign(new Error('Reply text is too long'), { code: 'reply_too_long' });
533
627
  }
534
- if (states.get(inReplyTo) === 'cancelled') {
628
+ // Only a prompt this session accepted. Checked before any send, so an
629
+ // invented id never becomes an agent.reply on the tab.
630
+ const state = states.get(inReplyTo);
631
+ if (!state) {
632
+ throw Object.assign(new Error('in_reply_to is not a prompt delivered to this session'), { code: 'unknown_prompt' });
633
+ }
634
+ if (state === 'cancelled') {
535
635
  return { ok: false, error: 'cancelled' };
536
636
  }
537
637
  const isFinal = args.final === true;
@@ -548,8 +648,12 @@ export function createPromptSession(options) {
548
648
  queue = queue.filter((item) => item.kind === 'cancel' || item.id !== inReplyTo);
549
649
  states.set(inReplyTo, 'replied');
550
650
  emitStatus(false, inReplyTo, true);
651
+ } else if (agentState === 'working') {
652
+ // Building stays until the final reply. A partial reply only refreshes the stall window.
653
+ workedEpoch = promptEpoch;
654
+ noteActivity();
551
655
  } else {
552
- // A streamed reply means the agent is writing: the tab reopens the chat.
656
+ // A streamed reply while responding keeps the dots and restarts the window.
553
657
  workedEpoch = promptEpoch;
554
658
  emitState('typing', inReplyTo, false);
555
659
  }
@@ -557,22 +661,24 @@ export function createPromptSession(options) {
557
661
  }
558
662
 
559
663
  /**
560
- * `state` (typing | working | idle) or the legacy `working` boolean; one is
561
- * required. `label` is optional text for the tab.
664
+ * `state` or the legacy `working` boolean; one is required. `label` is
665
+ * optional text for the tab. responding and typing are the dots; building
666
+ * and working are the spinner. The tab hears the mapped value.
562
667
  * @param {{ working?: unknown, state?: unknown, label?: unknown, id?: unknown }} args
563
668
  */
564
669
  function setStatus(args) {
565
670
  const hasState = typeof args?.state === 'string';
566
- if (hasState && !['typing', 'working', 'idle'].includes(args.state)) {
567
- throw Object.assign(new Error('state must be typing, working, or idle'), { code: 'bad_args' });
671
+ const mapped = hasState ? TAB_STATUS_STATE[args.state] : undefined;
672
+ if (hasState && !mapped) {
673
+ throw Object.assign(new Error('state must be responding, building, idle, typing, or working'), { code: 'bad_args' });
568
674
  }
569
675
  if (!hasState && typeof args?.working !== 'boolean') {
570
- throw Object.assign(new Error('state (typing | working | idle) or working (boolean) is required'), { code: 'bad_args' });
676
+ throw Object.assign(new Error('state (responding | building | idle) or working (boolean) is required'), { code: 'bad_args' });
571
677
  }
572
678
  if (args.label != null && (typeof args.label !== 'string' || args.label.length > 120)) {
573
679
  throw Object.assign(new Error('label must be a string of at most 120 characters'), { code: 'bad_args' });
574
680
  }
575
- const state = hasState ? args.state : (args.working ? 'working' : 'idle');
681
+ const state = hasState ? mapped : (args.working ? 'working' : 'idle');
576
682
  let id;
577
683
  if (args.id != null) {
578
684
  if (typeof args.id !== 'string' || !args.id || args.id.length > 80) {
@@ -592,8 +698,9 @@ export function createPromptSession(options) {
592
698
 
593
699
  /**
594
700
  * A tool call after a prompt. A call that changes the model (`mutates`)
595
- * switches the tab to working on its own, even when the agent never set
596
- * a state; a read-only call only keeps the current state alive.
701
+ * enters building if the agent has not already, so a missed set_status
702
+ * still collapses the chat while geometry changes. A read never does: it
703
+ * only refreshes the stall window when a phase is already open.
597
704
  * @param {{ mutates?: boolean }} [info]
598
705
  */
599
706
  function noteToolCall(info = {}) {
@@ -607,13 +714,10 @@ export function createPromptSession(options) {
607
714
  emitState('working', lastId, false);
608
715
  return;
609
716
  }
610
- if (promptEpoch > workedEpoch) {
611
- workedEpoch = promptEpoch;
612
- if (!working) emitStatus(true, lastId, false);
613
- else armIdle();
614
- return;
717
+ if (working) {
718
+ if (promptEpoch > workedEpoch) workedEpoch = promptEpoch;
719
+ noteActivity();
615
720
  }
616
- if (working) armIdle();
617
721
  }
618
722
 
619
723
  /**
@@ -658,9 +762,12 @@ export function createPromptSession(options) {
658
762
  life += 1;
659
763
  queue = [];
660
764
  states.clear();
765
+ recent = [];
661
766
  webhook = null;
662
767
  webhookBearer = null;
663
768
  working = false;
769
+ stalled = false;
770
+ workHolds = 0;
664
771
  agentState = 'idle';
665
772
  promptEpoch = 0;
666
773
  workedEpoch = 0;
@@ -674,9 +781,11 @@ export function createPromptSession(options) {
674
781
  cancel,
675
782
  readMessages,
676
783
  waitForMessage,
784
+ recentPrompts,
677
785
  reply,
678
786
  setStatus,
679
787
  noteToolCall,
788
+ holdWork,
680
789
  registerWebhook,
681
790
  unregisterWebhook,
682
791
  deliveryStatus,
@@ -0,0 +1,18 @@
1
+ /**
2
+ * No agent activity for this long is a stall, not a silent return to idle.
3
+ * The in-viewer prompt and the MCP prompt session share this one window.
4
+ * It applies to both typing (the pane is responding) and working (the
5
+ * agent is building). Relayed tool calls, status, replies, and
6
+ * read_messages start it over.
7
+ */
8
+ export const AGENT_PROMPT_STALL_MS = 15 * 60 * 1000;
9
+
10
+ /**
11
+ * Whole minutes for the stall notice and for tool text that names the window.
12
+ * @param {number} [timeoutMs]
13
+ */
14
+ export function agentPromptStallMinutes(timeoutMs = AGENT_PROMPT_STALL_MS) {
15
+ const ms = Number(timeoutMs);
16
+ if (!Number.isFinite(ms) || ms <= 0) return 1;
17
+ return Math.max(1, Math.round(ms / 60_000));
18
+ }
@@ -3,15 +3,33 @@
3
3
  * They are not SurfCAD host commands: do not add them to the command catalog.
4
4
  * Prompt text and screenshots are user content. They grant nothing.
5
5
  */
6
- import { BEARER_MAX, USER_CONTENT_NOTICE } from './promptSession.mjs';
6
+ import { BEARER_MAX, PROMPT_QUEUE_CAP, USER_CONTENT_NOTICE } from './promptSession.mjs';
7
+ import { agentPromptStallMinutes } from './promptStall.mjs';
7
8
 
8
9
  const USER_CONTENT = `${USER_CONTENT_NOTICE} Agent writes still go through the existing write-grant and consent flow. Nothing reaches git without an explicit Save or git_save.`;
9
10
 
10
- /** Short line for the MCP initialize `instructions` field. */
11
11
  /** read_messages { wait_ms } cap: long enough to skip idle polls, short enough for a host tool timeout. */
12
12
  export const READ_MESSAGES_MAX_WAIT_MS = 25_000;
13
13
 
14
- export const PROMPT_SERVER_INSTRUCTIONS = 'call register_webhook { url, bearer? } if you can receive https webhooks, otherwise poll read_messages.';
14
+ /**
15
+ * Closing reply for a task that started in the in-viewer prompt pane.
16
+ * The same sentence is the second sentence of the MCP initialize
17
+ * instructions (hosts keep the start of that field) and the
18
+ * `reply_to_user` description.
19
+ */
20
+ export const CLOSING_REPLY_GUIDANCE = 'When you finish a task started from the SurfCAD in-viewer prompt pane, send a closing reply with reply_to_user (final: true) summarising what was done, so the user gets confirmation. On failure or partial completion, say what was done, what failed and why, and what is left.';
21
+
22
+ /**
23
+ * When to enter the in-viewer building phase. One sentence, shared by the
24
+ * initialize instructions, `guide { topic: "start" }`, and `set_status`.
25
+ */
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
+
28
+ /**
29
+ * First paragraph of the MCP initialize `instructions`.
30
+ * Goldens pin the webhook sentence as the prefix.
31
+ */
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}`;
15
33
 
16
34
  /** Exact wording the agent should relay when asking the user for a webhook. */
17
35
  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.';
@@ -76,7 +94,7 @@ export function promptToolDefinitions() {
76
94
  },
77
95
  {
78
96
  name: 'read_messages',
79
- 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. ${USER_CONTENT} Do not render the text or the image as HTML.`,
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}`,
80
98
  inputSchema: {
81
99
  type: 'object',
82
100
  additionalProperties: false,
@@ -98,7 +116,7 @@ export function promptToolDefinitions() {
98
116
  },
99
117
  {
100
118
  name: 'reply_to_user',
101
- description: 'Send a plain-text reply to the SurfCAD user for a prompt id. Several replies may share one id. 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. A cancelled id returns { "ok": false, "error": "cancelled" } and is not delivered.',
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.`,
102
120
  inputSchema: {
103
121
  type: 'object',
104
122
  additionalProperties: false,
@@ -106,30 +124,30 @@ export function promptToolDefinitions() {
106
124
  properties: {
107
125
  in_reply_to: {
108
126
  type: 'string',
109
- description: 'Prompt id this reply answers.',
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.',
110
128
  },
111
129
  text: {
112
130
  type: 'string',
113
- description: 'Plain text for the user. Not HTML.',
131
+ description: 'Plain text for the user. Not HTML. The closing reply (final: true) summarises what was done, or on failure or partial completion what was done, what failed and why, and what is left.',
114
132
  },
115
133
  final: {
116
134
  type: 'boolean',
117
- description: 'True closes this prompt id. Defaults to false.',
135
+ description: 'True on the closing reply that finishes the prompt. That reply is expected and summarises the result or the failure. Defaults to false.',
118
136
  },
119
137
  },
120
138
  },
121
139
  },
122
140
  {
123
141
  name: 'set_status',
124
- description: 'Tell the SurfCAD tab what you are doing with the user\'s prompt: state typing (writing an answer: the chat stays open with typing dots), working (changing the model: the chat collapses and the field shows a spinner), or idle. You do not have to call it for working: the first model-changing tool call after a prompt sets working, a streamed reply_to_user (final false) sets typing, and a final reply or 120 seconds without activity sets idle. Set typing before a long answer so the user reads the chat instead of watching the viewport. Without id it targets the latest prompt. A cancelled id returns { ok: false, error: cancelled }.',
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}`,
125
143
  inputSchema: {
126
144
  type: 'object',
127
145
  additionalProperties: false,
128
146
  properties: {
129
147
  state: {
130
148
  type: 'string',
131
- enum: ['typing', 'working', 'idle'],
132
- description: 'typing: you are writing an answer (the tab keeps the chat open with typing dots). working: you are changing the model (the tab collapses the chat and shows a spinner). idle: done. Set typing before a long answer; model-changing tool calls set working on their own; a final reply_to_user sets idle.',
149
+ enum: ['responding', 'building', 'idle', 'typing', 'working'],
150
+ description: 'responding: bouncing dots, chat stays open (alias typing). building: you are creating or editing geometry and the field shows Agent is working (alias working). Call building only once you are actually modeling. idle: not responding or building. Idle does not close the task; a closing reply_to_user does.',
133
151
  },
134
152
  label: {
135
153
  type: 'string',
@@ -138,7 +156,7 @@ export function promptToolDefinitions() {
138
156
  },
139
157
  working: {
140
158
  type: 'boolean',
141
- description: 'Legacy form of state: true is working, false is idle. Use state.',
159
+ description: 'Legacy form of state: true is building (working), false is idle. Use state.',
142
160
  },
143
161
  id: {
144
162
  type: 'string',
@@ -172,9 +190,10 @@ export async function callPromptTool(prompts, name, args) {
172
190
  if (wait > 0 && typeof prompts.waitForMessage === 'function') await prompts.waitForMessage(wait);
173
191
  }
174
192
  const { messages, images } = prompts.readMessages(args.max);
193
+ const recent = typeof prompts.recentPrompts === 'function' ? prompts.recentPrompts() : [];
175
194
  if (messages.length === 0) {
176
195
  return {
177
- content: [{ type: 'text', text: JSON.stringify({ messages: [], acked: [] }, null, 2) }],
196
+ content: [{ type: 'text', text: JSON.stringify({ messages: [], acked: [], recent }, null, 2) }],
178
197
  };
179
198
  }
180
199
  const content = [];
@@ -186,7 +205,7 @@ export async function callPromptTool(prompts, name, args) {
186
205
  const image = images[i];
187
206
  if (image) content.push({ type: 'image', data: image.data, mimeType: image.mimeType });
188
207
  }
189
- content.push({ type: 'text', text: JSON.stringify({ acked }, null, 2) });
208
+ content.push({ type: 'text', text: JSON.stringify({ acked, recent }, null, 2) });
190
209
  return { content };
191
210
  }
192
211
  if (name === 'reply_to_user') {
package/src/relay.mjs CHANGED
@@ -144,7 +144,8 @@ export class RelaySession {
144
144
 
145
145
  /**
146
146
  * A tool call after a prompt arrives. A model-changing call (`mutates`)
147
- * marks the agent working; a read-only call keeps the state alive.
147
+ * enters building if the agent has not already. A read never does; it
148
+ * only keeps an open phase alive.
148
149
  * Best-effort: a dead socket does not fail the tool call.
149
150
  * @param {{ mutates?: boolean }} [info]
150
151
  */
@@ -156,6 +157,19 @@ export class RelaySession {
156
157
  }
157
158
  }
158
159
 
160
+ /**
161
+ * Pause the working deadline while a bridge call is in flight, then
162
+ * start it again when the call returns. A long tool call is activity.
163
+ * @param {boolean} held
164
+ */
165
+ holdAgentWork(held) {
166
+ try {
167
+ this.#prompts.holdWork(held === true);
168
+ } catch {
169
+ /* status is advisory */
170
+ }
171
+ }
172
+
159
173
  /**
160
174
  * @param {object} payload
161
175
  */
@@ -21,6 +21,8 @@ export const PAIR_MSG = Object.freeze({
21
21
  AGENT_REPLY: 'agent.reply',
22
22
  /** Agent → page. Contract v:1. */
23
23
  AGENT_STATUS: 'agent.status',
24
+ /** Agent → page. Contract v:1. Refreshes the working deadline without changing state. */
25
+ AGENT_ACTIVITY: 'agent.activity',
24
26
  /** Page → paired agent. Contract v:1. `{ id }`. */
25
27
  AGENT_PROMPT_CANCEL: 'agent.prompt.cancel',
26
28
  /** Agent → page. Contract v:1. `{ id, state }`. */
package/src/server.mjs CHANGED
@@ -41,6 +41,7 @@ import {
41
41
  } from './prompt/guide.mjs';
42
42
  import { withErrorHint, withRowHints } from './prompt/errorHints.mjs';
43
43
  import { callListHelpersTool, LIST_HELPERS_TOOL_NAME, listHelpersToolDefinition } from './helpers.mjs';
44
+ import { mergeRegisteredIntoListCommands } from './listCommandsMerge.mjs';
44
45
 
45
46
  const PAIR_TOOL_NAME = 'pair';
46
47
 
@@ -61,6 +62,46 @@ function augmentStatusTool(tool) {
61
62
  };
62
63
  }
63
64
 
65
+ /**
66
+ * One list for tools/list and for the rows list_commands adds. MCP-only
67
+ * tools are whatever this returns that is not a bridge command.
68
+ * @param {Array<{ name: string, description?: string, inputSchema?: object }>} bridgeTools
69
+ */
70
+ function registeredToolDefinitions(bridgeTools) {
71
+ return [
72
+ {
73
+ name: PAIR_TOOL_NAME,
74
+ description: `Pair this MCP server to an open SurfCAD tab via the local WebSocket relay. ${pairingEnvHint()} ${PROMPT_SERVER_INSTRUCTIONS} After pairing call guide { topic: "start" } (How to build in SurfCAD: block out first, features first, hardware as patterned parts) before the first model call.`,
75
+ inputSchema: {
76
+ type: 'object',
77
+ additionalProperties: false,
78
+ properties: {
79
+ code: {
80
+ type: 'string',
81
+ description: '6-character pairing code from the SurfCAD Local agent panel',
82
+ },
83
+ },
84
+ },
85
+ },
86
+ guideToolDefinition(),
87
+ listHelpersToolDefinition(),
88
+ ...promptToolDefinitions(),
89
+ ...bridgeTools,
90
+ ];
91
+ }
92
+
93
+ /**
94
+ * @param {{ name: string, description?: string }} tool
95
+ * @param {string[]} extraNames
96
+ */
97
+ function augmentListCommandsTool(tool, extraNames) {
98
+ if (!tool || tool.name !== 'list_commands' || extraNames.length === 0) return tool;
99
+ return {
100
+ ...tool,
101
+ description: `${tool.description || ''} Also lists the MCP-only tools this server registers (${extraNames.join(', ')}), in the agent group. They are not bridge commands.`,
102
+ };
103
+ }
104
+
64
105
  /** A bridge call that has to pair first waits this long for Allow, then fails. */
65
106
  const AUTO_PAIR_WAIT_MS = 1000;
66
107
  /** The pair tool returns pair_pending before typical MCP client timeouts (60 s). */
@@ -176,7 +217,15 @@ function toolErrorPayload(err) {
176
217
  export async function createSurfcadMcpServer(options = {}) {
177
218
  const catalog = options.catalog || loadCommandsCatalog();
178
219
  const session = options.session || new RelaySession();
220
+ const bridgeNames = new Set(catalog.commands.map((command) => command.name));
179
221
  const bridgeTools = bridgeToolDefinitions(catalog).map((tool) => augmentStatusTool(augmentScreenshotTool(tool)));
222
+ const mcpOnlyNames = registeredToolDefinitions(bridgeTools)
223
+ .map((tool) => tool.name)
224
+ .filter((name) => !bridgeNames.has(name));
225
+ for (let i = 0; i < bridgeTools.length; i += 1) {
226
+ bridgeTools[i] = augmentListCommandsTool(bridgeTools[i], mcpOnlyNames);
227
+ }
228
+ const registeredTools = registeredToolDefinitions(bridgeTools);
180
229
 
181
230
  const version = loadPackageVersion();
182
231
  const server = new Server(
@@ -202,26 +251,7 @@ export async function createSurfcadMcpServer(options = {}) {
202
251
  });
203
252
 
204
253
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
205
- tools: [
206
- {
207
- name: PAIR_TOOL_NAME,
208
- description: `Pair this MCP server to an open SurfCAD tab via the local WebSocket relay. ${pairingEnvHint()} ${PROMPT_SERVER_INSTRUCTIONS} After pairing call guide { topic: "start" } (How to build in SurfCAD: block out first, features first, hardware as patterned parts) before the first model call.`,
209
- inputSchema: {
210
- type: 'object',
211
- additionalProperties: false,
212
- properties: {
213
- code: {
214
- type: 'string',
215
- description: '6-character pairing code from the SurfCAD Local agent panel',
216
- },
217
- },
218
- },
219
- },
220
- guideToolDefinition(),
221
- listHelpersToolDefinition(),
222
- ...promptToolDefinitions(),
223
- ...bridgeTools,
224
- ],
254
+ tools: registeredTools,
225
255
  }));
226
256
 
227
257
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
@@ -288,13 +318,27 @@ export async function createSurfcadMcpServer(options = {}) {
288
318
  }
289
319
 
290
320
  try {
291
- // A model-changing tool switches the tab to working on its own.
321
+ // A model-changing tool enters building if set_status has not already.
322
+ // A read never does. The call holds the idle window until it returns:
323
+ // a long tool call is the agent working, not a stall.
292
324
  const row = catalog.commands.find((c) => c.name === name);
293
325
  session.noteAgentToolCall({ mutates: row?.mutates === true || (row?.mutates == null && mutatingTool(name)) });
294
- const out = await callPairedBridgeTool(session, name, withDefaultReturn(row, args));
326
+ session.holdAgentWork(true);
327
+ let out;
328
+ try {
329
+ out = await callPairedBridgeTool(session, name, withDefaultReturn(row, args));
330
+ } finally {
331
+ session.holdAgentWork(false);
332
+ }
295
333
  if (name === 'status' && out.isError !== true && out.value && typeof out.value === 'object' && !Array.isArray(out.value)) {
296
334
  return textResult({ ...out.value, ...session.prompts.deliveryStatus() });
297
335
  }
336
+ if (name === 'list_commands' && out.isError !== true) {
337
+ out = {
338
+ ...out,
339
+ value: mergeRegisteredIntoListCommands(out.value, { registered: registeredTools, bridgeNames, args }),
340
+ };
341
+ }
298
342
  if (out.isError === true) return errorResult(out.value, name);
299
343
  // A run that failed answers ok: false with errors rows; those carry hints too.
300
344
  return textResult(withRowHints(out.value));