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
package/src/server.mjs CHANGED
@@ -15,17 +15,13 @@ import {
15
15
  pairingEnvHint,
16
16
  } from './errors.mjs';
17
17
  import { loadPackageVersion } from './packageVersion.mjs';
18
- import {
19
- ensureAgentBridgeRelay,
20
- resetAgentBridgeRelayCache,
21
- stopAgentBridgeRelay,
22
- } from './bridge/relayServer.mjs';
23
- import { RelaySession } from './relay.mjs';
24
18
  import { resolveAgentName, resolveServerUrl } from './remote/config.mjs';
25
19
  import { handleRemoteStdinEnd, installRemoteProcessExitLogs } from './remote/processExit.mjs';
26
20
  import { RemoteSession } from './remote/session.mjs';
21
+ import { claimOwner, hostSession, ownerAttached, ownerStatus, readOwner, wakeTarget } from './listen/owner.mjs';
27
22
  import { forgetLoginIfToken, readSavedLogin } from './remote/tokenStore.mjs';
28
23
  import { waitForPairing } from './pairWait.mjs';
24
+ import { augmentBenchShowTool, augmentImportTool } from './importFile.mjs';
29
25
  import { augmentScreenshotTool, callPairedBridgeTool } from './screenshotFile.mjs';
30
26
  import {
31
27
  callPromptTool,
@@ -65,7 +61,81 @@ const PAIR_GUIDE_POINTER = 'Before the first model call read guide { topic: "sta
65
61
  */
66
62
  const PROMPT_TOOLS_WITHOUT_ACTIVITY = new Set(['set_status', 'post_progress', 'close_session', 'read_messages']);
67
63
 
68
- const STATUS_WAKE_NOTE = ' It also adds host ({ name, version }: what your MCP client calls itself, null when it did not say) and wake ({ coldWake, forms, source, listenerRunning, note }): whether a chat message can start a session of you while you are idle. coldWake is "ready", "listener_stopped" or "unavailable"; with "unavailable" messages reach you only while you are in a turn and polling (guide { topic: "chat" } section A).';
64
+ /**
65
+ * Chat messages waiting for this agent, for every tool result, so an agent in
66
+ * the middle of a build sees a message on its very next call instead of only
67
+ * at its next read_messages. null when nothing waits (the result is unchanged).
68
+ * @param {{ queuedIds?: () => string[] } | null | undefined} prompts
69
+ * @returns {{ count: number, ids: string[], next: string } | null}
70
+ */
71
+ export function pendingPromptsNotice(prompts) {
72
+ const ids = typeof prompts?.queuedIds === 'function' ? prompts.queuedIds() : [];
73
+ if (!Array.isArray(ids) || ids.length === 0) return null;
74
+ return {
75
+ count: ids.length,
76
+ ids: ids.slice(0, 10),
77
+ next: 'read_messages {} now, then set_status { state: "responding", id } for each',
78
+ };
79
+ }
80
+
81
+ /**
82
+ * The agent's display name for the chat cap, from the MCP client name.
83
+ * @param {unknown} clientName
84
+ */
85
+ export function agentDisplayName(clientName) {
86
+ const raw = typeof clientName === 'string' ? clientName.trim() : '';
87
+ if (!raw) return '';
88
+ const known = { 'claude-code': 'Claude Code', 'claude-ai': 'Claude', cursor: 'Cursor', 'grok-bot': 'Grok Bot' };
89
+ if (known[raw.toLowerCase()]) return known[raw.toLowerCase()];
90
+ return raw.replace(/[-_]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase()).slice(0, 40);
91
+ }
92
+
93
+ /**
94
+ * Merge extra fields into a tool result: into an object result, else as one
95
+ * more text block.
96
+ * @param {{ content: Array<{ type: string, text?: string }>, isError?: boolean }} result
97
+ * @param {Record<string, unknown>} fields
98
+ */
99
+ export function withNotice(result, fields) {
100
+ if (!result || !Array.isArray(result.content)) return result;
101
+ const first = result.content[0];
102
+ if (result.content.length === 1 && first?.type === 'text') {
103
+ try {
104
+ const value = JSON.parse(first.text);
105
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
106
+ return { ...result, content: [{ type: 'text', text: JSON.stringify({ ...value, ...fields }) }] };
107
+ }
108
+ } catch {
109
+ /* plain text: add a block below */
110
+ }
111
+ }
112
+ return { ...result, content: [...result.content, { type: 'text', text: JSON.stringify(fields) }] };
113
+ }
114
+
115
+ /**
116
+ * Add `pendingPrompts` to a tool result when chat messages are waiting. An
117
+ * object result gets the field; any other result gets one more text block.
118
+ * @param {{ content: Array<{ type: string, text?: string }>, isError?: boolean }} result
119
+ * @param {{ queuedIds?: () => string[] } | null | undefined} prompts
120
+ */
121
+ export function withPendingPrompts(result, prompts) {
122
+ const pending = pendingPromptsNotice(prompts);
123
+ if (!pending || !result || !Array.isArray(result.content)) return result;
124
+ const first = result.content[0];
125
+ if (result.content.length === 1 && first?.type === 'text') {
126
+ try {
127
+ const value = JSON.parse(first.text);
128
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
129
+ return { ...result, content: [{ type: 'text', text: JSON.stringify({ ...value, pendingPrompts: pending }) }] };
130
+ }
131
+ } catch {
132
+ /* plain text: add a block below */
133
+ }
134
+ }
135
+ return { ...result, content: [...result.content, { type: 'text', text: JSON.stringify({ pendingPrompts: pending }) }] };
136
+ }
137
+
138
+ const STATUS_WAKE_NOTE = ' It also adds mcpVersion (this surfcad-mcp package), host ({ name, version }: what your MCP client calls itself, null when it did not say) and wake ({ coldWake, forms, source, listenerRunning, note }): whether a chat message can start a session of you while you are idle. coldWake is "ready", "listener_stopped" or "unavailable"; with "unavailable" messages reach you only while you are in a turn and polling (guide { topic: "chat" } section A).';
69
139
 
