surfcad-mcp 0.3.2 → 0.3.4

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.
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Command protocol shared by the localhost agent relay and the server relay.
3
+ *
4
+ * This is the frame around one bridge call. It is not `window.surfcad.version`
5
+ * (the in-page envelope) and not the `v` on prompt messages. Pairing and
6
+ * prompt frames stay on their own `type` names in `relayMessages.mjs`.
7
+ *
8
+ * A frame we write always carries `v`. A frame we read may omit `v`; that
9
+ * means version 1, so a peer from before this field still works on the
10
+ * localhost relay. Any other `v` is not this protocol.
11
+ *
12
+ * The server relay's handshake is stricter: `checkAgentHandshakeVersion`
13
+ * requires an explicit `v`. A missing or older `v` is too old for that
14
+ * handshake. Local reads are unchanged.
15
+ */
16
+
17
+ export const AGENT_PROTOCOL_VERSION = 1;
18
+
19
+ /**
20
+ * @typedef {{ v: number, id: string | number, command: string, args: unknown }} CommandRequest
21
+ * @typedef {{
22
+ * v: number,
23
+ * id: string | number,
24
+ * ok: true,
25
+ * result: unknown,
26
+ * } | {
27
+ * v: number,
28
+ * id: string | number,
29
+ * ok: false,
30
+ * error?: unknown,
31
+ * }} CommandResponse
32
+ */
33
+
34
+ /**
35
+ * @param {unknown} msg
36
+ * @returns {boolean}
37
+ */
38
+ export function isSupportedProtocolVersion(msg) {
39
+ if (!msg || typeof msg !== 'object') return false;
40
+ const version = /** @type {{ v?: unknown }} */ (msg).v;
41
+ return version == null || version === AGENT_PROTOCOL_VERSION;
42
+ }
43
+
44
+ /**
45
+ * @param {{ id?: string | number, command: string, args?: unknown }} fields
46
+ * @returns {CommandRequest}
47
+ */
48
+ export function commandRequest(fields) {
49
+ return {
50
+ v: AGENT_PROTOCOL_VERSION,
51
+ id: fields.id,
52
+ command: fields.command,
53
+ args: fields.args == null ? {} : fields.args,
54
+ };
55
+ }
56
+
57
+ /**
58
+ * @param {{ id?: string | number, ok: boolean, result?: unknown, error?: unknown }} fields
59
+ * @returns {CommandResponse}
60
+ */
61
+ export function commandResponse(fields) {
62
+ if (fields.ok === true) {
63
+ return { v: AGENT_PROTOCOL_VERSION, id: fields.id, ok: true, result: fields.result };
64
+ }
65
+ const frame = { v: AGENT_PROTOCOL_VERSION, id: fields.id, ok: false };
66
+ if (fields.error !== undefined) frame.error = fields.error;
67
+ return frame;
68
+ }
69
+
70
+ /**
71
+ * A command request: a string `command`, not a `pair` control frame, at a
72
+ * supported protocol version. Args that are not an object become `{}`.
73
+ * @param {unknown} msg
74
+ * @returns {CommandRequest | null}
75
+ */
76
+ export function readCommandRequest(msg) {
77
+ if (!isSupportedProtocolVersion(msg)) return null;
78
+ const frame = /** @type {{ type?: unknown, command?: unknown, id?: string | number, args?: unknown, v?: unknown }} */ (msg);
79
+ if (frame.type === 'pair') return null;
80
+ if (typeof frame.command !== 'string') return null;
81
+ return {
82
+ v: frame.v == null ? AGENT_PROTOCOL_VERSION : /** @type {number} */ (frame.v),
83
+ id: frame.id,
84
+ command: frame.command,
85
+ args: frame.args && typeof frame.args === 'object' ? frame.args : {},
86
+ };
87
+ }
88
+
89
+ /**
90
+ * A command response: an own `ok` field, not a `pair` control frame, at a
91
+ * supported protocol version. `ok` other than `true` is a failure.
92
+ * @param {unknown} msg
93
+ * @returns {CommandResponse | null}
94
+ */
95
+ export function readCommandResponse(msg) {
96
+ if (!isSupportedProtocolVersion(msg)) return null;
97
+ const frame = /** @type {{ type?: unknown, ok?: unknown, id?: string | number, result?: unknown, error?: unknown, v?: unknown }} */ (msg);
98
+ if (frame.type === 'pair') return null;
99
+ if (!Object.prototype.hasOwnProperty.call(frame, 'ok')) return null;
100
+ const version = frame.v == null ? AGENT_PROTOCOL_VERSION : /** @type {number} */ (frame.v);
101
+ if (frame.ok === true) {
102
+ return { v: version, id: frame.id, ok: true, result: frame.result };
103
+ }
104
+ const failure = { v: version, id: frame.id, ok: false };
105
+ if (frame.error !== undefined) failure.error = frame.error;
106
+ return failure;
107
+ }
108
+
109
+ /** Shown when a server-relay client speaks a protocol older than this one. */
110
+ export const AGENT_HANDSHAKE_UPDATE_MESSAGE = 'please update surfcad-mcp';
111
+
112
+ /**
113
+ * Server handshake version. Unlike `readCommandRequest`, a missing `v` is
114
+ * too old. `v` above {@link AGENT_PROTOCOL_VERSION} is a different protocol.
115
+ * @param {unknown} version
116
+ * @returns {{ ok: true, v: number } | { ok: false, error: string }}
117
+ */
118
+ export function checkAgentHandshakeVersion(version) {
119
+ if (typeof version !== 'number' || !Number.isFinite(version) || version < AGENT_PROTOCOL_VERSION) {
120
+ return { ok: false, error: AGENT_HANDSHAKE_UPDATE_MESSAGE };
121
+ }
122
+ if (version !== AGENT_PROTOCOL_VERSION) {
123
+ return { ok: false, error: `Unsupported protocol version: ${version}` };
124
+ }
125
+ return { ok: true, v: version };
126
+ }
package/src/errors.mjs CHANGED
@@ -1,5 +1,9 @@
1
+ import { AGENT_HANDSHAKE_UPDATE_MESSAGE } from './commandProtocol.mjs';
2
+
1
3
  export const RECONNECT_HINT = 'Open SurfCAD in Chrome and keep the tab open; it will reconnect.';
