surfcad-mcp 0.3.9 → 0.4.1
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.
- package/README.md +71 -50
- package/bin/surfcad-mcp.js +16 -8
- package/data/commands.json +6481 -5817
- package/data/helpers.json +243 -268
- package/package.json +10 -2
- package/src/cli.mjs +296 -23
- package/src/cliCall.mjs +221 -0
- package/src/errors.mjs +8 -5
- package/src/helpers.mjs +7 -5
- package/src/importFile.mjs +186 -0
- package/src/listen/bootstrap.mjs +87 -34
- package/src/listen/claudeCodeWake.mjs +74 -0
- package/src/listen/daemon.mjs +35 -0
- package/src/listen/listenCli.mjs +121 -30
- package/src/listen/listener.mjs +138 -8
- package/src/listen/owner.mjs +293 -0
- package/src/listen/waitCli.mjs +133 -0
- package/src/listen/wake.mjs +39 -19
- package/src/listen/wakeSetupText.mjs +23 -5
- package/src/pairWait.mjs +3 -3
- package/src/pairingCode.mjs +10 -0
- package/src/prompt/buildGuidance.mjs +9 -7
- package/src/prompt/chatFlow.mjs +15 -0
- package/src/prompt/errorHints.mjs +24 -10
- package/src/prompt/guide.mjs +27 -14
- package/src/prompt/promptSession.mjs +74 -10
- package/src/prompt/promptTools.mjs +10 -6
- package/src/prompt/replyConfirm.mjs +69 -0
- package/src/relayMessages.mjs +43 -1
- package/src/remote/config.mjs +17 -13
- package/src/remote/session.mjs +103 -5
- package/src/room/roomRuntime.mjs +186 -0
- package/src/room/roomServer.mjs +112 -0
- package/src/room/roomToolSchemas.mjs +228 -0
- package/src/room/seat.mjs +334 -0
- package/src/screenshotFile.mjs +9 -0
- package/src/server.mjs +155 -111
- package/src/stepUploadLimit.mjs +8 -0
- package/src/bridge/bridgePage.mjs +0 -132
- package/src/bridge/bridgePopup.mjs +0 -288
- package/src/bridge/relayHub.mjs +0 -556
- package/src/bridge/relayServer.mjs +0 -291
- package/src/nodeClient.mjs +0 -63
- package/src/relay.mjs +0 -419
|
@@ -9,20 +9,22 @@ export const FEATURE_GAP_PREFIX = '// FEATURE-GAP:';
|
|
|
9
9
|
* The assembly-placement rule. Server instructions, guide assembly, the
|
|
10
10
|
* build-flow note, and the placement tool descriptions all use this sentence.
|
|
11
11
|
*/
|
|
12
|
-
export const JOINT_PLACEMENT_GUIDANCE = 'Fix one base part with a fixed joint, then place every part that touches or attaches to another with joint_create (one call creates the joint and solves placement). Use part_set_transform only for parts that touch nothing. Block-out positions are rough; joints set final positions.';
|
|
12
|
+
export const JOINT_PLACEMENT_GUIDANCE = 'Fix one base part with a fixed joint, then place every part that touches or attaches to another with joint_create (one call creates the joint and solves placement). Read and edit that pose with get_part_placement and set_part_placement (world centroid and XYZ rotation, free directions only, one undo; a locked direction is rejected and names the joint). part_get_transform and part_set_transform are deprecated. Use part_set_transform only for parts that touch nothing. A whole-part Move, Rotate, Center, or Align of a part in an assembly writes the Placement chip and adds no feature. One body of a multi-body part, and any part that is not in an assembly, still inserts an editable feature chip (open_feature / edit_feature). Block-out positions are rough; joints set final positions.';
|
|
13
13
|
|
|
14
14
|
/** One line for the tools that create parts and insert features. */
|
|
15
|
-
export const BUILD_FLOW_NOTE = ` Build in ribbon order: block out every part of the assembly as plain blocks first (within seconds of the prompt, then screenshot for the user), then
|
|
15
|
+
export const BUILD_FLOW_NOTE = ` Build in ribbon order: block out every part of the assembly as plain blocks first (within seconds of the prompt, then screenshot for the user), then Shape, then Join, then Polish, then pattern and place; finish each stage across the whole assembly before the next. Features first: insert_code_snippet { gap, why, script } is the fallback for one operation no feature can do (its block starts with // FEATURE-GAP: <missing feature or option> | <why the existing feature did not work>); set_script only rewrites a whole part. Hardware is one part per unique fastener type, one instance patterned to every place it goes. ${JOINT_PLACEMENT_GUIDANCE}`;
|
|
16
16
|
|
|
17
17
|
/** The full guidance, served by the MCP `guide` tool's `start` topic. */
|
|
18
18
|
export const BUILD_GUIDANCE = [
|
|
19
|
-
'How to build in SurfCAD. Work in the order of the feature ribbon: Block,
|
|
19
|
+
'How to build in SurfCAD. Work in the order of the feature ribbon: Block, Shape, Join, Polish.',
|
|
20
20
|
'1. Block out first. Within seconds of the prompt, create every part of the assembly as plain blocks (the first part already exists: create_assembly returns it as partId, the same id as activeId, already active. Build on that id and rename_part it; never call create_part for the first part. create_part is for the second part onward. Then insert_cube, insert_rounded_box, insert_cylinder, insert_sphere, insert_tube, insert_hex_prism) at roughly the right size and position (block-out positions are rough; joints set final positions), and take a screenshot so the user can approve the layout and proportions before any detail goes in. Never plan silently for long before something appears in the viewport.',
|
|
21
|
-
'2.
|
|
22
|
-
'3.
|
|
23
|
-
|
|
21
|
+
'2. Shape. Shape each block into its real form: insert_workplane, insert_cross_section, insert_make_extrude, insert_make_revolve, insert_make_sweep, insert_make_loft, insert_shell, insert_add_draft (sketch_* and slot_* for the profiles). Sheet metal is the Metal section between Shape and Join.',
|
|
22
|
+
'3. Join. Hole card (hole_open → hole_set_params → hole_begin_centres → plane_set / sketch_accept_plane → hole_centres_grid / hole_centres_polar / pick_points → hole_commit), insert_boss (or boss_open … boss_commit), insert_cut, insert_boolean, then insert_move, insert_rotate, insert_center, insert_align for bodies inside one part. The Joints button (joint_open) sits after Boolean and before Move.',
|
|
23
|
+
'4. Polish. insert_fillet_edges, insert_chamfer_edges, insert_move_face, insert_delete_face. Blend order is required: after the shell, concave fillets and chamfers before convex ones, with the edges picked by name (guide { topic: "modeling" }).',
|
|
24
|
+
`5. Pattern and place. insert_array3_d (grid; the Array button is on Block), insert_polar_array (polar body array; copies a body around an axis), and insert_pattern_points (one copy at every hole center and axis from list_faces; Array Type=Points) for repeats and hardware, and insert_mirror (Mirror, on Block) for a reflected body. Move, Rotate, Center, and Align are the Join buttons. ${JOINT_PLACEMENT_GUIDANCE}`,
|
|
24
25
|
'Finish each stage across the whole assembly before starting the next, and take a screenshot after each stage.',
|
|
25
26
|
'Modeling rules: guide { topic: "modeling" }; molded parts: guide { topic: "molding" }, and run mold_fit before Polish.',
|
|
26
27
|
'Features first. Use insert_* or invoke_helper whenever a feature can do the job. When no feature can, add a script snippet feature with insert_code_snippet { gap, why, script }: one operation, not the whole part, kept next to the other features. Its block starts with a gap comment in this exact form so it can be searched: // FEATURE-GAP: <missing feature or option> | <why the existing feature did not work>. Example: // FEATURE-GAP: sweep along 3D path | the frame tube follows a curve and extrude only goes straight. set_script is only for rewriting a whole part.',
|
|
27
|
-
'
|
|
28
|
+
'Holes. Every hole — single, grid, bolt circle, or free centres — is one Hole card (hole_open → hole_set_params { type, size, fit, dia, through, throughAll, depth, nearKind, nearDia, nearDepth, farKind, farDia, farDepth, side } → hole_begin_centres → plane_set / sketch_accept_plane → centres → hole_commit). Group holes by function: one Hole card per group that shares a function, size, and end treatment. Inside the centres sketch, use hole_centres_grid { n, m, spacingU, spacingV, rotation?, origin? } for an editable rectangular grid, hole_centres_polar { count, radius, startAngle?, center? } for an editable bolt circle, or pick_points { kind: "point", keys: [{ at: [u, v] }, …] } for individual/irregular centres. through: true defaults to up-to-next (stops at the first exit from material, never drilling across an air gap); pass throughAll: true only when you want to drill through the whole part across air gaps.',
|
|
29
|
+
'Hardware. Give each unique fastener type its own part named by its spec (Bolt M5x12 SHCS, Nut M5 nylock, Star nut 1-1/8"); two fasteners are the same type only when size, length, and head style all match. Model one instance per part and pattern it to every place it goes: list_faces on the part it fastens gives each hole center and axis in the fastened part frame (result.frame is "local"); compose with part_get_transform when the fastener does not share that frame, then pass them to insert_pattern_points { points: [{ at, axis }, …], up } on the fastener part (insert_array3_d for a regular grid). A bolt circle of holes in the part being drilled is one Hole card with hole_centres_polar, not insert_polar_array and not a FEATURE-GAP snippet. Run the pattern again when the holes move. Never one part that holds every fastener, never a copy-paste loop. Do hardware in the pattern-and-place stage, after the parts it fastens are finished.',
|
|
28
30
|
].join('\n');
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The standard SurfCAD chat turn, for a session woken by a chat message.
|
|
3
|
+
* One copy: the wake payload's `instruction` and `guide { topic: "chat" }`.
|
|
4
|
+
* Generic on purpose: no host name and no machine.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** A wake run is already paired. It must not start login or pair again. */
|
|
8
|
+
export const WAKE_NO_REPAIR = 'Do not run login or pair from a wake run. If a call says the session token is invalid (token_revoked or expired), do not pair again: a fresh pairing code is needed. Say that to the user if a reply still goes through; otherwise report it to your host.';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* What to do with the message. `set_status responding` is the ack that
|
|
12
|
+
* drives the jumping dots. A short non-final reply is only when the work
|
|
13
|
+
* will take a while. The final reply is how the user sees that you are done.
|
|
14
|
+
*/
|
|
15
|
+
export const WAKE_CHAT_FLOW = 'Call read_messages { wait_ms: 10000 } to fetch the message and its images (up to four; they follow the message as image blocks, and the message says image_count when there is more than one). Immediately set_status { state: "responding", id: <prompt id> } before any other work (the jumping dots). If the work will take a while, reply_to_user { in_reply_to: <id>, text: <one short acknowledgement>, final: false }. Do the work. Finish with reply_to_user { in_reply_to: <id>, final: true } that says what you did, so the user can see it is done. On failure or partial completion, say what was done, what failed and why, and what is left.';
|
|
@@ -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:
|
|
23
|
+
const PAIRING_GUIDE = 'A bridge call before pair is not_paired: run npx surfcad-mcp login --code ABCD-EFGH with the join code from SurfCAD → Connect Agent (the hyphen is optional), then call pair {}. pair_pending means the saved login is still connecting; wait and retry the same call. pairing_lost means the tab or server 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; otherwise poll read_messages { wait_ms: 25000 }.';
|
|
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
|
|
|
@@ -82,6 +82,10 @@ export const ERROR_HINTS = Object.freeze({
|
|
|
82
82
|
delete_failed: { hint: 'The block could not be removed from the editor: feature_tree {} again and retry delete_feature with the current id.' },
|
|
83
83
|
no_write_part: { hint: 'The active part is not writable (none active or still loading): parts {} then set_active_part { part_id }, and retry.' },
|
|
84
84
|
part_mismatch: { hint: 'part_id is not the active part: set_active_part { part_id } first, or pass the active id from parts {}.' },
|
|
85
|
+
part_claimed: { hint: 'Someone else in the room is editing that part and nothing was written: request_part { part_id } to ask for it, room_state {} to see who holds what, or work on another part.' },
|
|
86
|
+
read_only: { hint: 'This seat cannot make that change in the room: a view-only seat changes nothing, and a guest cannot add a comment in a room that does not share comments. Tell the user; a view-only seat needs an invite that can edit.' },
|
|
87
|
+
unknown_comment: { hint: 'Not a comment thread id: call list_comments {} and pass a thread\'s id. A resolved thread is listed only when the call asks for resolved ones.' },
|
|
88
|
+
no_solid: { hint: 'That part has no solid on screen to find the face or edge on: make it visible with set_part_visible, run {} and check status {}, then retry; or anchor the comment with { point: [x, y, z] }.' },
|
|
85
89
|
unknown_helper: { hint: 'Not a helper id: list_commands { group: "insert" } lists the insert_* tools, invoke_helper takes a HELPER_PALETTE id.' },
|
|
86
90
|
unknown_chip: { hint: 'The chip id is not in the strip: feature_tree {} lists the current chips.' },
|
|
87
91
|
unknown_sku: { hint: 'Not a fastener size: pass size as "M3", "M5", "1/4-20", ...; listFastenerSizes() in a script lists them.' },
|
|
@@ -94,6 +98,10 @@ export const ERROR_HINTS = Object.freeze({
|
|
|
94
98
|
no_sketch: { hint: 'Sketch mode is closed: sketch_begin { plane } first, or open_feature on a contour feature to reopen its sketch.' },
|
|
95
99
|
sketch_open: { hint: 'A sketch or slot card is already open: sketch_commit or sketch_cancel it, then sketch_begin.' },
|
|
96
100
|
plane_card_open: { hint: 'Accept the plane first: sketch_begin { plane, accept_plane: true } or sketch_accept_plane {}, then sketch_add.' },
|
|
101
|
+
no_boss_card: { hint: 'The Boss card is not open: boss_open {} first, then boss_set_params { face, size, height, ... }, then boss_begin_centres {}.' },
|
|
102
|
+
no_face: { hint: 'The Boss card has no face yet: boss_set_params { face: "<name from list_faces>" } (or pick_faces / select_faces on a flat face), then boss_begin_centres {}.' },
|
|
103
|
+
no_boss_sketch: { hint: 'The boss centres sketch is not open: boss_begin_centres {} after the card has a face, add centres with sketch_add / pick_points, then boss_commit {}.' },
|
|
104
|
+
no_hole_sketch: { hint: 'The Hole centres sketch is not open: call hole_open → hole_set_params → hole_begin_centres → sketch_accept_plane before hole_centres_grid / hole_centres_polar.' },
|
|
97
105
|
empty_sketch: { hint: 'Nothing is drawn: sketch_add { tool, ... } at least one closed profile before sketch_commit, or sketch_cancel.' },
|
|
98
106
|
invalid_profile: { hint: 'The profile params are invalid (message names the field): fix radius / width / height / points and sketch_add again.' },
|
|
99
107
|
no_profile: { hint: 'The feature needs a closed profile: sketch a contour (sketch_begin → sketch_add → sketch_commit) or pass one with insert_cross_section first.' },
|
|
@@ -104,7 +112,7 @@ export const ERROR_HINTS = Object.freeze({
|
|
|
104
112
|
slot_not_ready: { hint: 'A required contour slot is empty: slot_assign_contour each slot, then slot_commit.' },
|
|
105
113
|
commit_failed: { hint: 'The commit was refused (message is the toast): fix the sketch or params it names and commit again; sketch_cancel leaves.' },
|
|
106
114
|
dimension_failed: { hint: 'The dimension could not be applied: check the entity ids with list_sketch_entities and that the value is finite.' },
|
|
107
|
-
constraint_failed: { hint: 'The constraint could not be solved: remove a conflicting one
|
|
115
|
+
constraint_failed: { hint: 'The constraint could not be solved: remove a conflicting one or change the value and retry.' },
|
|
108
116
|
// Documents, parts, assemblies
|
|
109
117
|
unknown_part: { hint: 'Not an open part id (paths and names are never ids): parts {} and pass a row\'s id.' },
|
|
110
118
|
unknown_assembly: { hint: 'Not a saved assembly id: list_assemblies {} and pass a row\'s id.' },
|
|
@@ -124,7 +132,9 @@ export const ERROR_HINTS = Object.freeze({
|
|
|
124
132
|
joint_unsolvable: { hint: 'The solver refused that joint (details.reason is its message; details.candidates lists id, origin, direction and radius when more than one axis matches): pass face_id from list_faces, or pick one of those candidates. Concentric needs two cylindrical faces. Nothing was written.' },
|
|
125
133
|
part_still_referenced: { hint: 'Another assembly lists this part: delete it with scope: "assembly", or delete those parents first.' },
|
|
126
134
|
delete_refused: { hint: 'The delete was refused and nothing was written: tell the user the message and do not retry until they ask again.' },
|
|
127
|
-
origin_blocked: { hint: 'This change would move the assembly origin: place the part with
|
|
135
|
+
origin_blocked: { hint: 'This change would move the assembly origin: place the part with set_part_placement instead.' },
|
|
136
|
+
dof_locked: { hint: 'That direction is locked by a joint (the message names it). get_part_placement lists the free directions. Change a free one with set_part_placement; do not retry the locked field.' },
|
|
137
|
+
part_drag: { hint: 'A freeform drag is in progress on this part. Wait until the drag ends, then retry set_part_placement or part_set_transform.' },
|
|
128
138
|
off_study_part: { hint: 'The FEA study belongs to another part: set_active_part to the study\'s part (fea_state {} names it) and retry.' },
|
|
129
139
|
no_fea: { hint: 'No FEA study is open: fea_open {} (or the study tool the description names) first.' },
|
|
130
140
|
no_paint_mode: { hint: 'Paint mode is closed: paint_open {} first (it waits up to 1.5 s for the viewport), or use paint { color } for one call.' },
|
|
@@ -159,6 +169,9 @@ export const ERROR_HINTS = Object.freeze({
|
|
|
159
169
|
bad_view: { hint: 'view must be iso, front, back, right, left, top, bottom, side, front_of_model or normal_to_sketch; or pass position and target.' },
|
|
160
170
|
camera_failed: { hint: 'The viewport could not apply the camera: camera_fit {} then camera_set again.' },
|
|
161
171
|
screenshot_failed: { hint: 'The viewport returned no image: camera_fit {}, wait a moment, then screenshot { save_to: true } again.' },
|
|
172
|
+
import_failed: { hint: 'The file did not become a part (message): check that it is a closed solid in a supported format (.step, .stp, .stl, .obj, .3mf). STEP must be 200 MB or smaller; STL, OBJ, and 3MF must be 32 MiB or smaller. Retry import_model once.' },
|
|
173
|
+
unknown_upload: { hint: 'That upload is no longer open (uploads expire after 10 minutes): send the file again from index 0.' },
|
|
174
|
+
too_large: { hint: 'STEP files over 200 MB, and STL, OBJ, or 3MF over 32 MiB, are refused. Export a smaller model and import that.' },
|
|
162
175
|
screenshot_save_failed: { hint: 'The PNG could not be written on the MCP host (message): pass save_to with a writable path, or save_to: true for a temp file.' },
|
|
163
176
|
unsupported_format: { hint: 'format must be png or jpeg (screenshot) or stl, 3mf, step (export).' },
|
|
164
177
|
export_failed: { hint: 'The mesh could not be exported (message): run {} the part to a runState of ok, then export again.' },
|
|
@@ -168,18 +181,19 @@ export const ERROR_HINTS = Object.freeze({
|
|
|
168
181
|
bad_call: { hint: 'The call shape is wrong (message): pass arguments as an object with the keys the tool schema names.' },
|
|
169
182
|
internal: { hint: 'The command threw unexpectedly: retry once; if it repeats, status {} and tell the user with the message.' },
|
|
170
183
|
refused: { hint: 'The tab refused this call (message says why): fix what it names and call again.' },
|
|
184
|
+
has_dependents: { hint: 'Other sheet features depend on this one (details lists them): delete those dependents first with delete_feature, or delete the whole sheet block.' },
|
|
171
185
|
forbidden: { hint: 'This call is not allowed for the agent (message): ask the user to do it in the SurfCAD UI.' },
|
|
172
186
|
unknown_tool: { hint: 'Not a tool of this server: list_commands { group } or the tools list shows the names.' },
|
|
173
187
|
unknown_command: { hint: 'Not a bridge command: list_commands {} shows the names.' },
|
|
174
188
|
unknown_topic: { hint: 'guide {} lists the topics; error topics are errors.<code>.' },
|
|
175
189
|
// Pairing and prompts (MCP side)
|
|
176
|
-
not_paired: { hint: '
|
|
177
|
-
pair_pending: { hint: 'The
|
|
190
|
+
not_paired: { hint: 'Run npx surfcad-mcp login --code with the join code from SurfCAD → Connect Agent (ABCD-EFGH; the hyphen is optional), then call pair {}.', guide: PAIRING_GUIDE },
|
|
191
|
+
pair_pending: { hint: 'The saved login is still connecting: wait a few seconds and retry the same call; do not ask for a new code.', guide: PAIRING_GUIDE },
|
|
178
192
|
pair_rejected: { hint: 'The user clicked Deny: ask them before calling pair again.', guide: PAIRING_GUIDE },
|
|
179
|
-
pair_cancelled: { hint: 'The pairing attempt was cancelled
|
|
180
|
-
pair_failed: { hint: 'Pairing failed
|
|
193
|
+
pair_cancelled: { hint: 'The pairing attempt was cancelled. Run npx surfcad-mcp login --code again, then call pair {}.', guide: PAIRING_GUIDE },
|
|
194
|
+
pair_failed: { hint: 'Pairing failed. Check the join code from Connect Agent and run npx surfcad-mcp login --code again, then call pair {}.', guide: PAIRING_GUIDE },
|
|
181
195
|
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 },
|
|
182
|
-
bad_pairing_code: { hint: '
|
|
196
|
+
bad_pairing_code: { hint: 'Run npx surfcad-mcp login --code ABCD-EFGH with the join code from Connect Agent. The hyphen is optional. Then call pair {}.', guide: PAIRING_GUIDE },
|
|
183
197
|
tab_asleep: { hint: 'Open SurfCAD in Chrome and keep that tab open, then retry this call. A long mold_* analysis does not hold the call: after about 30 s it answers { status: "running", jobId } and mold_status { job_id } returns the next heartbeat or the result. Keep the tab in the foreground.' },
|
|
184
198
|
command_timeout: { hint: 'The tab is awake but this command ran past its budget (120 s for mold_*, 30 s otherwise). Retry once with the tab in the foreground; for mold_* pass pull to skip the direction search.' },
|
|
185
199
|
too_many_pending: { hint: 'Wait for the SurfCAD tab to finish the commands already in flight, then retry.' },
|
|
@@ -187,11 +201,11 @@ export const ERROR_HINTS = Object.freeze({
|
|
|
187
201
|
expired: { hint: 'The pairing expired, get a new join code in SurfCAD, then run npx surfcad-mcp login again.' },
|
|
188
202
|
client_update_required: { hint: 'This surfcad-mcp is too old for the agent server. Update the package, then run npx surfcad-mcp login again.' },
|
|
189
203
|
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.' },
|
|
190
|
-
relay_unavailable: { hint: 'The
|
|
204
|
+
relay_unavailable: { hint: 'The server relay is not reachable. Check the saved login and SURFCAD_AGENT_SERVER, then run npx surfcad-mcp login --code again.', guide: PAIRING_GUIDE },
|
|
191
205
|
bridge_error: { hint: 'The tab refused the call without a code: status {} and retry once; tell the user if it repeats.' },
|
|
192
206
|
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 },
|
|
193
207
|
no_request: { hint: 'in_reply_to is not an open prompt id: read_messages {} lists the queued prompts.' },
|
|
194
|
-
unknown_prompt: { hint: 'in_reply_to is not a prompt this
|
|
208
|
+
unknown_prompt: { hint: 'in_reply_to is not a prompt in this paired chat. Use the id from read_messages or from the wake payload. An id another session of this same chat already read is valid. An id that does not exist, or that belongs to someone else, is refused. Omit in_reply_to to post a plain-text note when you have no prompt id.' },
|
|
195
209
|
reply_too_long: { hint: 'Shorten the reply (message gives the limit) or send it in several reply_to_user calls with final on the last.' },
|
|
196
210
|
});
|
|
197
211
|
|
package/src/prompt/guide.mjs
CHANGED
|
@@ -9,7 +9,8 @@
|
|
|
9
9
|
*
|
|
10
10
|
* Every statement here describes the current tool contract; the catalog
|
|
11
11
|
* (data/commands.json) and docs/agent/SKILL.md are the sources. Keep each
|
|
12
|
-
* topic under 1,
|
|
12
|
+
* topic under 1,800 words. `chat` carries the wake setup and the wake-run
|
|
13
|
+
* flow, so it is the long one.
|
|
13
14
|
*/
|
|
14
15
|
import { BUILD_GUIDANCE, JOINT_PLACEMENT_GUIDANCE } from './buildGuidance.mjs';
|
|
15
16
|
import {
|
|
@@ -22,6 +23,7 @@ import {
|
|
|
22
23
|
READ_MESSAGES_POLL_MS,
|
|
23
24
|
WEBHOOK_REQUIRED_GUIDANCE,
|
|
24
25
|
} from './promptTools.mjs';
|
|
26
|
+
import { WAKE_NO_REPAIR } from './chatFlow.mjs';
|
|
25
27
|
import { WAKE_GUIDE_SECTION } from '../listen/wakeSetupText.mjs';
|
|
26
28
|
import { agentPromptStallMinutes } from './promptStall.mjs';
|
|
27
29
|
import {
|
|
@@ -44,7 +46,7 @@ const START = `${BUILD_GUIDANCE}
|
|
|
44
46
|
|
|
45
47
|
Quick start, three calls after pair:
|
|
46
48
|
1. create_assembly { name: "Hub", part_name: "Hub" } then insert_tube { outerRadius: 20, innerRadius: 14, height: 40 }. create_assembly's result partId is the first part, already active: build on it and never call create_part for it (create_part { name } adds the second part onward, and its result carries that part's opaque partId). Numbers are mm.
|
|
47
|
-
2.
|
|
49
|
+
2. select_faces { names: ["tube1.top"] } → hole_open {} → hole_set_params { type: "tapDrill", size: "M5", through: true } → hole_begin_centres {} → sketch_accept_plane {} → hole_centres_polar { count: 4, radius: 17 } → hole_commit {}.
|
|
48
50
|
3. paint_open {} → paint_set_color { color: "#2f6fdb" } → paint_part {} (or paint_faces { keys }) → paint_confirm {}.
|
|
49
51
|
Then select_clear {} → camera_set { view: "iso" } → screenshot { save_to: true } and show the user.
|
|
50
52
|
|
|
@@ -53,7 +55,7 @@ Ids are opaque surf ids from parts, list_assemblies, create_part, create_assembl
|
|
|
53
55
|
Topics: guide { topic: "dialect" | "features" | "selection" | "paint" | "limits" | "camera" | "assembly" | "modeling" | "molding" | "chat" }; list_helpers { names } documents any script helper.
|
|
54
56
|
In-viewer chat is a required workflow, not a tip: read guide { topic: "chat" } after every pair and follow it for every prompt the user sends from the SurfCAD chat box (register_webhook after every pair, ack first, the ${READ_MESSAGES_POLL_MS / 1000} second read_messages long-poll while connected).
|
|
55
57
|
|
|
56
|
-
In-viewer prompt pane. ${CLOSING_REPLY_GUIDANCE} set_status is for progress and does not close the task. ${BUILDING_STATUS_GUIDANCE} Be interactive: post_progress while you work, especially during long reasoning. A fresh surfcad-mcp process per tool call is normal and stays present. A long-lived process is optional and nothing depends on it.
|
|
58
|
+
In-viewer prompt pane. ${CLOSING_REPLY_GUIDANCE} set_status is for progress and does not close the task. ${BUILDING_STATUS_GUIDANCE} Be interactive: post_progress while you work, especially during long reasoning. A fresh surfcad-mcp process per tool call is normal and stays present. A long-lived process is optional and nothing depends on it. Do not call close_session after a task: the user may answer minutes later, and the chat stays with you. Every tool result carries pendingPrompts while a chat message waits: read_messages at once when you see it. state "responding" (alias typing) is the bouncing dots after the user sends. Listing parts, faces, edges, or transforms, status, and read_messages never start building. Building stays until the closing reply. reply_to_user takes an in_reply_to that belongs to this paired chat, including one another session read (a wake run or a one-shot call). An id that does not exist, or that belongs to someone else, is unknown_prompt and is not shown. Omit in_reply_to to post one plain-text message to this paired session when no prompt is waiting (not a prompt id, one per second). After read_messages acks a prompt, that id stays in the response's recent list (the last 50 prompts in this session, oldest first, each { id, state }), including on a later empty read_messages {} and on a remote session. An idle session that has not received a prompt has recent: [].
|
|
57
59
|
|
|
58
60
|
${PROMPT_TURN_GUIDANCE}`;
|
|
59
61
|
|
|
@@ -78,7 +80,7 @@ What the markers buy you:
|
|
|
78
80
|
|
|
79
81
|
Script snippet feature. When no insert_* can do an operation, insert_code_snippet { gap, why, script } adds one block (its first line is // FEATURE-GAP: <missing feature or option> | <why the existing feature did not work>); script reads and sets part. Use set_script { part_id, source } only to rewrite a whole part; part_id must be the active part. Never redeclare a reserved helper name (cut, hole, shell, filletEdges, convexEdges, ...; the set_script description lists them): rename your variable.
|
|
80
82
|
|
|
81
|
-
Sketch sessions. sketch_begin → sketch_add { tool, ... } / pick_points { kind, keys } → sketch_commit saves a contour; sketch_cancel
|
|
83
|
+
Sketch sessions. sketch_begin → sketch_add { tool, ... } / pick_points { kind, keys } → sketch_commit saves a contour; sketch_cancel is the rail X, and on a new sketch it also removes a contour that sketch_dimension, sketch_constrain or sketch_offset already wrote (removedContour). A saved contour opened for edit is left as it was saved. If a feature already uses the new contour, the same confirm the X shows stays up and the contour is kept (keptContour). An axis preset (plane_set { preset: "x" | "y" | "z", offset? } or sketch_begin { plane: "x" | "y" | "z", offset? }) always sits on the world plane through [0, 0, 0] with offset along the world axis (unaffected by prior face selection or bounding box); sketch_begin, plane_set, and sketch_accept_plane return the resolved plane { center, normal, x, y, preset, offset }. A second closed sketch_add adds a loop on the same sketch. A rectangle or polygon arrives with its shape held and no sizes: sketch_dimension adds them. sketch_offset { face: "cube1.top", distance } or { edges: [...], distance } offsets a face outline or model edges and adds only the offset; distance 0 traces the outline. insert_make_extrude { height, contour? } extrudes that contour (omitted: the newest saved contour no feature uses yet). insert_make_revolve { contour?, angle?, axis?, sense?, axisOffset?, axisLine?, combine? } revolves it about v, u, -v, -u (shifted by axisOffset in sketch-plane mm) or a sketch line entity (axisLine). slot_assign_contour on Extrude accepts several contours; loop_role is auto, outer, or hole. In-contour entities are p0, e0, a0, ...; a saved contour is @contour id=c1 in the script. Centres cards: hole_open → hole_set_params { type, size, fit, dia, through, throughAll, depth, nearKind, nearDia, nearDepth, farKind, farDia, farDepth, side } → hole_begin_centres → plane_set → sketch_accept_plane → hole_centres_grid / hole_centres_polar / pick_points { kind: "point", keys: [{ at: [u, v] }, ...] } → hole_commit writes holesOnContour (through: true stops at the first exit from material; throughAll: true drills across air gaps; side 1 is In, −1 is Out); boss_open → boss_set_params { face: "cube1.top", size, height, hole, through } → boss_begin_centres (the face is the plane, no plane card) → sketch_add / pick_points → boss_commit writes bossesOnContour.`;
|
|
82
84
|
|
|
83
85
|
const SELECTION = `Selection. Faces and edges are addressed by keys that survive a rerun of the same script and are invalid after a remesh.
|
|
84
86
|
|
|
@@ -112,10 +114,12 @@ After a timeout. undo waits for the replaced worker, re-runs the restored script
|
|
|
112
114
|
|
|
113
115
|
Result sizes. Over MCP every model-changing tool defaults to return: "status" (no script echo). "summary" adds status.features, "full" echoes the script. Read scripts with get_script, one span with get_script { range }. list_commands { group } returns one tool group (core, feature, insert, pick, sketch, document, joint, paint, measure, fea, sheet, git, export, view, agent); list_commands { names } just those rows; no args is the bridge catalog plus every MCP-only tool this server registers (pair, guide, list_helpers, reply_to_user, set_status, and the other prompt tools) in the agent group.
|
|
114
116
|
|
|
115
|
-
Pairing. A bridge call before pair is not_paired
|
|
117
|
+
Pairing. A bridge call before pair is not_paired: run npx surfcad-mcp login --code with the join code from Connect Agent, then call pair {}. pair_pending means the saved login is still connecting. pairing_lost means the tab or server relay dropped and the server re-pairs on its own: retry in a few seconds, do not ask for a new code. Numbers are finite and within ±1,000,000 mm; NaN and Infinity are bad_args.`;
|
|
116
118
|
|
|
117
119
|
const CAMERA = `Camera and screenshots.
|
|
118
120
|
|
|
121
|
+
Model space is Z-up, millimetres, right-handed. A part stands on the ground with its base toward -Z. Stock SolidWorks STEP is Y-up and imports lying on its side; do not rotate a body so Y is up to match that template. The light-theme contact shadow is a viewport disc, not geometry.
|
|
122
|
+
|
|
119
123
|
Named views place the camera on one side of the target and look back at it, Z up: iso (camera at +X +Y +Z), front (camera on -Y, looking +Y, so you see the -Y face), back (camera on +Y), right (camera on +X, looking -X, so you see the +X face), left (camera on -X), top (camera on +Z, looking down, -Y up on screen), bottom (camera on -Z), normal_to_sketch (square to the open sketch plane). For a model whose length runs along X, "right" is therefore an end view, not a side elevation; use an explicit pose for that: camera_set { position: [cx, cy - d, cz], target: [cx, cy, cz] } looks along +Y with X across the screen (up defaults to [0, 0, 1] and the view never rolls; fov is optional).
|
|
120
124
|
|
|
121
125
|
A named view frames the whole assembly as placed, or the highlighted part alone while one is selected (set_active_part or select_parts highlights it; select_clear returns to the assembly), so no camera_fit is needed after it. camera_fit {} frames the model.
|
|
@@ -132,13 +136,13 @@ Reuse. insert_part { part_id } or { assembly_id } inserts by reference (the same
|
|
|
132
136
|
|
|
133
137
|
Instances. insert_part { part_id, instance: true, position? } adds another placement of a part already in the open assembly: a new row with its own id, name ("Roller (2)"), pose and visibility that shares the definition's script, run and undo history, so set_script on any one rebuilds all of them from one run. parts lists such rows with instanceOf (the definition id). Joints, part_set_transform, set_part_visible and paint act on the one row; set_script, list_faces, export and FEA act on the shared definition. delete_part on an instance keeps the script while another row still places it; the last row to go takes the script with it. Use instances for repeated hardware (rollers, bolts) instead of copies, and joint_create to place each one that touches another. Patterns and instances inside one part (insert_array3_d, insert_polar_array, insert_pattern_points, insert_move) are bodies of that part, not assembly parts.
|
|
134
138
|
|
|
135
|
-
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.
|
|
139
|
+
Placement. ${JOINT_PLACEMENT_GUIDANCE} The Placement chip is the one control for a part's pose. get_part_placement { part_id } reads its world centroid and rotation and which directions are free. set_part_placement { part_id, centroid?, rotation? } writes them. Move, Rotate, Center, and Align Z keep their cards. A whole-part transform of a part in an assembly writes the Placement chip and adds no feature. One body of a multi-body part, and any part that is not in an assembly, still inserts an editable feature chip (open_feature / edit_feature). 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.
|
|
136
140
|
|
|
137
141
|
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.
|
|
138
142
|
|
|
139
143
|
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" }.
|
|
140
144
|
|
|
141
|
-
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
|
|
145
|
+
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 on the part being drilled is one Hole card with hole_centres_polar { count, radius, startAngle?, center? }, not insert_polar_array (which is a body array only) and not a FEATURE-GAP.
|
|
142
146
|
|
|
143
147
|
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, unsupported_vault_version, conflict and repo-moved unchanged. Checked out on main, git_save and git_add_to_repo answer save_on_main and write nothing: git_branch_create { name }, then git_save { message } on that branch. 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.`;
|
|
144
148
|
|
|
@@ -147,11 +151,11 @@ const MODELING = `3D modeling guidelines. Follow these on every part; for a part
|
|
|
147
151
|
First part (rule). create_assembly already made the first part: an empty seed part, already active. Its result partId (the same id as activeId) is that part. Build the first part on that id: name it with create_assembly { part_name } or rename_part { part_id, name }, then insert_*. Do not call create_part for the first part; create_part is for the second part onward. After the first body the assembly has exactly one part (parts {} lists one row) and no empty "Part (1)" beside it.
|
|
148
152
|
|
|
149
153
|
Order of operations (required technique).
|
|
150
|
-
- Block out with primitives, then
|
|
154
|
+
- Block out with primitives, then Shape, then Join, then Polish, then pattern and place (the ribbon order in guide { topic: "start" }).
|
|
151
155
|
- Polish order: draft (insert_add_draft, if any), then shell (insert_shell), then concave fillets and chamfers, then convex fillets and chamfers. Concave before convex holds for fillets and for chamfers alike. Blending every convex edge before the shell, or before the concave edges, is how a one-piece part turns into several bodies.
|
|
152
156
|
- Draft goes before the shell, so the inside walls inherit it.
|
|
153
157
|
- Shell opening. insert_shell opens every face that faces openScope (default "z", the +Z faces). When a post, boss or flange stands on a face that faces that way, the shell removes that face and cuts the feature loose (2 bodies). Open the other side (openScope: "-z") or use "none" for a closed hollow. status.bodyCount must be 1 straight after the shell, before any blend.
|
|
154
|
-
- Pick blend edges by name once the part has a shell or a concave blend. list_feature_edges names each edge by its two faces; "cylinder1.top~cylinder2.side" is the concave edge where a post meets its base. select_edges { names: [...] } then insert_fillet_edges or insert_chamfer_edges { use_selection: true }. A face pick (select_faces { names }, then use_selection: true) blends that one face's convex edges.
|
|
158
|
+
- Pick blend edges by name once the part has a shell or a concave blend. list_feature_edges names each edge by its two faces; "cylinder1.top~cylinder2.side" is the concave edge where a post meets its base. select_edges { names: [...] } then insert_fillet_edges or insert_chamfer_edges { use_selection: true }, or in one call insert_fillet_edges { edges: [...] }. tangent: true (on the insert or on select_edges) adds every edge that continues a named one tangentially, so one name takes a whole chain; tangent.added in the result lists what it added. A face pick (select_faces { names }, then use_selection: true) blends that one face's convex edges.
|
|
155
159
|
- The no-selection default (every convex edge) is for a plain block with no shell and no concave blend. After a shell it also takes both rims of every wall. After a concave blend it can fail and leave the part as it was (always when the blend runs onto a sphere or another doubly curved face): the fillet answers feature_failed "filletEdges: edge is concave", the chamfer "chamferEdges: edge N split the solid into 2 bodies". Pick by name there.
|
|
156
160
|
- A chamfer leg or fillet radius on a shelled part stays below the wall thickness, one named rim at a time. A rim-face pick takes the inner and the outer rim together, and a leg at or above the wall removes the rim face and leaves a ridge.
|
|
157
161
|
- Keep edges that must stay sharp (a parting line, a rib base on a molded part) out of the selection.
|
|
@@ -166,7 +170,7 @@ Playtest cases. Each failing sequence was reproduced in the app on 2026-11-06; r
|
|
|
166
170
|
Reuse instead of rebuilding.
|
|
167
171
|
- Repeated parts: one part, many instances. insert_part { part_id, instance: true } or a pattern, never a second copy rebuilt by hand. Hardware is one part per unique fastener type, patterned to every place it goes.
|
|
168
172
|
- Symmetric geometry: model one half or one side and insert_mirror it.
|
|
169
|
-
- Repeated features:
|
|
173
|
+
- Repeated features: group holes by function into one Hole card per group that shares size and end treatment (hole_open → hole_set_params → hole_begin_centres → plane_set / sketch_accept_plane → hole_centres_grid for an editable rectangular grid, hole_centres_polar for an editable bolt circle, or pick_points { kind: "point", keys: [{ at: [u, v] }, ...] } for irregular/single centres → hole_commit). Use insert_array3_d / insert_polar_array for body arrays and insert_pattern_points to put one copy on every hole center. Never place the same hole N times.
|
|
170
174
|
- Prefer boolean operations with primitives (insert_cube, insert_rounded_box, insert_cylinder, insert_tube, insert_sphere with combine add or subtract, or insert_boolean) over hand sketches. Sketch (sketch_begin, then insert_make_extrude or insert_make_revolve) only for a profile no primitive or primitive boolean gives.
|
|
171
175
|
- Features first; insert_code_snippet only for a real feature gap, with its // FEATURE-GAP line.
|
|
172
176
|
|
|
@@ -190,14 +194,14 @@ const CHAT = `In-viewer chat: the required workflow. Everything here is a requir
|
|
|
190
194
|
${WAKE_GUIDE_SECTION}
|
|
191
195
|
|
|
192
196
|
A2. After every pair or login, before you wait for a prompt (required)
|
|
193
|
-
0. Read the pair result's note. It says whether idle wake is ready
|
|
197
|
+
0. Read the pair result's note. It says whether idle wake is ready and what, if anything, to tell the user. SurfCAD greets the user itself when the pairing lands; do not send a greeting. Do what the note says first.
|
|
194
198
|
1. ${WEBHOOK_REQUIRED_GUIDANCE} status.webhookRegistered is then true until this process exits.
|
|
195
199
|
2. The URL and bearer are held in this process's memory only: never logged, never written to disk, never returned, never sent to the tab. Unpair, a new pair, and a new process all start with no webhook, so register again every time.
|
|
196
200
|
3. Never ask the user for a webhook URL or key. If the user offers one, register it: the key is the bearer argument.
|
|
197
201
|
4. Your host cannot receive callbacks: the long-poll in section C is the required fallback. Never run with neither a webhook nor the poll.
|
|
198
202
|
|
|
199
203
|
B. Every prompt, in this order (required)
|
|
200
|
-
1. The user's message appears in the chat box. It reaches you as a webhook POST or as a read_messages item with its id.
|
|
204
|
+
1. The user's message appears in the chat box. It reaches you as a webhook POST or as a read_messages item with its id. A message can carry up to four images: they follow it as consecutive image blocks, and the message says image_count when there is more than one.
|
|
201
205
|
2. Ack. Your first tool call after you receive the prompt is set_status { state: "responding", id: <prompt id> }. The chat shows the jumping dots. No modeling, no list_*, no screenshot, no other tool before this. set_status responding is the ack; there is no separate ack tool.
|
|
202
206
|
3. Acknowledge in words, once: reply_to_user { in_reply_to: <id>, text: "Got it. Starting on <one-line plan>.", final: false }. Keep it short. Send it when work will follow.
|
|
203
207
|
4. The tab keeps that reply on screen for about 10 seconds. That is the tab's timer. Do not sleep and do not wait for it.
|
|
@@ -215,8 +219,17 @@ C. While connected: the ${READ_MESSAGES_POLL_MS / 1000} second long-poll (requir
|
|
|
215
219
|
5. An empty immediate read_messages {} does not mean the user never sent. status.queued can be above 0 while a fresh per-call process has not been offered the prompt yet. Use wait_ms.
|
|
216
220
|
6. Polling is not activity. A poll keeps the session connected, and nothing more: it does not restart the "No activity from the agent for ${agentPromptStallMinutes()} min" stall window and it does not show the working state. Activity is set_status, a model-changing tool, post_progress, and reply_to_user. Do not poll to look busy; post_progress while you really work.
|
|
217
221
|
|
|
222
|
+
C2. Between turns: surfcad-mcp wait (hosts with background commands)
|
|
223
|
+
Answering a prompt makes your session the chat's owner when the host exports a session id (Claude Code: CLAUDE_CODE_SESSION_ID; see status.chat.owner). End every turn by starting npx -y surfcad-mcp@latest wait in the background (Claude Code: run_in_background). It exits when the next message arrives, however late, and your host resumes this session: call read_messages {} first (wait does not read it). Exit 0 a message, 2 timed out (start again), 3 the chat moved (stop). While it runs, no other session is woken.
|
|
224
|
+
|
|
218
225
|
D. One window
|
|
219
|
-
The dots, the fold, the spinner, and your replies show only in the SurfCAD window that paired you (or, after the user sends a prompt from another window of the same account, that window). Your tool calls run in that window. Other windows of the account stay quiet
|
|
226
|
+
The dots, the fold, the spinner, and your replies show only in the SurfCAD window that paired you (or, after the user sends a prompt from another window of the same account, that window). Your tool calls run in that window. Other windows of the account stay quiet.
|
|
227
|
+
|
|
228
|
+
E. A wake run (a fresh session, because you were idle)
|
|
229
|
+
Follow the wake payload's instruction. You have no memory of the session that paired.
|
|
230
|
+
${WAKE_NO_REPAIR}
|
|
231
|
+
Fetch the message with read_messages { wait_ms: 10000 } (up to four images follow it as image blocks; the message says image_count when there is more than one), then follow section B. That id is valid in reply_to_user even though this process did not see the prompt before. An id that is not in this paired chat, or that belongs to someone else, is unknown_prompt.
|
|
232
|
+
Do not send a greeting. A test wake (reason "test") calls status once and ends.`;
|
|
220
233
|
|
|
221
234
|
/**
|
|
222
235
|
* Design guidelines for high pressure injection molding. The numbers that
|
|
@@ -372,7 +385,7 @@ export const SERVER_INSTRUCTIONS = [
|
|
|
372
385
|
'',
|
|
373
386
|
// The wake pointer is here because every host shows these lines first. The cap is 2048 bytes.
|
|
374
387
|
`After pair, do what its idle-wake note says. Then guide { topic: "start" } before the first model call; guide {} topics: ${GUIDE_TOPIC_NAMES.join(', ')}.`,
|
|
375
|
-
'Flow: first part = create_assembly\'s partId (create_part: later parts only); insert_cube / insert_cylinder / insert_tube,
|
|
388
|
+
'Flow: first part = create_assembly\'s partId (create_part: later parts only); insert_cube / insert_cylinder / insert_tube, hole_open, insert_cut, insert_shell, then blends, concave before convex. Place: fix one base part with a fixed joint, then joint_create. part_set_transform only for parts that touch nothing.',
|
|
376
389
|
'Rules: use_selection is single use (nothing selected is no_selection). git_save { message } answers consent_pending until Allow. Tools default to return: "status". list_faces { filter, page }. list_commands { group }.',
|
|
377
390
|
].join('\n');
|
|
378
391
|
|
|
@@ -19,6 +19,11 @@ export { AGENT_PROMPT_STALL_MS };
|
|
|
19
19
|
export const PROMPT_TEXT_MAX = 8000;
|
|
20
20
|
export const PROMPT_REPLY_MAX = 32_000;
|
|
21
21
|
export const PROMPT_SCREENSHOT_MAX_BYTES = 2 * 1024 * 1024;
|
|
22
|
+
/**
|
|
23
|
+
* Images one prompt may carry: `screenshot` (the first) plus `extra_images`.
|
|
24
|
+
* An older tab sends `screenshot` alone.
|
|
25
|
+
*/
|
|
26
|
+
export const PROMPT_IMAGES_MAX = 4;
|
|
22
27
|
export const PROMPT_QUEUE_CAP = 50;
|
|
23
28
|
export const PROMPT_RATE_MS = 1000;
|
|
24
29
|
export const BEARER_MAX = 4096;
|
|
@@ -147,6 +152,9 @@ export function createPromptSession(options) {
|
|
|
147
152
|
}
|
|
148
153
|
const send = options.send;
|
|
149
154
|
const onTaken = typeof options.onTaken === 'function' ? options.onTaken : null;
|
|
155
|
+
// When set, an id this process never saw is still sent. The relay accepts
|
|
156
|
+
// it when the id belongs to this paired chat and rejects it otherwise.
|
|
157
|
+
const confirmReplies = options.confirmReplies === true;
|
|
150
158
|
const onUnread = typeof options.onUnread === 'function' ? options.onUnread : null;
|
|
151
159
|
const unreadGraceMs = options.unreadGraceMs ?? PROMPT_UNREAD_GRACE_MS;
|
|
152
160
|
/** @param {string[]} ids */
|
|
@@ -203,6 +211,8 @@ export function createPromptSession(options) {
|
|
|
203
211
|
let lastSessionAt = -Infinity;
|
|
204
212
|
/** @type {string | null} */
|
|
205
213
|
let lastId = null;
|
|
214
|
+
/** Shown in the chat cap ("Claude Code"); set from the MCP client's name. */
|
|
215
|
+
let agentDisplayName = '';
|
|
206
216
|
/** @type {unknown} */
|
|
207
217
|
let idleTimer = null;
|
|
208
218
|
let chain = Promise.resolve();
|
|
@@ -237,6 +247,10 @@ export function createPromptSession(options) {
|
|
|
237
247
|
*/
|
|
238
248
|
function emit(payload, { required = false } = {}) {
|
|
239
249
|
let result;
|
|
250
|
+
// The agent's display name for the chat cap, on status and reply frames.
|
|
251
|
+
if (agentDisplayName && payload && (payload.type === PAIR_MSG.AGENT_STATUS || payload.type === PAIR_MSG.AGENT_REPLY)) {
|
|
252
|
+
payload = { ...payload, agent: agentDisplayName };
|
|
253
|
+
}
|
|
240
254
|
try {
|
|
241
255
|
result = send(payload);
|
|
242
256
|
} catch (err) {
|
|
@@ -575,6 +589,28 @@ export function createPromptSession(options) {
|
|
|
575
589
|
}
|
|
576
590
|
screenshot = shot.value;
|
|
577
591
|
}
|
|
592
|
+
// More images of the same message, after `screenshot`. Each is checked
|
|
593
|
+
// like the first; a bad one fails the prompt, it is not dropped quietly.
|
|
594
|
+
/** @type {Array<{ mime: 'image/png', data: string, width: number, height: number }>} */
|
|
595
|
+
const extraImages = [];
|
|
596
|
+
if (message.extra_images != null) {
|
|
597
|
+
if (!Array.isArray(message.extra_images) || !screenshot) {
|
|
598
|
+
failAck('bad_screenshot');
|
|
599
|
+
return;
|
|
600
|
+
}
|
|
601
|
+
if (message.extra_images.length > PROMPT_IMAGES_MAX - 1) {
|
|
602
|
+
failAck('too_many_images');
|
|
603
|
+
return;
|
|
604
|
+
}
|
|
605
|
+
for (const item of message.extra_images) {
|
|
606
|
+
const shot = normalizeScreenshot(item);
|
|
607
|
+
if (shot.error) {
|
|
608
|
+
failAck(shot.error);
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
extraImages.push(shot.value);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
578
614
|
// The server relay offers a held prompt to every new socket or pull
|
|
579
615
|
// session until one reports it taken, so the same id can arrive again
|
|
580
616
|
// (a reconnect in this process). Keep the copy this process has.
|
|
@@ -598,6 +634,7 @@ export function createPromptSession(options) {
|
|
|
598
634
|
ts,
|
|
599
635
|
...(context.value ? { context: context.value } : {}),
|
|
600
636
|
...(screenshot ? { screenshot } : {}),
|
|
637
|
+
...(extraImages.length ? { extra_images: extraImages } : {}),
|
|
601
638
|
};
|
|
602
639
|
armWork(id);
|
|
603
640
|
await deliver(prompt, epoch);
|
|
@@ -659,11 +696,14 @@ export function createPromptSession(options) {
|
|
|
659
696
|
const taken = queue.splice(0, count);
|
|
660
697
|
const messages = [];
|
|
661
698
|
const images = [];
|
|
699
|
+
/** Per message, the images after the first (same order as `images`). */
|
|
700
|
+
const extraImages = [];
|
|
662
701
|
const takenIds = [];
|
|
663
702
|
for (const item of taken) {
|
|
664
703
|
if (item.kind === 'cancel') {
|
|
665
704
|
messages.push({ type: 'cancel', id: item.id });
|
|
666
705
|
images.push(null);
|
|
706
|
+
extraImages.push([]);
|
|
667
707
|
continue;
|
|
668
708
|
}
|
|
669
709
|
if (states.get(item.id) === 'queued') states.set(item.id, 'delivered');
|
|
@@ -681,18 +721,27 @@ export function createPromptSession(options) {
|
|
|
681
721
|
height: item.screenshot.height,
|
|
682
722
|
},
|
|
683
723
|
} : {}),
|
|
724
|
+
...(item.extra_images?.length ? {
|
|
725
|
+
image_count: 1 + item.extra_images.length,
|
|
726
|
+
extra_images: item.extra_images.map((shot) => ({
|
|
727
|
+
mime: shot.mime,
|
|
728
|
+
width: shot.width,
|
|
729
|
+
height: shot.height,
|
|
730
|
+
})),
|
|
731
|
+
} : {}),
|
|
684
732
|
notice: USER_CONTENT_NOTICE,
|
|
685
733
|
acked: true,
|
|
686
734
|
});
|
|
687
735
|
images.push(item.screenshot
|
|
688
736
|
? { data: item.screenshot.data, mimeType: 'image/png' }
|
|
689
737
|
: null);
|
|
738
|
+
extraImages.push((item.extra_images || []).map((shot) => ({ data: shot.data, mimeType: 'image/png' })));
|
|
690
739
|
}
|
|
691
740
|
// A poll is not activity. read_messages (with or without wait_ms) must
|
|
692
741
|
// not restart the stall window or tell the tab the agent is active: an
|
|
693
742
|
// agent that only long-polls would otherwise never stall.
|
|
694
743
|
noteTaken(takenIds);
|
|
695
|
-
return { messages, images };
|
|
744
|
+
return { messages, images, extraImages };
|
|
696
745
|
}
|
|
697
746
|
|
|
698
747
|
/**
|
|
@@ -756,18 +805,22 @@ export function createPromptSession(options) {
|
|
|
756
805
|
if (typeof inReplyTo !== 'string' || !inReplyTo || inReplyTo.length > 80) {
|
|
757
806
|
throw Object.assign(new Error('in_reply_to is required'), { code: 'bad_args' });
|
|
758
807
|
}
|
|
759
|
-
//
|
|
760
|
-
//
|
|
761
|
-
//
|
|
762
|
-
//
|
|
763
|
-
//
|
|
808
|
+
// This process's own prompts are known here. An id another session read
|
|
809
|
+
// (a wake run, `surfcad-mcp call`) is not. With `confirmReplies` the
|
|
810
|
+
// relay decides: it knows every prompt this paired chat sent, and it
|
|
811
|
+
// refuses an id that does not exist or belongs to someone else. Without
|
|
812
|
+
// that (unit tests, a relay that cannot answer) a prompt-shaped id is
|
|
813
|
+
// still sent and anything else is refused before any send.
|
|
764
814
|
let state = states.get(inReplyTo);
|
|
815
|
+
const unseen = !state;
|
|
765
816
|
if (!state) {
|
|
766
|
-
if (!UUID_RE.test(inReplyTo)) {
|
|
767
|
-
throw Object.assign(new Error('in_reply_to is not a prompt
|
|
817
|
+
if (!confirmReplies && !UUID_RE.test(inReplyTo)) {
|
|
818
|
+
throw Object.assign(new Error('in_reply_to is not a prompt in this paired chat'), { code: 'unknown_prompt' });
|
|
819
|
+
}
|
|
820
|
+
if (!confirmReplies) {
|
|
821
|
+
remember(inReplyTo, 'delivered');
|
|
822
|
+
state = 'delivered';
|
|
768
823
|
}
|
|
769
|
-
remember(inReplyTo, 'delivered');
|
|
770
|
-
state = 'delivered';
|
|
771
824
|
}
|
|
772
825
|
if (state === 'cancelled') {
|
|
773
826
|
return { ok: false, error: 'cancelled' };
|
|
@@ -782,6 +835,7 @@ export function createPromptSession(options) {
|
|
|
782
835
|
final: isFinal,
|
|
783
836
|
}, { required: true });
|
|
784
837
|
const finish = () => {
|
|
838
|
+
if (unseen && confirmReplies) remember(inReplyTo, 'delivered');
|
|
785
839
|
if (isFinal) {
|
|
786
840
|
queue = queue.filter((item) => item.kind === 'cancel' || item.id !== inReplyTo);
|
|
787
841
|
states.set(inReplyTo, 'replied');
|
|
@@ -982,6 +1036,15 @@ export function createPromptSession(options) {
|
|
|
982
1036
|
queuedCount() {
|
|
983
1037
|
return promptQueueLength();
|
|
984
1038
|
},
|
|
1039
|
+
/** @param {string} name the agent's display name for the chat cap */
|
|
1040
|
+
setAgentName(name) {
|
|
1041
|
+
const clean = typeof name === 'string' ? name.trim().slice(0, 40) : '';
|
|
1042
|
+
agentDisplayName = /^[\w .()+-]*$/.test(clean) ? clean : '';
|
|
1043
|
+
},
|
|
1044
|
+
/** Ids still waiting for read_messages, oldest first (cancels left out). */
|
|
1045
|
+
queuedIds() {
|
|
1046
|
+
return queue.filter((item) => item.kind !== 'cancel').map((item) => item.id);
|
|
1047
|
+
},
|
|
985
1048
|
/** Stall window. Local and remote sessions leave this at AGENT_PROMPT_STALL_MS. */
|
|
986
1049
|
idleMs,
|
|
987
1050
|
};
|
|
@@ -999,5 +1062,6 @@ function webhookBody(prompt) {
|
|
|
999
1062
|
ts: prompt.ts,
|
|
1000
1063
|
...(prompt.context ? { context: prompt.context } : {}),
|
|
1001
1064
|
...(prompt.screenshot ? { screenshot: prompt.screenshot } : {}),
|
|
1065
|
+
...(prompt.extra_images?.length ? { extra_images: prompt.extra_images } : {}),
|
|
1002
1066
|
};
|
|
1003
1067
|
}
|