70
140
  const STATUS_PROMPT_NOTE = ' This process also adds webhookRegistered (true when a prompt webhook is registered; the URL and any bearer are not included), queued (prompt messages waiting for read_messages; cancelled prompts are not counted), counts ({ queued, delivered, replied, cancelled }), and last ({ id, state } of the latest prompt, or null).';
71
141
 
@@ -90,16 +160,11 @@ function registeredToolDefinitions(bridgeTools) {
90
160
  return [
91
161
  {
92
162
  name: PAIR_TOOL_NAME,
93
- 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.`,
163
+ description: `Connect this MCP server to the SurfCAD tab that redeemed the saved login. Call pair {} with no code. Pairing itself is npx surfcad-mcp login --code with the join code from Connect Agent (ABCD-EFGH; the hyphen is optional). pair {} starts the wake listener and fires the test wake once per login. SurfCAD greets the user itself; do not send a greeting. ${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.`,
94
164
  inputSchema: {
95
165
  type: 'object',
96
166
  additionalProperties: false,
97
- properties: {
98
- code: {
99
- type: 'string',
100
- description: '8-character pairing code from the SurfCAD Local agent panel',
101
- },
102
- },
167
+ properties: {},
103
168
  },
104
169
  },
105
170
  guideToolDefinition(),
@@ -121,8 +186,6 @@ function augmentListCommandsTool(tool, extraNames) {
121
186
  };
122
187
  }
123
188
 
124
- /** A bridge call that has to pair first waits this long for Allow, then fails. */
125
- const AUTO_PAIR_WAIT_MS = 1000;
126
189
  /** The pair tool returns pair_pending before typical MCP client timeouts (60 s). */
127
190
  const PAIR_TOOL_WAIT_MS = 30_000;
128
191
 
@@ -176,7 +239,7 @@ export function withDefaultReturn(row, args) {
176
239
  * @param {string} name
177
240
  */
178
241
  function mutatingTool(name) {
179
- return /^(set_script|run|insert_|invoke_helper|confirm_feature|delete_feature|rollback_to|undo|redo|create_|delete_|rename_|part_set_transform|insert_part|open_|paint_confirm|paint$|joint_commit|sheet_commit|sheet_set_params|sheet_edit|sketch_commit|slot_commit|hole_commit|git_|export_|edit_feature|pick_done|select_)/.test(name);
242
+ return /^(set_script|run|insert_|invoke_helper|confirm_feature|delete_feature|rollback_to|undo|redo|create_|delete_|rename_|part_set_transform|set_part_placement|insert_part|open_|paint_confirm|paint$|joint_commit|sheet_commit|sheet_set_params|sheet_edit|sketch_commit|slot_commit|hole_commit|boss_commit|git_|export_|edit_feature|pick_done|select_)/.test(name);
180
243
  }
181
244
 
182
245
  function pairToolResult(result, prompts, wake) {
@@ -223,8 +286,8 @@ async function wakeStatus(session, opts = {}) {
223
286
  const state = await bootstrapWake({
224
287
  env,
225
288
  remote,
226
- greet: enabled && opts.greet === true,
227
- selfGreet: opts.selfGreet !== false,
289
+ check: enabled && opts.check === true,
290
+ tellUser: opts.tellUser !== false,
228
291
  autoListen: enabled,
229
292
  });
230
293
  return {
@@ -287,6 +350,8 @@ export function createInProcessWake(options) {
287
350
  const wake = async (prompts) => {
288
351
  try {
289
352
  if (options.remote && await readListenerPid(env)) return { ok: false, skipped: 'listener' };
353
+ // The chat's owner is waiting (surfcad-mcp wait): its waiter delivers.
354
+ if (await ownerAttached(env)) return { ok: false, skipped: 'owner_waiting' };
290
355
  let pending = Array.isArray(prompts) ? prompts : [];
291
356
  // Up to ten minutes of an agent that keeps working without reading.
292
357
  for (let tries = 0; tries < 40 && await isAwake(); tries += 1) {
@@ -302,7 +367,10 @@ export function createInProcessWake(options) {
302
367
  waker = createWaker(config, { env, ...(options.deps || {}) });
303
368
  wakerKey = key;
304
369
  }
305
- const outcome = await waker.wake(wakePayload(prompts));
370
+ // The chat's owner answers: its conversation resumed, or a fork of it
371
+ // when it is open but idle. No owner: a fresh session.
372
+ const target = await wakeTarget(env).catch(() => ({ action: 'fresh' }));
373
+ const outcome = await waker.wake(wakePayload(prompts, { session: target.action === 'busy' ? { ...target, action: 'fork' } : target }));
306
374
  log(outcome.ok ? `woke the agent by ${outcome.form} for an unread chat message` : `wake failed (${outcome.error})`);
307
375
  return outcome;
308
376
  } catch {
@@ -361,13 +429,19 @@ function toolErrorPayload(err) {
361
429
  }
362
430
 
363
431
  /**
364
- * @param {{ catalog?: ReturnType<typeof loadCommandsCatalog>, session?: RelaySession, autoPair?: boolean }} [options]
432
+ * @param {{ catalog?: ReturnType<typeof loadCommandsCatalog>, session: import('./remote/session.mjs').RemoteSession }} options
365
433
  */
366
434
  export async function createSurfcadMcpServer(options = {}) {
367
435
  const catalog = options.catalog || loadCommandsCatalog();
368
- const session = options.session || new RelaySession();
436
+ if (!options.session) {
437
+ throw Object.assign(
438
+ new Error('createSurfcadMcpServer requires a session. Run npx surfcad-mcp login --code CODE.'),
439
+ { code: 'not_logged_in' },
440
+ );
441
+ }
442
+ const session = options.session;
369
443
  const bridgeNames = new Set(catalog.commands.map((command) => command.name));
370
- const bridgeTools = bridgeToolDefinitions(catalog).map((tool) => augmentStatusTool(augmentScreenshotTool(tool)));
444
+ const bridgeTools = bridgeToolDefinitions(catalog).map((tool) => augmentStatusTool(augmentBenchShowTool(augmentImportTool(augmentScreenshotTool(tool)))));
371
445
  /** Names outside the shipped catalog the paired tab was asked about (tabAdvertisesTool). */
372
446
  const unlistedToolCache = new Map();
373
447
  const mcpOnlyNames = registeredToolDefinitions(bridgeTools)
@@ -405,7 +479,38 @@ export async function createSurfcadMcpServer(options = {}) {
405
479
  tools: registeredTools,
406
480
  }));
407
481
 
482
+ /** This process's session answered a chat prompt and owned the chat. */
483
+ let ownedChat = false;
484
+
408
485
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
486
+ const result = await handleToolCall(request);
487
+ const moved = ownedChat ? await chatMovedNotice() : null;
488
+ // read_messages is how the waiting messages are taken: no notice on it.
489
+ if (request.params.name === 'read_messages') return moved ? withNotice(result, { chatMoved: moved }) : result;
490
+ const out = withPendingPrompts(result, session.prompts);
491
+ return moved ? withNotice(out, { chatMoved: moved }) : out;
492
+ });
493
+
494
+ /**
495
+ * The chat this session owned now belongs to another session (a fork of
496
+ * this one answered while it was idle, or the user started over). Said
497
+ * once, then this process stops tracking it.
498
+ */
499
+ async function chatMovedNotice() {
500
+ const me = hostSession(process.env);
501
+ if (!me) return null;
502
+ const owner = await readOwner(process.env).catch(() => null);
503
+ if (owner && owner.session === me.session) return null;
504
+ ownedChat = false;
505
+ return {
506
+ to: owner?.session || null,
507
+ message: owner
508
+ ? 'The SurfCAD chat moved to another agent session (it answered while you were idle). Stop waiting for chat messages here; do not reply to old prompts.'
509
+ : 'The SurfCAD chat was released (the user deleted the chat history). Stop waiting for chat messages here.',
510
+ };
511
+ }
512
+
513
+ async function handleToolCall(request) {
409
514
  // A tool call means the agent is in a turn: the wake leaves it alone.
410
515
  void stampAwake(process.env);
411
516
  const name = request.params.name;
@@ -429,6 +534,12 @@ export async function createSurfcadMcpServer(options = {}) {
429
534
  try {
430
535
  const out = await callPromptTool(session.prompts, name, args);
431
536
  if (out.isError) return errorResult(out.error, name);
537
+ // Answering a chat prompt makes this session the chat's owner: the
538
+ // user's next message, however late, goes to it (owner.mjs).
539
+ if (name === 'reply_to_user' || (name === 'set_status' && (args.state === 'responding' || args.state === 'typing'))) {
540
+ const claimed = await claimOwner(process.env).catch(() => null);
541
+ if (claimed?.owner) ownedChat = true;
542
+ }
432
543
  return { content: out.content, isError: false };
433
544
  } catch (err) {
434
545
  return errorResult(toolErrorPayload(err), name);
@@ -436,18 +547,11 @@ export async function createSurfcadMcpServer(options = {}) {
436
547
  }
437
548
 
438
549
  if (name === PAIR_TOOL_NAME) {
439
- const code = typeof args.code === 'string' && args.code.trim()
440
- ? args.code.trim()
441
- : (process.env.SURFCAD_PAIRING_CODE || '').trim();
442
- if (!code) {
443
- return errorResult({
444
- code: 'bad_pairing_code',
445
- message: `Missing pairing code. Pass { "code": "........" } or set SURFCAD_PAIRING_CODE. ${pairingEnvHint()}`,
446
- }, name);
447
- }
550
+ // The saved login is the pairing. pair {} connects and runs the
551
+ // bootstrap. A code is not accepted here: login --code redeems it.
448
552
  try {
449
- const result = await waitForPairing(session.pair(code), PAIR_TOOL_WAIT_MS);
450
- return pairToolResult(result, session.prompts, await wakeStatus(session, { greet: true }));
553
+ const result = await waitForPairing(session.pair(''), PAIR_TOOL_WAIT_MS);
554
+ return pairToolResult(result, session.prompts, await wakeStatus(session, { check: true }));
451
555
  } catch (err) {
452
556
  return errorResult(toolErrorPayload(err), name);
453
557
  }
@@ -463,17 +567,8 @@ export async function createSurfcadMcpServer(options = {}) {
463
567
 
464
568
  // A lost session is already re-pairing in the background; session.call
465
569
  // fails fast with pairing_lost until it is back.
466
- if (!session.isPaired() && session.state !== 'lost') {
467
- const envCode = (process.env.SURFCAD_PAIRING_CODE || '').trim();
468
- if (envCode) {
469
- try {
470
- await waitForPairing(session.pair(envCode), AUTO_PAIR_WAIT_MS);
471
- } catch (err) {
472
- return errorResult(toolErrorPayload(err), name);
473
- }
474
- } else if (session.state !== 'pairing') {
475
- return errorResult(notPairedError(), name);
476
- }
570
+ if (!session.isPaired() && session.state !== 'lost' && session.state !== 'pairing') {
571
+ return errorResult(notPairedError(), name);
477
572
  }
478
573
  if (!known && !(await tabAdvertisesTool(session, name, unlistedToolCache))) {
479
574
  return errorResult({ code: 'unknown_tool', message: `Unknown tool: ${name}` });
@@ -493,7 +588,7 @@ export async function createSurfcadMcpServer(options = {}) {
493
588
  session.holdAgentWork(false);
494
589
  }
495
590
  if (name === 'status' && out.isError !== true && out.value && typeof out.value === 'object' && !Array.isArray(out.value)) {
496
- return textResult({ ...out.value, ...session.prompts.deliveryStatus(), wake: await wakeStatus(session), host: hostInfo(server) });
591
+ return textResult({ ...out.value, ...session.prompts.deliveryStatus(), wake: await wakeStatus(session), chat: await ownerStatus(process.env).catch(() => ({ owner: null })), host: hostInfo(server), mcpVersion: version });
497
592
  }
498
593
  if (name === 'list_commands' && out.isError !== true) {
499
594
  out = {
@@ -520,76 +615,24 @@ export async function createSurfcadMcpServer(options = {}) {
520
615
  }
521
616
  return errorResult(toolErrorPayload(err), name);
522
617
  }
523
- });
618
+ }
524
619
 
525
620
  return { server, session, catalog, bridgeTools };
526
621
  }
527
622
 
528
623
  /**
529
- * @param {{ autoPairFromEnv?: boolean, startRelay?: boolean, mode?: 'local' | 'remote', server?: string, name?: string, env?: NodeJS.ProcessEnv }} [options]
624
+ * Stdio server. Always the server relay. A saved login is required.
625
+ * `mode: 'local'` is refused: the loopback relay was removed in 0.4.0.
626
+ * @param {{ mode?: 'local' | 'remote', server?: string, name?: string, env?: NodeJS.ProcessEnv }} [options]
530
627
  */
531
628
  export async function runSurfcadMcpServer(options = {}) {
532
- if (options.mode === 'remote') return runRemoteMcpServer(options);
533
-
534
- /** @type {Awaited<ReturnType<typeof ensureAgentBridgeRelay>> | null} */
535
- let ownedRelay = null;
536
- const startRelay = options.startRelay !== false && process.env.SURFCAD_MCP_START_RELAY !== '0';
537
- const relayOptions = {
538
- onReady: (url) => {
539
- if (process.env.SURFCAD_AGENT_BRIDGE_WS_VERBOSE === '1') {
540
- console.error(`[surfcad-mcp] Agent bridge relay on ${url}`);
541
- }
542
- },
543
- };
544
- if (startRelay) {
545
- const relay = await ensureAgentBridgeRelay(relayOptions);
546
- if (relay.ownsServer) ownedRelay = relay;
547
- }
548
-
549
- // Another surfcad-mcp process may own the relay; when it exits, take over
550
- // the port so the tab and this session can reconnect.
551
- const takeOverRelay = async () => {
552
- if (!startRelay || ownedRelay) return;
553
- resetAgentBridgeRelayCache();
554
- const relay = await ensureAgentBridgeRelay(relayOptions);
555
- if (relay.ownsServer) {
556
- ownedRelay = relay;
557
- console.error(`${new Date().toISOString()} [surfcad-mcp] relay owner went away; now serving ${relay.url}`);
558
- }
559
- };
560
-
561
- // Intended MCP stdio lifecycle: when the client closes stdin the process
562
- // (and the relay it owns) must exit. Playtests that spawn this bin have to
563
- // keep stdin open; stdio: 'ignore' ends the stream immediately.
564
- const onStdinClosed = () => {
565
- if (ownedRelay) {
566
- const closing = ownedRelay;
567
- ownedRelay = null;
568
- void stopAgentBridgeRelay(closing).finally(() => {
569
- setTimeout(() => process.exit(0), 0).unref();
570
- });
571
- return;
572
- }
573
- setTimeout(() => process.exit(0), 0).unref();
574
- };
575
- process.stdin.once('end', onStdinClosed);
576
-
577
- const localWake = createInProcessWake({ remote: false });
578
- const { server, session } = await createSurfcadMcpServer({
579
- session: new RelaySession({ ensureRelay: takeOverRelay, onUnread: localWake }),
580
- });
581
- localWake.attach(session.prompts);
582
- const transport = new StdioServerTransport();
583
- await server.connect(transport);
584
-
585
- const envCode = (process.env.SURFCAD_PAIRING_CODE || '').trim();
586
- if (options.autoPairFromEnv !== false && envCode) {
587
- session.pair(envCode).catch(() => {
588
- /* user may approve later; tools will retry */
589
- });
629
+ if (options.mode === 'local') {
630
+ throw Object.assign(
631
+ new Error('The local relay was removed in surfcad-mcp 0.4.0. Run npx surfcad-mcp login --code CODE.'),
632
+ { code: 'local_relay_removed' },
633
+ );
590
634
  }
591
-
592
- return { server, session, transport };
635
+ return runRemoteMcpServer(options);
593
636
  }
594
637
 
595
638
  /**
@@ -617,16 +660,17 @@ async function runRemoteMcpServer(options) {
617
660
  liveLogin = { token: saved.token, env, clear: () => remote.prompts.unregisterWebhook() };
618
661
  const { server, session } = await createSurfcadMcpServer({ session: remote });
619
662
  // A logged-in agent may never call `pair`. Once connected, start the
620
- // listener and let the wake greet (once per login). With no wake there is
621
- // nobody to tell here, so that greeting waits for the next pair.
663
+ // listener and fire the test wake (once per login). With no wake there is
664
+ // nobody to tell here, so the one-time user notice waits for the next pair.
622
665
  let bootstrapped = false;
623
666
  const bootstrapOnce = () => {
624
667
  if (bootstrapped) return;
625
668
  bootstrapped = true;
626
- void wakeStatus(remote, { greet: true, selfGreet: false }).catch(() => {});
669
+ void wakeStatus(remote, { check: true, tellUser: false }).catch(() => {});
627
670
  };
628
671
  server.oninitialized = () => {
629
672
  remote.applyClientInfo(server.getClientVersion());
673
+ remote.prompts?.setAgentName?.(agentDisplayName(server.getClientVersion()?.name));
630
674
  void remote.connect().then(bootstrapOnce, (err) => {
631
675
  console.error(`${new Date().toISOString()} [surfcad-mcp] ${err?.message || 'remote connect failed'}`);
632
676
  });
@@ -0,0 +1,8 @@
1
+ /**
2
+ * STEP import cap. Keep in lockstep with src/utils/stepUploadLimit.js.
3
+ * The published package cannot import the app copy.
4
+ */
5
+ export const STEP_UPLOAD_MAX_BYTES = 200 * 1024 * 1024;
6
+
7
+ export const STEP_UPLOAD_TOO_LARGE =
8
+ 'This STEP file is over 200 MB. Export a smaller model and try again.';
@@ -1,132 +0,0 @@
1
- /**
2
- * HTTP responses for the loopback popup bridge (`/bridge`, `/bridge.js`).
3
- * See `bridgePopup.mjs` for the browser side.
4
- */
5
-
6
- import { readFileSync } from 'node:fs';
7
-
8
- export const BRIDGE_PAGE_PATH = '/bridge';
9
- export const BRIDGE_SCRIPT_PATH = '/bridge.js';
10
-
11
- let cachedScript = null;
12
-
13
- function bridgeScriptSource() {
14
- if (cachedScript == null) {
15
- cachedScript = readFileSync(new URL('./bridgePopup.mjs', import.meta.url), 'utf8');
16
- }
17
- return cachedScript;
18
- }
19
-
20
- function escapeHtmlAttr(value) {
21
- return String(value)
22
- .replace(/&/g, '&amp;')
23
- .replace(/"/g, '&quot;')
24
- .replace(/</g, '&lt;')
25
- .replace(/>/g, '&gt;');
26
- }
27
-
28
- /**
29
- * The page must stay a top-level window: it cannot be framed, it does not
30
- * isolate its opener (COOP would null `window.opener`), and it sends no
31
- * Referer back out.
32
- *
33
- * @param {number} port
34
- */
35
- export function bridgeSecurityHeaders(port) {
36
- return {
37
- 'Content-Security-Policy': [
38
- "default-src 'none'",
39
- "script-src 'self'",
40
- "style-src 'unsafe-inline'",
41
- `connect-src ws://127.0.0.1:${port} ws://localhost:${port}`,
42
- "base-uri 'none'",
43
- "form-action 'none'",
44
- "frame-ancestors 'none'",
45
- ].join('; '),
46
- 'X-Frame-Options': 'DENY',
47
- 'X-Content-Type-Options': 'nosniff',
48
- 'Referrer-Policy': 'no-referrer',
49
- 'Cross-Origin-Opener-Policy': 'unsafe-none',
50
- 'Cache-Control': 'no-store',
51
- };
52
- }
53
-
54
- /**
55
- * DNS-rebinding guard: only answer for the loopback host names the
56
- * SurfCAD tab actually opens.
57
- *
58
- * @param {string | undefined} hostHeader
59
- * @param {number} port
60
- */
61
- export function isBridgeHostAllowed(hostHeader, port) {
62
- if (typeof hostHeader !== 'string') return false;
63
- const host = hostHeader.trim().toLowerCase();
64
- return host === `127.0.0.1:${port}` || host === `localhost:${port}`;
65
- }
66
-
67
- /**
68
- * @param {{ extraOrigins?: string[] }} [opts]
69
- */
70
- export function bridgePageHtml(opts = {}) {
71
- const extra = escapeHtmlAttr(JSON.stringify(opts.extraOrigins || []));
72
- return `<!doctype html>
73
- <html lang="en" data-surfcad-bridge="1" data-extra-origins="${extra}">
74
- <head>
75
- <meta charset="utf-8">
76
- <meta name="viewport" content="width=device-width, initial-scale=1">
77
- <title>SurfCAD local agent bridge</title>
78
- <style>
79
- :root { color-scheme: dark; }
80
- body { margin: 0; font: 14px/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: #15171a; color: #e6e8eb; }
81
- main { padding: 20px 22px; max-width: 420px; }
82
- h1 { font-size: 16px; margin: 0 0 8px; }
83
- p { margin: 0 0 10px; color: #b3b8bf; }
84
- #bridge-status { color: #e6e8eb; padding: 8px 10px; border: 1px solid #2c3036; border-radius: 6px; background: #1c1f23; }
85
- html[data-status="connected"] #bridge-status { border-color: #1f6f4a; color: #7ee2b0; }
86
- html[data-status="forbidden"] #bridge-status, html[data-status="invalid"] #bridge-status { border-color: #7a2d2d; color: #f2a7a7; }
87
- </style>
88
- </head>
89
- <body>
90
- <main>
91
- <h1>SurfCAD local agent bridge</h1>
92
- <p>This window connects your SurfCAD tab to the local agent running on this computer (<code>npx surfcad-mcp</code>).</p>
93
- <p><strong>Keep it open</strong> while the agent works. Closing it disconnects the agent.</p>
94
- <p id="bridge-status" role="status" aria-live="polite">Starting…</p>
95
- </main>
96
- <script type="module" src="${BRIDGE_SCRIPT_PATH}"></script>
97
- </body>
98
- </html>
99
- `;
100
- }
101
-
102
- /**
103
- * @param {import('node:http').IncomingMessage} req
104
- * @param {import('node:http').ServerResponse} res
105
- * @param {{ port: number, extraOrigins?: string[] }} opts
106
- * @returns {boolean} true when the request was a bridge route and has been answered
107
- */
108
- export function handleBridgeRequest(req, res, opts) {
109
- if (req.method !== 'GET' && req.method !== 'HEAD') return false;
110
- let pathname;
111
- try {
112
- pathname = new URL(req.url || '/', 'http://127.0.0.1').pathname;
113
- } catch {
114
- return false;
115
- }
116
- if (pathname !== BRIDGE_PAGE_PATH && pathname !== BRIDGE_SCRIPT_PATH) return false;
117
-
118
- if (!isBridgeHostAllowed(req.headers.host, opts.port)) {
119
- res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });
120
- res.end('Host not allowed\n');
121
- return true;
122
- }
123
-
124
- const isPage = pathname === BRIDGE_PAGE_PATH;
125
- const body = isPage ? bridgePageHtml({ extraOrigins: opts.extraOrigins }) : bridgeScriptSource();
126
- res.writeHead(200, {
127
- ...bridgeSecurityHeaders(opts.port),
128
- 'Content-Type': isPage ? 'text/html; charset=utf-8' : 'text/javascript; charset=utf-8',
129
- });
130
- res.end(req.method === 'HEAD' ? undefined : body);
131
- return true;
132
- }