2
4
 
5
+ export const LOGIN_AGAIN_MESSAGE = 'This agent login is no longer valid. Run npx surfcad-mcp login again.';
6
+
3
7
  /**
4
8
  * @param {{ code?: string, message?: string, details?: unknown, hint?: string, retryable?: boolean }} err
5
9
  */
@@ -16,7 +20,7 @@ export function formatBridgeError(err) {
16
20
  export function notPairedError() {
17
21
  return {
18
22
  code: 'not_paired',
19
- message: 'Not paired to a SurfCAD tab. Set SURFCAD_PAIRING_CODE or call the pair tool, then click Allow in the app.',
23
+ message: 'Not paired to a SurfCAD tab. Set SURFCAD_PAIRING_CODE or call the pair tool and click Allow, or run npx surfcad-mcp login --code with the join code.',
20
24
  hint: pairingEnvHint(),
21
25
  };
22
26
  }
@@ -40,5 +44,80 @@ export function pairPendingError() {
40
44
  }
41
45
 
42
46
  export function pairingEnvHint() {
43
- return 'Copy the 6-character code from SurfCAD → Local agent → Show pairing code.';
47
+ return 'Copy the 8-character code from SurfCAD → Local agent → Show pairing code, or run npx surfcad-mcp login --code with the join code.';
48
+ }
49
+
50
+ export function tabAsleepError() {
51
+ return Object.assign(new Error('SurfCAD tab is asleep'), {
52
+ code: 'tab_asleep',
53
+ hint: 'Open SurfCAD in Chrome and keep that tab open, then retry this call.',
54
+ retryable: true,
55
+ });
56
+ }
57
+
58
+ export function tooManyPendingError() {
59
+ return Object.assign(new Error('Too many commands are waiting'), {
60
+ code: 'too_many_pending',
61
+ hint: 'Wait for the SurfCAD tab to finish the commands already in flight, then retry.',
62
+ retryable: true,
63
+ });
64
+ }
65
+
66
+ export function tokenRevokedError() {
67
+ return Object.assign(new Error(LOGIN_AGAIN_MESSAGE), {
68
+ code: 'token_revoked',
69
+ hint: 'Run npx surfcad-mcp login and approve the new code in SurfCAD.',
70
+ retryable: false,
71
+ });
72
+ }
73
+
74
+ /**
75
+ * @param {string} [message]
76
+ */
77
+ export function clientUpdateError(message = AGENT_HANDSHAKE_UPDATE_MESSAGE) {
78
+ const text = typeof message === 'string' && message.includes(AGENT_HANDSHAKE_UPDATE_MESSAGE)
79
+ ? AGENT_HANDSHAKE_UPDATE_MESSAGE
80
+ : (message || AGENT_HANDSHAKE_UPDATE_MESSAGE);
81
+ return Object.assign(new Error(text), {
82
+ code: 'client_update_required',
83
+ hint: 'This surfcad-mcp is too old for the agent server. Update the package, then run npx surfcad-mcp login again.',
84
+ });
85
+ }
86
+
87
+ /**
88
+ * Map a server-relay command error onto a clear Error. Leaves other errors alone.
89
+ * @param {unknown} error
90
+ */
91
+ export function asRemoteError(error) {
92
+ if (error instanceof Error) {
93
+ const code = /** @type {Error & { code?: string }} */ (error).code;
94
+ if (
95
+ code === 'tab_asleep'
96
+ || code === 'too_many_pending'
97
+ || code === 'token_revoked'
98
+ || code === 'client_update_required'
99
+ ) return error;
100
+ }
101
+ const record = error && typeof error === 'object'
102
+ ? /** @type {{ code?: unknown, message?: unknown }} */ (error)
103
+ : {};
104
+ const code = typeof record.code === 'string' ? record.code : (typeof error === 'string' ? error : '');
105
+ const message = typeof record.message === 'string'
106
+ ? record.message
107
+ : (typeof error === 'string' ? error : '');
108
+ if (code === 'tab_asleep' || message === 'SurfCAD tab is asleep') return tabAsleepError();
109
+ if (code === 'too_many_pending' || message === 'Too many commands are waiting') return tooManyPendingError();
110
+ if (code === 'token_revoked' || code === 'unauthorized' || code === '4001') return tokenRevokedError();
111
+ if (
112
+ code === 'client_update_required'
113
+ || code === AGENT_HANDSHAKE_UPDATE_MESSAGE
114
+ || message === AGENT_HANDSHAKE_UPDATE_MESSAGE
115
+ || message.includes(AGENT_HANDSHAKE_UPDATE_MESSAGE)
116
+ ) {
117
+ return clientUpdateError(message || code);
118
+ }
119
+ if (error instanceof Error) return error;
120
+ return Object.assign(new Error(message || 'Bridge call failed'), {
121
+ code: code || 'bridge_error',
122
+ });
44
123
  }
package/src/helpers.mjs CHANGED
@@ -23,7 +23,7 @@ export const HELPER_GROUPS = Object.freeze({
23
23
  blocks: ['roundedBox', 'tube', 'rectTube', 'hexPrism', 'sheetMetalSolid'],
24
24
  shapes: ['makeCrossSection', 'solveContour', 'profileCircle', 'profileRectangle', 'profilePolygon', 'makeExtrude', 'makeRevolve', 'makeLoft', 'loft', 'sweep', 'sweepPoints', 'makeSweepPath', 'rotateContour', 'offsetPlaneFrame'],
25
25
  build: ['cut', 'hollow', 'shell', 'hole', 'holeSpan', 'cboreHole', 'cskHole', 'clearanceHole', 'tapDrillHole', 'holePattern', 'holesOnContour', 'booleanBodies', 'externalBody', 'addDraft', 'draftFaces', 'moveFace', 'deleteFace'],
26
- polish: ['filletEdges', 'chamferEdges', 'filletAlongPath', 'convexEdges', 'concaveEdges', 'signedFeatureEdges', 'edge', 'edgesBetween', 'boundaryEdges'],
26
+ polish: ['filletEdges', 'chamferEdges', 'filletAlongPath', 'edgesNamed', 'convexEdges', 'concaveEdges', 'signedFeatureEdges', 'edge', 'edgesBetween', 'boundaryEdges'],
27
27
  place: ['move', 'rotateAbout', 'center', 'align', 'mirror', 'array3D', 'polarArray', 'patternOnPoints', 'getDimensions'],
28
28
  faces: ['faceNames', 'facesNamed', 'edgesOf', 'surfaceOf', 'facesByNormal', 'planarFaceAt', 'edgesByOrientation', 'workplaneFromFace', 'placeInFrame', 'transformByFrame', 'placeOnFace'],
29
29
  fasteners: ['fastenerClearanceDia', 'fastenerTapDrillDia', 'fastenerMajorDia', 'listFastenerSizes', 'resolveFastenerSize'],
@@ -0,0 +1,34 @@
1
+ import { pairPendingError } from './errors.mjs';
2
+
3
+ /** Sentinel the pairing wait resolves with when the user has not clicked Allow in time. */
4
+ const PAIR_WAIT_TIMED_OUT = Symbol('pair_wait_timed_out');
5
+
6
+ /**
7
+ * Wait up to `waitMs` for a pairing attempt. Past that it is `pair_pending`:
8
+ * the attempt keeps running in the background and the caller retries.
9
+ *
10
+ * The timer used to resolve the timeout promise with itself, which is a
11
+ * TypeError ("Chaining cycle detected for promise"): every pairing that did
12
+ * not complete in time (an old tab that never answers, status before Allow
13
+ * with a code in the env) surfaced as that message instead of pair_pending
14
+ * (MVP 3 B4). A plain sentinel now marks the timeout.
15
+ *
16
+ * @template T
17
+ * @param {Promise<T>} attempt
18
+ * @param {number} waitMs
19
+ * @returns {Promise<T>}
20
+ */
21
+ export async function waitForPairing(attempt, waitMs) {
22
+ attempt.catch(() => {});
23
+ let timer;
24
+ const timeout = new Promise((resolve) => {
25
+ timer = setTimeout(() => resolve(PAIR_WAIT_TIMED_OUT), waitMs);
26
+ });
27
+ try {
28
+ const outcome = await Promise.race([attempt, timeout]);
29
+ if (outcome === PAIR_WAIT_TIMED_OUT) throw pairPendingError();
30
+ return outcome;
31
+ } finally {
32
+ clearTimeout(timer);
33
+ }
34
+ }
@@ -20,7 +20,7 @@ const CRASH_GUIDE = 'The whole run was treated as a crash (reason timeout, out_o
20
20
 
21
21
  const NAMES_GUIDE = 'Faces and edges are addressed by the keys and names list_faces / list_feature_edges return for the current mesh. A key from before a rebuild, a display label, or a guess answers unknown_face / unknown_edge; a key that matches several patches answers ambiguous_face / ambiguous_edge with details.candidates. List again (filter and page the list on a detailed part), then select_faces { keys } or { names } with a row from that answer. Faces a helper built carry a name (feature.role) that survives upstream edits; prefer names when you will edit the part again.';
22
22
 
23
- const PAIRING_GUIDE = 'A bridge call before pair is not_paired: call pair { code } with the 6-character code from SurfCAD → Local agent → Show pairing code (or set SURFCAD_PAIRING_CODE). pair_pending means the user has not clicked Allow yet; wait and retry the same call. pair_rejected means they clicked Deny; ask before trying again. pairing_lost means the tab or relay dropped and the server re-pairs on its own: retry in a few seconds, do not ask for a new code. Webhook errors (bad_webhook_url) need a public https URL; a local session polls read_messages { wait_ms: 25000 } instead.';
23
+ const PAIRING_GUIDE = 'A bridge call before pair is not_paired: call pair { code } with the 8-character code from SurfCAD → Local agent → Show pairing code (or set SURFCAD_PAIRING_CODE). A remote session uses the join code instead: npx surfcad-mcp login --code ABCD-EFGH. pair_pending means the user has not clicked Allow yet; wait and retry the same call. pair_rejected means they clicked Deny; ask before trying again. pairing_lost means the tab or relay dropped and the server re-pairs on its own: retry in a few seconds, do not ask for a new code. Webhook errors (bad_webhook_url) need a public https URL; a local session polls read_messages { wait_ms: 25000 } instead.';
24
24
 
25
25
  const CONTOUR_GUIDE = 'open_feature on an extrude, revolve, loft or sweep that owns a contour reopens its sketch; edit_feature then patches the sketch (points, radius, width / height, polygon_preset, or tool) and confirm_feature saves the sketch and the feature in one step. no_feature_edit means nothing is open: open_feature { id } first (feature_tree {} lists ids), then edit, then confirm. sketch_cancel leaves a reopened sketch without writing.';
26
26
 
@@ -45,6 +45,13 @@ export const ERROR_HINTS = Object.freeze({
45
45
  unknown_entity: { hint: 'The sketch entity id is not in the open contour: list_sketch_entities {} and use an id from it (p0, e0, a0, ...).' },
46
46
  no_body: { hint: 'Name the body: body_index or at from list_bodies {}, face or face_id from list_faces, or select a face and pass use_selection: true.' },
47
47
  no_mesh: { hint: 'No solid is shown yet: insert a block (insert_cube, insert_cylinder, ...) or run {} the part, then call again.' },
48
+ quote_failed: { hint: 'The molding quote service did not answer: retry mold_quote once. The part is unchanged and nothing was ordered.' },
49
+ lead_failed: { hint: 'The molding request did not go through: retry mold_request_firm_quote or mold_request_human_review once. Nothing was charged.' },
50
+ sign_in: { hint: 'Sign in, then retry mold_request_firm_quote or mold_request_human_review. Nothing was saved.' },
51
+ unknown_partner: { hint: 'That public label is not an active molding partner: mold_quote, then pass an anonLabel from vendors.' },
52
+ no_lead: { hint: 'Request a human review with mold_request_human_review before mold_pay_human_review. Nothing was charged.' },
53
+ review_unavailable: { hint: 'Human review checkout is not configured. Do not retry in a loop, and do not invent a card charge.' },
54
+ rate_limited: { hint: 'Too many requests in a short window: wait, then retry the same call once. Do not loop.' },
48
55
  not_picked: { hint: 'pick_next { remove: true } named keys that are not picked: pick_next with no remove to see the live picks, or pick_clear {}.' },
49
56
  empty_pick: { hint: 'The card needs at least one pick: pick_next { keys } before pick_done, or pick_cancel {}.' },
50
57
  pick_count: { hint: 'Fewer picks than the card\'s minimum: pick_next more keys, then pick_done again.' },
@@ -107,6 +114,10 @@ export const ERROR_HINTS = Object.freeze({
107
114
  hint: 'Place it with joint_create (one call creates the joint and solves placement). Fix a base part with type fixed first.',
108
115
  guide: 'A part that touches or attaches to another part belongs in a joint. joint_create { type, picks } writes the joint and solves the placement in one call. Ground the base with type fixed and one whole-part pick { part_id }, then mate each touching part with two picks from list_faces (coincident, concentric, distance, and the other types). part_set_transform is only for a part that touches nothing. The warning does not block the call: the placement was written. A single-part document does not warn, and neither does the base part once it has a fixed joint. parts and status list the ids still in no joint as unjointedParts. Bodies, patterns, and insert_move inside one part are not assembly parts and do not warn.',
109
116
  },
117
+ joint_broken: {
118
+ hint: 'A joint stopped solving after this call (its face moved or vanished, or it now conflicts): list_joints {} shows each joint with status and reason; fix the part, joint_edit it to new picks, or joint_delete it.',
119
+ guide: 'joint_broken is a warning on a successful result: the part edit or joint commit was written, and the solve that re-runs after every part run left one or more joints failing that were not failing before. status.jointFailures { count, ids } and list_joints {} (id, name, type, status ok | broken | conflict, reason such as "Face not found on Shaft", parts, picks) show the standing state at any time. A broken joint keeps the last good placement and is left out of the solve. Fix it by editing the part so the referenced face comes back, by joint_edit { joint_id } with picks from list_faces on the new mesh, or by joint_delete { joint_id }. The joints strip shows the same joints as red chips.',
120
+ },
110
121
  no_joint_card: { hint: 'The joint card is closed: joint_open {} first, then joint_pick / joint_set_params / joint_commit.' },
111
122
  no_joint_edit: { hint: 'No joint is open for editing: joint_open {} for a new joint or joint_edit { joint_id } for an existing one.' },
112
123
  joints_unavailable: { hint: 'The joint card could not open because another card or session is open: close it (cancel_feature, sketch_cancel, sheet_exit) and call joint_create again.' },
@@ -130,6 +141,7 @@ export const ERROR_HINTS = Object.freeze({
130
141
  real_repo_blocked: { hint: 'This session cannot get consent for a real-repo write: tell the user and stop; do not loop.', guide: CONSENT_GUIDE },
131
142
  confirm_required: { hint: 'Nothing changed: ask the user (details lists what the change touches), and only then retry with confirm: true.', guide: CONSENT_GUIDE },
132
143
  pending_save: { hint: 'The write is planned offline: ask the user to Save again when online; nothing more to do now.' },
144
+ unknown_save: { hint: 'No save with that id is running or recent in this tab: a git_save that finished within its budget answered its result directly; call git_save { message } again if the save is still wanted.' },
133
145
  upgrade_required: { hint: 'Legacy vault: after the user agrees, git_upgrade_vault { confirm: true }, then git_save again.' },
134
146
  upgrade_unavailable: { hint: 'The vault cannot be upgraded from here (message says why): tell the user and stop.' },
135
147
  conflict: { hint: 'A remote edit overlaps this save: git_behind_resolve { action: "reload" | "branch", confirm: true } after the user chooses, or git_force_overwrite with confirm: true.' },
@@ -159,13 +171,18 @@ export const ERROR_HINTS = Object.freeze({
159
171
  unknown_command: { hint: 'Not a bridge command: list_commands {} shows the names.' },
160
172
  unknown_topic: { hint: 'guide {} lists the topics; error topics are errors.<code>.' },
161
173
  // Pairing and prompts (MCP side)
162
- not_paired: { hint: 'pair { code } with the code from SurfCAD → Local agent → Show pairing code, then the user clicks Allow; or set SURFCAD_PAIRING_CODE.', guide: PAIRING_GUIDE },
163
- pair_pending: { hint: 'The user has not clicked Allow yet: wait a few seconds and retry the same call; do not ask for a new code.', guide: PAIRING_GUIDE },
174
+ not_paired: { hint: 'pair { code } with the 8-character code from SurfCAD → Local agent → Show pairing code (or set SURFCAD_PAIRING_CODE), or run npx surfcad-mcp login --code with the join code from SurfCAD.', guide: PAIRING_GUIDE },
175
+ pair_pending: { hint: 'The user has not clicked Allow yet: wait a few seconds and retry the same call; do not ask for a new code. If SurfCAD shows no Allow prompt, the tab may be an older build than this server: ask the user to reload SurfCAD and pair again.', guide: PAIRING_GUIDE },
164
176
  pair_rejected: { hint: 'The user clicked Deny: ask them before calling pair again.', guide: PAIRING_GUIDE },
165
177
  pair_cancelled: { hint: 'The pairing attempt was cancelled: pair { code } again when the user is ready.', guide: PAIRING_GUIDE },
166
- pair_failed: { hint: 'Pairing failed (message): check the code (6 characters, from the open tab) and that the tab shows it, then pair again.', guide: PAIRING_GUIDE },
178
+ pair_failed: { hint: 'Pairing failed (message): check the code (8 characters, from the open tab) and that the tab shows it, then pair again.', guide: PAIRING_GUIDE },
167
179
  pairing_lost: { hint: 'The tab or relay dropped and the server re-pairs on its own: retry in a few seconds; do not ask for a new code.', guide: PAIRING_GUIDE },
168
- bad_pairing_code: { hint: 'pair { code: "......" } with the 6-character code from SurfCAD → Local agent → Show pairing code.', guide: PAIRING_GUIDE },
180
+ bad_pairing_code: { hint: 'pair { code: "........" } with the 8-character code from SurfCAD → Local agent → Show pairing code.', guide: PAIRING_GUIDE },
181
+ tab_asleep: { hint: 'Open SurfCAD in Chrome and keep that tab open, then retry this call.' },
182
+ too_many_pending: { hint: 'Wait for the SurfCAD tab to finish the commands already in flight, then retry.' },
183
+ token_revoked: { hint: 'Run npx surfcad-mcp login and approve the new code in SurfCAD.' },
184
+ client_update_required: { hint: 'This surfcad-mcp is too old for the agent server. Update the package, then run npx surfcad-mcp login again.' },
185
+ prompts_need_websocket: { hint: 'The agent WebSocket is not open. A paired session still sends status over HTTPS; retry the call. If it keeps failing, reconnect where the agent server allows wss.' },
169
186
  relay_unavailable: { hint: 'The local relay is not running: start surfcad-mcp normally (it owns the relay) or set SURFCAD_AGENT_BRIDGE_WS_URL.', guide: PAIRING_GUIDE },
170
187
  bridge_error: { hint: 'The tab refused the call without a code: status {} and retry once; tell the user if it repeats.' },
171
188
  bad_webhook_url: { hint: 'Webhooks need a public https URL (no credentials, localhost or private hosts): fix it, or poll read_messages { wait_ms: 25000 } instead.', guide: PAIRING_GUIDE },
@@ -70,7 +70,7 @@ const SELECTION = `Selection. Faces and edges are addressed by keys that survive
70
70
 
71
71
  Faces. list_faces { part_id?, filter?, page? } returns one row per face a viewport click selects, all bodies: id (f0, f1, ...), type (planar | cylindrical | curved), center, normal, axis and radius for cylinders, area, and key { at, n, area, src?, ord? } (the same fingerprint the viewport uses). frame is "local": center, normal, axis and key.at are the part's own coordinates, including on a placed part, and they match select_faces. Compose with part_get_transform when another part does not share that frame. The whole list on a detailed part is 100 KB or more: filter it in the tab. filter { kind, normalWithin: { n, deg }, minArea, maxArea, bbox: { min, max } } keeps the rows that match every given field. bbox keeps a face whose bounds overlap the box, including a large face whose center is outside it. page { offset, limit } returns one slice; omitting page returns the first 100 faces. The result carries total (after the filter), returned, offset, limit, and nextOffset when another page remains (pass offset: nextOffset). The top faces: { kind: "planar", normalWithin: { n: [0, 0, 1], deg: 5 } }. Hole walls: { kind: "cylindrical", maxArea }. Pass face_id together with its key to joint_pick so a stale id answers unknown_face instead of picking another face.
72
72
 
73
- Edges. list_feature_edges gives grouped ids e0, e1, ... (a whole edge chain, the stable choice); list_edges gives raw mesh edges. Both set frame to "local" (midpoints in the same part frame as list_faces) and take filter { between: [faceKeyA, faceKeyB], minLength, maxLength, bbox } and page.
73
+ Edges. list_feature_edges lists every edge by name, the pair of stamped faces it lies between ("plate.top~boss.side", "[k]" for one chain of a pair that meets twice, "*" glob), with the two faces' list_faces keys; that name is the stable reference (select_edges { names }, pick_next { keys }, edgesNamed(part, name) in the script) and survives edits that keep the faces. list_edges gives raw mesh edges, also with name. Legacy e0, e1 ids still resolve but renumber after edits. Both set frame to "local" (midpoints in the same part frame as list_faces) and take filter { between: [faceKeyA, faceKeyB], minLength, maxLength, bbox } and page.
74
74
 
75
75
  Picking. select_faces { keys: [...] } and select_edges { keys } set the viewport selection; select_clear {} clears faces, edges and contour picks. pick_begin → pick_next { keys: ["e3"] } → pick_done { accept: true } drives a card's pick session; a keys item is a grouped edge id (eN), a face id (fN), a face key, or an edge face pair { faceKeyA, faceKeyB }.
76
76
 
@@ -84,7 +84,7 @@ const PAINT = `Paint. Colours live on the assembly document (a colors map keyed
84
84
 
85
85
  Sequence: set_active_part { part_id } → paint_open {} → paint_set_color { color: "#rrggbb" } (hex is an alias) → paint_part {} for the whole part, or paint_faces { keys: [...] } with keys from list_faces → paint_confirm {}. paint_undo {} steps back inside the session, paint_clear {} removes the part's colours, paint_cancel {} / paint_close {} leave without writing.
86
86
 
87
- paint_open is safe straight after create_part or set_active_part: it waits up to 1.5 s for the viewport to take paint mode. Past that it answers not_ready with details.reason (prompt_working while an in-viewer prompt is being worked, or mode_not_ready) and details.retryable: true; call paint_open again. Already open answers { open: true, already: true }. Game mode is bad_view.
87
+ paint_open is safe straight after create_part or set_active_part: it waits up to 1.5 s for the viewport to take paint mode. While an in-viewer prompt is being worked it opens headless (the session runs with no card; result headless: true), so a paint during a prompt applies like any other. Past the wait it answers not_ready with details.reason (mode_not_ready) and details.retryable: true; call paint_open again.
88
88
 
89
89
  Paint writes the working copy only; nothing reaches the vault until git_save.`;
90
90
 
@@ -120,13 +120,13 @@ Instances. insert_part { part_id, instance: true, position? } adds another place
120
120
 
121
121
  Placement. ${JOINT_PLACEMENT_GUIDANCE} part_get_transform { part_id } reads a rigid placement: translation in mm, rotation as intrinsic XYZ Euler degrees. A placed part's features, previews and picks are in its own frame. list_faces, list_edges and list_feature_edges set frame to "local" (centers and edge midpoints are part-local, not world); compose them with part_get_transform when another part does not share that frame. part_set_transform { part_id, position?, rotation? } writes that placement in one assembly undo step and is only for a part that touches nothing. create_part and insert_part { position } are a rough block-out. In an assembly of two or more parts, part_set_transform, or create_part / insert_part with a position, returns warning { code: "unjointed_part", part_id, hint } when that part is in no joint. The call still succeeds. A single-part document does not warn, and neither does the base part once it has a fixed joint.
122
122
 
123
- Joints. joint_create { type, picks } is the call. type is coincident, parallel, perpendicular, distance, angle, concentric, symmetric or fixed (planar is coincident). picks come from list_faces: face_id with its key, a cylindrical face as an axis, or { part_id } alone for a whole-part pick. A face_id selects that face, including on a pattern or an instance, and is never an ambiguous axis. A real tie (two different axes) is joint_unsolvable and details.candidates lists each axis id, origin, direction and radius. joint_delete { joint_id } removes one joint and is one undo step. Fixed takes one pick; every other type takes two, one per part. Distance is mm, angle is degrees.
123
+ Joints. joint_create { type, picks } is the call. type is coincident, parallel, perpendicular, distance, angle, concentric, symmetric or fixed (planar is coincident). picks come from list_faces: face_id with its key, a cylindrical face as an axis, or { part_id } alone for a whole-part pick. A face_id selects that face, including on a pattern or an instance, and is never an ambiguous axis. A real tie (two different axes) is joint_unsolvable and details.candidates lists each axis id, origin, direction and radius. joint_delete { joint_id } removes one joint and is one undo step. Fixed takes one pick; every other type takes two, one per part. Distance is mm, angle is degrees. list_joints {} lists every joint with status (ok | broken | conflict), reason and picks; status.jointFailures { count, ids } is the short form. A joint goes broken when a later part run no longer has its face (a remesh, a moved or deleted feature) and conflict when it cannot hold with the others; the solve re-runs after every part run, so the strip's red chips and this list agree. A part edit or joint commit that leaves a joint failing returns warning { code: "joint_broken", joints, hint } and still succeeds.
124
124
 
125
125
  The Joints card is the advanced path for the same write: joint_open {} → joint_pick { part_id, face_id?, key? } (a whole part, a face with its key, or an edge) → joint_set_params { type, value?, sense?, opposed? } → joint_commit {}. Fixed takes one pick and no second reference: joint_pick { part_id } alone suggests fixed; a face pick needs joint_set_params { type: "fixed" }.
126
126
 
127
127
  Hardware. One part per unique fastener type, patterned to every place it goes: list_faces on the fastened part (cylindrical rows, filter by radius) gives each hole's center and axis in that part's frame (frame is "local"); compose with part_get_transform when the fastener does not share it. insert_pattern_points { points: [{ at, axis }, ...], up } on the fastener part places one instance per hole; insert_array3_d covers a grid. A bolt circle of holes is insert_polar_array { count, boltCircleRadius, axis, boreRadius, boreHeight } on the part being drilled (boreRadius greater than 0 subtracts the holes and does not copy the body; boreRadius 0 copies it; boltCircleRadius defaults to 0, on the axis). Do not record a bolt-circle hole pattern as a FEATURE-GAP.
128
128
 
129
- Saving. Working-copy tools never commit. git_save { message } is the one vault write; it answers consent_pending while the Allow dialog is up (retry the same call after the user clicks Allow), clean when nothing changed, and passes through pending_save, upgrade_required, conflict and repo-moved unchanged.`;
129
+ Saving. Working-copy tools never commit. git_save { message } is the one vault write; it answers consent_pending while the Allow dialog is up (retry the same call after the user clicks Allow), clean when nothing changed, and passes through pending_save, upgrade_required, conflict and repo-moved unchanged. A save is many GitHub round trips: when it is still running after about 20 s, git_save answers { status: "running", saveId } and keeps going; poll git_save_status { save_id } until it answers the save result.`;
130
130
 
131
131
  /** Topic name → one-line summary and the text. Order is the listing order. */
132
132
  export const GUIDE_TOPICS = Object.freeze({
@@ -189,13 +189,43 @@ export function createPromptSession(options) {
189
189
  for (const resolve of list) resolve();
190
190
  }
191
191
 
192
- function emit(payload) {
192
+ function asSendError(err) {
193
+ const code = err && typeof err === 'object' && typeof err.code === 'string' && err.code
194
+ ? err.code
195
+ : 'not_paired';
196
+ const message = err instanceof Error && err.message ? err.message : 'Not paired';
197
+ const out = err instanceof Error ? err : new Error(message);
198
+ if (!out.message) out.message = message;
199
+ out.code = code;
200
+ if (err && typeof err === 'object' && typeof err.hint === 'string' && !out.hint) out.hint = err.hint;
201
+ return out;
202
+ }
203
+
204
+ /**
205
+ * @param {object} payload
206
+ * @param {{ required?: boolean }} [opts]
207
+ * A required send keeps the transport's error (a connected remote session
208
+ * is not rewritten as not_paired). Advisory sends stay quiet.
209
+ */
210
+ function emit(payload, { required = false } = {}) {
211
+ let result;
193
212
  try {
194
- send(payload);
195
- return true;
196
- } catch {
213
+ result = send(payload);
214
+ } catch (err) {
215
+ if (required) throw asSendError(err);
197
216
  return false;
198
217
  }
218
+ if (result && typeof result.then === 'function') {
219
+ const pending = Promise.resolve(result).then(() => true);
220
+ if (!required) {
221
+ pending.catch(() => {});
222
+ return true;
223
+ }
224
+ return pending.catch((err) => {
225
+ throw asSendError(err);
226
+ });
227
+ }
228
+ return true;
199
229
  }
200
230
 
201
231
  function clearIdle() {
@@ -256,8 +286,9 @@ export function createPromptSession(options) {
256
286
  * @param {string | null | undefined} id
257
287
  * @param {boolean} force
258
288
  * @param {string} [label]
289
+ * @param {boolean} [required]
259
290
  */
260
- function emitState(state, id, force, label) {
291
+ function emitState(state, id, force, label, required = false) {
261
292
  const next = state !== 'idle';
262
293
  if (!force && agentState === state && !stalled) {
263
294
  if (next) armIdle();
@@ -269,7 +300,7 @@ export function createPromptSession(options) {
269
300
  const msg = { type: PAIR_MSG.AGENT_STATUS, v: 1, working: next, state };
270
301
  if (typeof id === 'string' && id) msg.id = id;
271
302
  if (typeof label === 'string' && label) msg.label = label.slice(0, 120);
272
- const sent = emit(msg);
303
+ const sent = emit(msg, { required: required === true });
273
304
  if (next) armIdle();
274
305
  else clearIdle();
275
306
  return sent;
@@ -642,22 +673,26 @@ export function createPromptSession(options) {
642
673
  text,
643
674
  ts: new Date(now()).toISOString(),
644
675
  final: isFinal,
645
- });
676
+ }, { required: true });
677
+ const finish = () => {
678
+ if (isFinal) {
679
+ queue = queue.filter((item) => item.kind === 'cancel' || item.id !== inReplyTo);
680
+ states.set(inReplyTo, 'replied');
681
+ emitStatus(false, inReplyTo, true);
682
+ } else if (agentState === 'working') {
683
+ // Building stays until the final reply. A partial reply only refreshes the stall window.
684
+ workedEpoch = promptEpoch;
685
+ noteActivity();
686
+ } else {
687
+ // A streamed reply while responding keeps the dots and restarts the window.
688
+ workedEpoch = promptEpoch;
689
+ emitState('typing', inReplyTo, false);
690
+ }
691
+ return { id: inReplyTo, final: isFinal };
692
+ };
693
+ if (sent && typeof sent.then === 'function') return sent.then(finish);
646
694
  if (!sent) throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
647
- if (isFinal) {
648
- queue = queue.filter((item) => item.kind === 'cancel' || item.id !== inReplyTo);
649
- states.set(inReplyTo, 'replied');
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();
655
- } else {
656
- // A streamed reply while responding keeps the dots and restarts the window.
657
- workedEpoch = promptEpoch;
658
- emitState('typing', inReplyTo, false);
659
- }
660
- return { id: inReplyTo, final: isFinal };
695
+ return finish();
661
696
  }
662
697
 
663
698
  /**
@@ -691,9 +726,11 @@ export function createPromptSession(options) {
691
726
  return { ok: false, error: 'cancelled' };
692
727
  }
693
728
  workedEpoch = promptEpoch;
694
- const sent = emitState(state, id || lastId, true, typeof args.label === 'string' ? args.label : undefined);
729
+ const sent = emitState(state, id || lastId, true, typeof args.label === 'string' ? args.label : undefined, true);
730
+ const payload = { working: state !== 'idle', state };
731
+ if (sent && typeof sent.then === 'function') return sent.then(() => payload);
695
732
  if (!sent) throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
696
- return { working: state !== 'idle', state };
733
+ return payload;
697
734
  }
698
735
 
699
736
  /**
@@ -796,6 +833,8 @@ export function createPromptSession(options) {
796
833
  queuedCount() {
797
834
  return promptQueueLength();
798
835
  },
836
+ /** Stall window. Local and remote sessions leave this at AGENT_PROMPT_STALL_MS. */
837
+ idleMs,
799
838
  };
800
839
  }
801
840
 
@@ -209,11 +209,11 @@ export async function callPromptTool(prompts, name, args) {
209
209
  return { content };
210
210
  }
211
211
  if (name === 'reply_to_user') {
212
- const result = prompts.reply(args);
212
+ const result = await prompts.reply(args);
213
213
  return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
214
214
  }
215
215
  if (name === 'set_status') {
216
- const result = prompts.setStatus(args);
216
+ const result = await prompts.setStatus(args);
217
217
  return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
218
218
  }
219
219
  throw Object.assign(new Error(`Unknown tool: ${name}`), { code: 'unknown_tool' });
package/src/relay.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { WebSocket } from 'ws';
2
+ import { commandRequest, readCommandResponse } from './commandProtocol.mjs';
2
3
  import { connectPeer } from './nodeClient.mjs';
3
4
  import { PAIR_MSG } from './relayMessages.mjs';
4
5
  import { redactToken } from './bridge/relayHub.mjs';
@@ -282,12 +283,14 @@ export class RelaySession {
282
283
  const waiter = id ? this.#pending.get(id) : undefined;
283
284
  if (waiter) {
284
285
  this.#pending.delete(id);
285
- if (msg.ok === true) {
286
- waiter.resolve(msg.result);
286
+ const response = readCommandResponse(msg);
287
+ if (response?.ok === true) {
288
+ waiter.resolve(response.result);
287
289
  return;
288
290
  }
289
- const error = msg.error && typeof msg.error === 'object'
290
- ? msg.error
291
+ const rawError = response?.error ?? msg.error;
292
+ const error = rawError && typeof rawError === 'object'
293
+ ? rawError
291
294
  : { code: 'bridge_error', message: 'Command refused' };
292
295
  // hint and retryable ride along when the tab sent them (the server
293
296
  // fills in a hint from its own table when it did not).
@@ -397,7 +400,7 @@ export class RelaySession {
397
400
  return new Promise((resolve, reject) => {
398
401
  this.#pending.set(id, { resolve, reject });
399
402
  try {
400
- ws.send(JSON.stringify({ id, command, args }));
403
+ ws.send(JSON.stringify(commandRequest({ id, command, args })));
401
404
  } catch {
402
405
  this.#lose(ws, 'send_failed');
403
406
  }