surfcad-mcp 0.3.0 → 0.3.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 +12 -9
- package/data/commands.json +181 -111
- package/data/helpers.json +6 -6
- package/package.json +1 -1
- package/src/bridge/relayHub.mjs +2 -1
- package/src/prompt/buildGuidance.mjs +11 -5
- package/src/prompt/errorHints.mjs +7 -0
- package/src/prompt/guide.mjs +20 -16
- package/src/prompt/promptSession.mjs +55 -6
- package/src/prompt/promptStall.mjs +6 -0
- package/src/prompt/promptTools.mjs +19 -8
- package/src/relay.mjs +13 -0
- package/src/relayMessages.mjs +2 -0
- package/src/server.mjs +9 -1
package/data/helpers.json
CHANGED
|
@@ -239,8 +239,8 @@
|
|
|
239
239
|
"default": "'z'"
|
|
240
240
|
}
|
|
241
241
|
],
|
|
242
|
-
"description": "
|
|
243
|
-
"doc": "
|
|
242
|
+
"description": "Copies of a solid equally spaced around an axis, offset perpendicular to that axis (+Y for x, +X for y and z), without keeping the input as an extra body.",
|
|
243
|
+
"doc": "Copies a solid equally spaced around an axis. The radius offset is perpendicular to that axis (+Y when the axis is x, +X for y and z) so the copies orbit; radius 0 leaves every copy on the axis. The result is only those copies. The input solid is not kept as an extra body.\n\n`insert_polar_array` writes this call. `boreRadius` 0 (the default) copies the body. `boreRadius` greater than 0 subtracts that many centered holes of `boreRadius` by `boreHeight` on the circle and does not copy the body; `boltCircleRadius` must then be greater than 0. `boltCircleRadius` defaults to 0 (on the axis). That is the bolt-circle hole pattern. Do not record it as a FEATURE-GAP.\n\n\n\n**Parameters:**\n- `manifold` - The manifold to array\n- `count` - Number of copies\n- `radius` - Orbit radius. 0 leaves the copies on the axis. The offset is perpendicular to `axis`\n- `axis` - Rotation axis: 'x', 'y', or 'z' (default: 'z')\n\n---",
|
|
244
244
|
"examples": [
|
|
245
245
|
"// Create 6 cylinders in a circle\nconst cylinder = Manifold.cylinder(20, 5, 5, 32);\nconst circle = polarArray(cylinder, 6, 30, 'z');\nreturn circle;"
|
|
246
246
|
]
|
|
@@ -264,7 +264,7 @@
|
|
|
264
264
|
}
|
|
265
265
|
],
|
|
266
266
|
"description": "Pattern on points: one copy of `manifold` at every point, turned so its `up` axis follows the point's `axis` when the point has one. ",
|
|
267
|
-
"doc": "One copy of the body at every point, turned so its `up` axis follows the point's `axis` when the point has one. The hardware helper: a bolt onto the hole centers and axes of the part it fastens.\n\n\n\n**Parameters:**\n- `manifold` - The body to copy (one instance)\n- `points` - Array of `[x, y, z]` or `{ at: [x, y, z], axis?: [nx, ny, nz] }` in mm; a point with no axis is a plain translate\n- `opts.up` - The body axis that follows each point's axis (default `[0, 0, 1]`)\n- `opts.keepOriginal` - Also keep the source where it is (default `false`)\n- `opts.merge` - Union the copies (default `true`); `false` composes them as separate bodies\n\nThrows a plain error on an empty list, a point that is not three numbers, or a zero axis. The palette item is **Points** (`patternPoints`,
|
|
267
|
+
"doc": "One copy of the body at every point, turned so its `up` axis follows the point's `axis` when the point has one. The hardware helper: a bolt onto the hole centers and axes of the part it fastens.\n\n\n\n**Parameters:**\n- `manifold` - The body to copy (one instance)\n- `points` - Array of `[x, y, z]` or `{ at: [x, y, z], axis?: [nx, ny, nz] }` in mm; a point with no axis is a plain translate\n- `opts.up` - The body axis that follows each point's axis (default `[0, 0, 1]`)\n- `opts.keepOriginal` - Also keep the source where it is (default `false`)\n- `opts.merge` - Union the copies (default `true`); `false` composes them as separate bodies\n\nThrows a plain error on an empty list, a point that is not three numbers, or a zero axis. The palette item is **Points** (`patternPoints`, Array Type=Points); the agent tool is `insert_pattern_points { points, up?, keepOriginal?, merge? }`.\n\n---",
|
|
268
268
|
"examples": [
|
|
269
269
|
"// Four bolts, one per hole; each hole gives its center and axis\nconst bolt = Manifold.cylinder(12, 2.5, 2.5, 24);\nlet part = patternOnPoints(bolt, [\n { at: [-20, -15, 6], axis: [0, 0, 1] },\n { at: [20, -15, 6], axis: [0, 0, 1] },\n { at: [-20, 15, 6], axis: [0, 0, 1] },\n { at: [20, 15, 6], axis: [0, 0, 1] },\n], { up: [0, 0, 1] });\nreturn part;"
|
|
270
270
|
]
|
|
@@ -1098,7 +1098,7 @@
|
|
|
1098
1098
|
}
|
|
1099
1099
|
],
|
|
1100
1100
|
"description": "chamferEdges(part, edges, c) — equal-leg 45° chamfer c on a SET of straight convex edges. ",
|
|
1101
|
-
"doc": "chamferEdges(part, edges, c) — equal-leg 45° chamfer c on a SET of straight\nconvex edges. Edges = objects from c4MeshData/convexEdges, or a plain\n[{va, vb, n0, n1}] array. n0/n1 (outward normals of the two adjacent faces\nat that edge) are REQUIRED for hand-built edges, but are AUTO-DERIVED from\nthe current mesh when the edge object carries {faces: [i0, i1]} (as all\nc4MeshData-based selectors do: convexEdges, edgesByOrientation,\nedgesByNormal, planarFaceAt-derived selections) — no more\n\"Cannot read properties of undefined (reading '0')\" when mixing selectors\nwith chamferEdges.\n\nConstruction (verified, C2 pilot + C4): per edge, cutter = hull of the two\nedge endpoints plus four corner points pulled c into each adjacent face\ninterior. c IS THE LEG LENGTH along each adjacent face (CAD \"C2\" = 2 mm\non both legs), NOT the perpendicular face offset — the perpendicular\noffset is derived from the face-to-face angle (offset = c·tan(θ/2), θ =\nangle between n0/n1; at a 90° corner they coincide, at a 120° hex-nut\ncorner C2 → 1.155 mm offset / 2 mm legs). CUTTERS ARE APPLIED SEQUENTIALLY (one difference per edge) and\neach intermediate result is checked: a single degenerate cutter (e.g. at\na triple-junction rib-base edge where the two \"adjacent faces\" are coplanar\nor the cutter self-intersects) must not be allowed to wedge the batch\nunion into a wasm out-of-bounds trap (observed: chamfering ALL convex\nedges of a ribbed plate — one subset crashes the kernel while the rest\nbuild fine). The first bad edge throws a named, actionable error instead.\nCost: n differences instead of 1 — fine for the edge counts these parts\nactually use (≤ ~30); the C8 timeout guard catches anything pathological.",
|
|
1101
|
+
"doc": "chamferEdges(part, edges, c) — equal-leg 45° chamfer c on a SET of straight\nconvex edges. Edges = objects from c4MeshData/convexEdges, or a plain\n[{va, vb, n0, n1}] array. n0/n1 (outward normals of the two adjacent faces\nat that edge) are REQUIRED for hand-built edges, but are AUTO-DERIVED from\nthe current mesh when the edge object carries {faces: [i0, i1]} (as all\nc4MeshData-based selectors do: convexEdges, edgesByOrientation,\nedgesByNormal, planarFaceAt-derived selections) — no more\n\"Cannot read properties of undefined (reading '0')\" when mixing selectors\nwith chamferEdges.\n\nConstruction (verified, C2 pilot + C4): per edge, cutter = hull of the two\nedge endpoints plus four corner points pulled c into each adjacent face\ninterior. c IS THE LEG LENGTH along each adjacent face (CAD \"C2\" = 2 mm\non both legs), NOT the perpendicular face offset — the perpendicular\noffset is derived from the face-to-face angle (offset = c·tan(θ/2), θ =\nangle between n0/n1; at a 90° corner they coincide, at a 120° hex-nut\ncorner C2 → 1.155 mm offset / 2 mm legs). CUTTERS ARE APPLIED SEQUENTIALLY (one difference per edge) and\neach intermediate result is checked: a single degenerate cutter (e.g. at\na triple-junction rib-base edge where the two \"adjacent faces\" are coplanar\nor the cutter self-intersects) must not be allowed to wedge the batch\nunion into a wasm out-of-bounds trap (observed: chamfering ALL convex\nedges of a ribbed plate — one subset crashes the kernel while the rest\nbuild fine). The first bad edge throws a named, actionable error instead.\nCost: n differences instead of 1 — fine for the edge counts these parts\nactually use (≤ ~30); the C8 timeout guard catches anything pathological.\nA chamfer that splits the solid into more bodies than it started with\nthrows. The pieces are not returned.",
|
|
1102
1102
|
"examples": [
|
|
1103
1103
|
"part = chamferEdges(part, convexEdges(part), 2);"
|
|
1104
1104
|
]
|
|
@@ -1448,7 +1448,7 @@
|
|
|
1448
1448
|
}
|
|
1449
1449
|
],
|
|
1450
1450
|
"description": "makeLoft(sections, opts?) — loft two or more profiles on parallel or angled planes. ",
|
|
1451
|
-
"doc": "Loft ≥2 `makeCrossSection` values into a solid. **Parallel planes** (same\nworkplane + per-profile offset along the normal, normals within about 8°)\nuse the polar warp. `offsetPlaneFrame(plane, offset)` copies a PlaneFrame\nand translates `center` by `offset * normal`. That solid is **local** (XY =\nstation UV, Z along the shared normal, z=0 at the lowest station) — Confirm\nplaces it with `placeInFrame`. **Angled planes** keep input order. Each\ncontour is mapped through its own frame, arc-length resampled, and\nshift-aligned, then carried on a Hermite spine so a right-angle elbow does\nnot fold. That solid is local to the **first** profile's plane\n(`placeInFrame` on that plane). The legacy `loft({ topCS, bottomCS, height })`\ncup helper is unchanged.\n\n\n\n**Contour-mode Loft:** game-mode **Loft** builds a multi-profile list (min 2,\ndefault circle r=5 @ 0 and circle r=8 @ 20 on the shared workplane). Circle /\nrect / polygon / polyline edit the selected profile. Each station can stay on\nthat plane with an offset, or pick a face, a saved workplane, or a saved\nsketch's plane. Confirm emits one `makeCrossSection` per station plus\n`makeLoft`, then `placeInFrame`. Offset-only stations still use\n`offsetPlaneFrame`. A station with its own frame emits that frame, and the\nplacement frame is the first station. Second Confirm replaces the same marked\nblock. **Back** exits with no commit. Live preview skins the stations as\noffsets, planes, or shapes change.\n\n**Loud failures:** < 2 profiles; coincident stations (zero-length loft);\ndegenerate / empty contours; a turn tighter than the profiles\n(self-intersection); empty result volume. Never a silent wrong solid.\n\n`opts.align` (default true) matches cornered stations by their outermost\nvertex angle (a 45° copy of the same rectangle un-rotates back to a prism).\nA nearly circular station does **not** spin the other profile — that was\nthe off-angle circle↔rectangle default. `opts.resolution
|
|
1451
|
+
"doc": "Loft ≥2 `makeCrossSection` values into a solid. **Parallel planes** (same\nworkplane + per-profile offset along the normal, normals within about 8°)\nuse the polar warp. `offsetPlaneFrame(plane, offset)` copies a PlaneFrame\nand translates `center` by `offset * normal`. That solid is **local** (XY =\nstation UV, Z along the shared normal, z=0 at the lowest station) — Confirm\nplaces it with `placeInFrame`. **Angled planes** keep input order. Each\ncontour is mapped through its own frame, arc-length resampled, and\nshift-aligned, then carried on a Hermite spine so a right-angle elbow does\nnot fold. That solid is local to the **first** profile's plane\n(`placeInFrame` on that plane). The legacy `loft({ topCS, bottomCS, height })`\ncup helper is unchanged.\n\n\n\n**Contour-mode Loft:** game-mode **Loft** builds a multi-profile list (min 2,\ndefault circle r=5 @ 0 and circle r=8 @ 20 on the shared workplane). Circle /\nrect / polygon / polyline edit the selected profile. Each station can stay on\nthat plane with an offset, or pick a face, a saved workplane, or a saved\nsketch's plane. Confirm emits one `makeCrossSection` per station plus\n`makeLoft`, then `placeInFrame`. Offset-only stations still use\n`offsetPlaneFrame`. A station with its own frame emits that frame, and the\nplacement frame is the first station. Second Confirm replaces the same marked\nblock. **Back** exits with no commit. Live preview skins the stations as\noffsets, planes, or shapes change.\n\n**Loud failures:** < 2 profiles; coincident stations (zero-length loft);\ndegenerate / empty contours; a turn tighter than the profiles\n(self-intersection); empty result volume. Never a silent wrong solid.\n\n`opts.align` (default true) matches cornered stations by their outermost\nvertex angle (a 45° copy of the same rectangle un-rotates back to a prism).\nA nearly circular station does **not** spin the other profile — that was\nthe off-angle circle↔rectangle default. Parallel rings and the slices\nbetween stations follow a chordal tolerance, 0.0005 of the part's bounding\ndiagonal, clamped to 0.01–0.25 mm. A vertex drops only when it sits within\nthat tolerance of a chord and the corner turns less than 25°. A span that\nis straight is one slice; a twisted span is split until the quad's twist\nstays inside the same tolerance. `opts.resolution`, when set, is the\nmaximum polar gap `2π / N` (clamped to 8–256) and only adds samples.\nOmitting it does not fall back to a uniform 128-ray table. Rectangle\ncorners stay in the table, so a circle's chords do not bite them. Legacy\n`loft({ topCS, bottomCS, height })` is unchanged.\n\n**Default contour plane** (no face and no saved workplane) is world **+Z**\nwith **X/Y** axes — the standard views. A picked face or construction\nworkplane still supplies the frame. Angle sliders in the contour chip rotate\nthat frame; Confirm uses the edited plane.\n\n**Workplane** (Advanced) inserts a literal PlaneFrame\n`{ center, normal, x, y }` — a rendered, selectable construction plane.\nIt does **not** create a host cube. Tapping it on an empty script leaves\nthe viewport empty of solids (the plane overlay remains).\n\n**Blank run:** an empty, whitespace, or comment-only script (and a\nconstruction-plane-only script) clears the 3D view. Undo back to a blank\nbuffer does not keep the previous solid. A failed non-empty script still\nrestores the last good mesh.\n\n**Rules for both:**\n- `contours` is an **array of contours** `[outer, hole1, ...]`; a single\n solid can be written as `[...pts]` (bare point list) — both accepted.\n- Every contour needs **≥ 3 distinct points**, closed polygon (auto-closed\n if first ≠ last). Open polylines / 2-point lists throw.\n- For a **hollow** part: outer contour + inner contour (through-hole).\n- Invalid profile → **named throw** (never a silent empty).\n\n---\n\n## Example: Complex Part\n\n\n\n## Security Notes\n\nScripts run in an isolated Web Worker sandbox with:\n- No network access (fetch, XMLHttpRequest, WebSocket blocked)\n- No storage access (indexedDB, localStorage blocked)\n- No worker spawning\n- Memory limits enforced\n- Execution timeout enforced\n\nImported models are available via `window.__importedManifolds['filename']`.",
|
|
1452
1452
|
"examples": [
|
|
1453
1453
|
"const fr = { center: [0, 0, 0], normal: [0, 0, 1], x: [1, 0, 0], y: [0, 1, 0] };\nconst xs0 = makeCrossSection(fr, profileCircle(5, 32));\nconst xs1 = makeCrossSection(offsetPlaneFrame(fr, 20), profileCircle(8, 32));\npart = placeInFrame(fr, makeLoft([xs0, xs1]));",
|
|
1454
1454
|
"// Create a flanged tube with mounting holes\n\n// Main tube\nconst mainTube = tube(15, 12, 40, 64);\n\n// Bottom flange\nconst flange = Manifold.cylinder(5, 25, 25, 64);\n\n// Mounting holes in flange\nconst bore = Manifold.cylinder(10, 3, 3, 32);\nconst holes = polarArray(bore, 4, 20, 'z');\n\n// Combine\nlet part = mainTube.add(flange);\npart = part.subtract(holes);\n\n// Center and align bottom to Z=0\npart = center(part, [true, true, false]);\npart = align(part, { min: [undefined, undefined, 0] });\n\nreturn part;"
|
|
@@ -1468,7 +1468,7 @@
|
|
|
1468
1468
|
}
|
|
1469
1469
|
],
|
|
1470
1470
|
"description": "Copy of a workplane translated along its normal. ",
|
|
1471
|
-
"doc": "Loft ≥2 `makeCrossSection` values into a solid. **Parallel planes** (same\nworkplane + per-profile offset along the normal, normals within about 8°)\nuse the polar warp. `offsetPlaneFrame(plane, offset)` copies a PlaneFrame\nand translates `center` by `offset * normal`. That solid is **local** (XY =\nstation UV, Z along the shared normal, z=0 at the lowest station) — Confirm\nplaces it with `placeInFrame`. **Angled planes** keep input order. Each\ncontour is mapped through its own frame, arc-length resampled, and\nshift-aligned, then carried on a Hermite spine so a right-angle elbow does\nnot fold. That solid is local to the **first** profile's plane\n(`placeInFrame` on that plane). The legacy `loft({ topCS, bottomCS, height })`\ncup helper is unchanged.\n\n\n\n**Contour-mode Loft:** game-mode **Loft** builds a multi-profile list (min 2,\ndefault circle r=5 @ 0 and circle r=8 @ 20 on the shared workplane). Circle /\nrect / polygon / polyline edit the selected profile. Each station can stay on\nthat plane with an offset, or pick a face, a saved workplane, or a saved\nsketch's plane. Confirm emits one `makeCrossSection` per station plus\n`makeLoft`, then `placeInFrame`. Offset-only stations still use\n`offsetPlaneFrame`. A station with its own frame emits that frame, and the\nplacement frame is the first station. Second Confirm replaces the same marked\nblock. **Back** exits with no commit. Live preview skins the stations as\noffsets, planes, or shapes change.\n\n**Loud failures:** < 2 profiles; coincident stations (zero-length loft);\ndegenerate / empty contours; a turn tighter than the profiles\n(self-intersection); empty result volume. Never a silent wrong solid.\n\n`opts.align` (default true) matches cornered stations by their outermost\nvertex angle (a 45° copy of the same rectangle un-rotates back to a prism).\nA nearly circular station does **not** spin the other profile — that was\nthe off-angle circle↔rectangle default. `opts.resolution
|
|
1471
|
+
"doc": "Loft ≥2 `makeCrossSection` values into a solid. **Parallel planes** (same\nworkplane + per-profile offset along the normal, normals within about 8°)\nuse the polar warp. `offsetPlaneFrame(plane, offset)` copies a PlaneFrame\nand translates `center` by `offset * normal`. That solid is **local** (XY =\nstation UV, Z along the shared normal, z=0 at the lowest station) — Confirm\nplaces it with `placeInFrame`. **Angled planes** keep input order. Each\ncontour is mapped through its own frame, arc-length resampled, and\nshift-aligned, then carried on a Hermite spine so a right-angle elbow does\nnot fold. That solid is local to the **first** profile's plane\n(`placeInFrame` on that plane). The legacy `loft({ topCS, bottomCS, height })`\ncup helper is unchanged.\n\n\n\n**Contour-mode Loft:** game-mode **Loft** builds a multi-profile list (min 2,\ndefault circle r=5 @ 0 and circle r=8 @ 20 on the shared workplane). Circle /\nrect / polygon / polyline edit the selected profile. Each station can stay on\nthat plane with an offset, or pick a face, a saved workplane, or a saved\nsketch's plane. Confirm emits one `makeCrossSection` per station plus\n`makeLoft`, then `placeInFrame`. Offset-only stations still use\n`offsetPlaneFrame`. A station with its own frame emits that frame, and the\nplacement frame is the first station. Second Confirm replaces the same marked\nblock. **Back** exits with no commit. Live preview skins the stations as\noffsets, planes, or shapes change.\n\n**Loud failures:** < 2 profiles; coincident stations (zero-length loft);\ndegenerate / empty contours; a turn tighter than the profiles\n(self-intersection); empty result volume. Never a silent wrong solid.\n\n`opts.align` (default true) matches cornered stations by their outermost\nvertex angle (a 45° copy of the same rectangle un-rotates back to a prism).\nA nearly circular station does **not** spin the other profile — that was\nthe off-angle circle↔rectangle default. Parallel rings and the slices\nbetween stations follow a chordal tolerance, 0.0005 of the part's bounding\ndiagonal, clamped to 0.01–0.25 mm. A vertex drops only when it sits within\nthat tolerance of a chord and the corner turns less than 25°. A span that\nis straight is one slice; a twisted span is split until the quad's twist\nstays inside the same tolerance. `opts.resolution`, when set, is the\nmaximum polar gap `2π / N` (clamped to 8–256) and only adds samples.\nOmitting it does not fall back to a uniform 128-ray table. Rectangle\ncorners stay in the table, so a circle's chords do not bite them. Legacy\n`loft({ topCS, bottomCS, height })` is unchanged.\n\n**Default contour plane** (no face and no saved workplane) is world **+Z**\nwith **X/Y** axes — the standard views. A picked face or construction\nworkplane still supplies the frame. Angle sliders in the contour chip rotate\nthat frame; Confirm uses the edited plane.\n\n**Workplane** (Advanced) inserts a literal PlaneFrame\n`{ center, normal, x, y }` — a rendered, selectable construction plane.\nIt does **not** create a host cube. Tapping it on an empty script leaves\nthe viewport empty of solids (the plane overlay remains).\n\n**Blank run:** an empty, whitespace, or comment-only script (and a\nconstruction-plane-only script) clears the 3D view. Undo back to a blank\nbuffer does not keep the previous solid. A failed non-empty script still\nrestores the last good mesh.\n\n**Rules for both:**\n- `contours` is an **array of contours** `[outer, hole1, ...]`; a single\n solid can be written as `[...pts]` (bare point list) — both accepted.\n- Every contour needs **≥ 3 distinct points**, closed polygon (auto-closed\n if first ≠ last). Open polylines / 2-point lists throw.\n- For a **hollow** part: outer contour + inner contour (through-hole).\n- Invalid profile → **named throw** (never a silent empty).\n\n---\n\n## Example: Complex Part\n\n\n\n## Security Notes\n\nScripts run in an isolated Web Worker sandbox with:\n- No network access (fetch, XMLHttpRequest, WebSocket blocked)\n- No storage access (indexedDB, localStorage blocked)\n- No worker spawning\n- Memory limits enforced\n- Execution timeout enforced\n\nImported models are available via `window.__importedManifolds['filename']`.",
|
|
1472
1472
|
"examples": [
|
|
1473
1473
|
"const fr = { center: [0, 0, 0], normal: [0, 0, 1], x: [1, 0, 0], y: [0, 1, 0] };\nconst xs0 = makeCrossSection(fr, profileCircle(5, 32));\nconst xs1 = makeCrossSection(offsetPlaneFrame(fr, 20), profileCircle(8, 32));\npart = placeInFrame(fr, makeLoft([xs0, xs1]));",
|
|
1474
1474
|
"// Create a flanged tube with mounting holes\n\n// Main tube\nconst mainTube = tube(15, 12, 40, 64);\n\n// Bottom flange\nconst flange = Manifold.cylinder(5, 25, 25, 64);\n\n// Mounting holes in flange\nconst bore = Manifold.cylinder(10, 3, 3, 32);\nconst holes = polarArray(bore, 4, 20, 'z');\n\n// Combine\nlet part = mainTube.add(flange);\npart = part.subtract(holes);\n\n// Center and align bottom to Z=0\npart = center(part, [true, true, false]);\npart = align(part, { min: [undefined, undefined, 0] });\n\nreturn part;"
|
package/package.json
CHANGED
package/src/bridge/relayHub.mjs
CHANGED
|
@@ -362,7 +362,8 @@ export function createAgentBridgeRelayHub(opts = {}) {
|
|
|
362
362
|
|
|
363
363
|
if (msg.type === PAIR_MSG.AGENT_PROMPT || msg.type === PAIR_MSG.AGENT_PROMPT_CANCEL
|
|
364
364
|
|| msg.type === PAIR_MSG.AGENT_PROMPT_ACK || msg.type === PAIR_MSG.AGENT_PROMPT_CANCEL_RESULT
|
|
365
|
-
|| msg.type === PAIR_MSG.AGENT_REPLY || msg.type === PAIR_MSG.AGENT_STATUS
|
|
365
|
+
|| msg.type === PAIR_MSG.AGENT_REPLY || msg.type === PAIR_MSG.AGENT_STATUS
|
|
366
|
+
|| msg.type === PAIR_MSG.AGENT_ACTIVITY) {
|
|
366
367
|
if (msg.type === PAIR_MSG.AGENT_PROMPT || msg.type === PAIR_MSG.AGENT_PROMPT_CANCEL) {
|
|
367
368
|
if (meta.role !== 'tab') {
|
|
368
369
|
sendJson(socket, {
|
|
@@ -5,17 +5,23 @@
|
|
|
5
5
|
|
|
6
6
|
export const FEATURE_GAP_PREFIX = '// FEATURE-GAP:';
|
|
7
7
|
|
|
8
|
+
/**
|
|
9
|
+
* The assembly-placement rule. Server instructions, guide assembly, the
|
|
10
|
+
* build-flow note, and the placement tool descriptions all use this sentence.
|
|
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.';
|
|
13
|
+
|
|
8
14
|
/** One line for the tools that create parts and insert features. */
|
|
9
|
-
export const BUILD_FLOW_NOTE =
|
|
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 Build and Shape, 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}`;
|
|
10
16
|
|
|
11
17
|
/** The full guidance, served by the MCP `guide` tool's `start` topic. */
|
|
12
18
|
export const BUILD_GUIDANCE = [
|
|
13
19
|
'How to build in SurfCAD. Work in the order of the feature ribbon: Block, Build, Shape, Polish, Move.',
|
|
14
|
-
'1. Block out first. Within seconds of the prompt, create every part of the assembly as plain blocks (create_part, then insert_cube, insert_rounded_box, insert_cylinder, insert_sphere, insert_tube, insert_hex_prism) at roughly the right size and position, 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.',
|
|
20
|
+
'1. Block out first. Within seconds of the prompt, create every part of the assembly as plain blocks (create_part, 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.',
|
|
15
21
|
'2. Build. Shape each block into its real form with Build and Shape features: insert_hole, insert_cut, insert_boolean, insert_shell, insert_add_draft; insert_cross_section, insert_workplane, insert_make_extrude, insert_make_revolve, insert_make_sweep, insert_make_loft (sketch_* and slot_* for the profiles).',
|
|
16
22
|
'3. Polish. insert_fillet_edges, insert_chamfer_edges, insert_move_face, insert_delete_face.',
|
|
17
|
-
|
|
23
|
+
`4. Pattern and place. insert_array3_d (grid), insert_polar_array (bolt circle), and insert_pattern_points (one copy at every hole center and axis from list_faces; Array Type=Points) for repeats and hardware, then insert_move, insert_rotate, insert_center, insert_align, insert_mirror for bodies inside one part. insert_polar_array drills the holes when boreRadius is greater than 0 and boltCircleRadius is the circle (it must be greater than 0); boreRadius 0 copies the body and boltCircleRadius 0 (the default) leaves it on the axis. A bolt circle of holes is that tool, not a FEATURE-GAP snippet. ${JOINT_PLACEMENT_GUIDANCE}`,
|
|
18
24
|
'Finish each stage across the whole assembly before starting the next, and take a screenshot after each stage.',
|
|
19
|
-
'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 }
|
|
20
|
-
'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
|
|
25
|
+
'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.',
|
|
26
|
+
'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 insert_polar_array { count, boltCircleRadius, axis, boreRadius, boreHeight }, 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.',
|
|
21
27
|
].join('\n');
|
|
@@ -103,6 +103,10 @@ export const ERROR_HINTS = Object.freeze({
|
|
|
103
103
|
unknown_assembly: { hint: 'Not a saved assembly id: list_assemblies {} and pass a row\'s id.' },
|
|
104
104
|
no_assembly: { hint: 'No document is open: create_assembly {} or open_assembly { assembly_id } first.' },
|
|
105
105
|
unknown_joint: { hint: 'The joint id is not in this assembly: joint_edit takes an id from a joint_commit result; joint_open {} starts a new one.' },
|
|
106
|
+
unjointed_part: {
|
|
107
|
+
hint: 'Place it with joint_create (one call creates the joint and solves placement). Fix a base part with type fixed first.',
|
|
108
|
+
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
|
+
},
|
|
106
110
|
no_joint_card: { hint: 'The joint card is closed: joint_open {} first, then joint_pick / joint_set_params / joint_commit.' },
|
|
107
111
|
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.' },
|
|
108
112
|
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.' },
|
|
@@ -284,5 +288,8 @@ export function withRowHints(value) {
|
|
|
284
288
|
if (isPlainObject(value.crash) && typeof value.crash.code === 'string') {
|
|
285
289
|
out = { ...out, crash: withErrorHint(value.crash) };
|
|
286
290
|
}
|
|
291
|
+
if (isPlainObject(value.warning) && typeof value.warning.code === 'string') {
|
|
292
|
+
out = { ...out, warning: withErrorHint(value.warning) };
|
|
293
|
+
}
|
|
287
294
|
return out;
|
|
288
295
|
}
|
package/src/prompt/guide.mjs
CHANGED
|
@@ -11,8 +11,8 @@
|
|
|
11
11
|
* (data/commands.json) and docs/agent/SKILL.md are the sources. Keep each
|
|
12
12
|
* topic under 1,500 words.
|
|
13
13
|
*/
|
|
14
|
-
import { BUILD_GUIDANCE } from './buildGuidance.mjs';
|
|
15
|
-
import { PROMPT_SERVER_INSTRUCTIONS } from './promptTools.mjs';
|
|
14
|
+
import { BUILD_GUIDANCE, JOINT_PLACEMENT_GUIDANCE } from './buildGuidance.mjs';
|
|
15
|
+
import { CLOSING_REPLY_GUIDANCE, PROMPT_SERVER_INSTRUCTIONS } from './promptTools.mjs';
|
|
16
16
|
import {
|
|
17
17
|
ERROR_TOPIC_CODES,
|
|
18
18
|
ERROR_TOPIC_PREFIX,
|
|
@@ -39,7 +39,9 @@ Then select_clear {} → camera_set { view: "iso" } → screenshot { save_to: tr
|
|
|
39
39
|
|
|
40
40
|
Reading results: every model-changing tool answers { ok, errors, status } with return "status" by default over MCP (no script echo; get_script reads it, get_script { range: { fromFeature, toFeature } } reads one span). status.runState is not_run_yet | ok | failed; errors rows are feature_failed with the viewport's text and a detail reason.
|
|
41
41
|
Ids are opaque surf ids from parts, list_assemblies, create_part, create_assembly; never a path or a display name.
|
|
42
|
-
Topics: guide { topic: "dialect" | "features" | "selection" | "paint" | "limits" | "camera" | "assembly" }; list_helpers { names } documents any script helper
|
|
42
|
+
Topics: guide { topic: "dialect" | "features" | "selection" | "paint" | "limits" | "camera" | "assembly" }; list_helpers { names } documents any script helper.
|
|
43
|
+
|
|
44
|
+
In-viewer prompt pane. ${CLOSING_REPLY_GUIDANCE} set_status is for progress and does not close the task.`;
|
|
43
45
|
|
|
44
46
|
const FEATURES = `Feature blocks. The script of a part is plain JavaScript over the SurfCAD helpers, and the feature strip reads it from marker comments. Every insert_* writes one block:
|
|
45
47
|
|
|
@@ -55,7 +57,7 @@ That trailing marker is the contour id (c1, c2, ...). Extrude, Revolve, Loft and
|
|
|
55
57
|
|
|
56
58
|
What the markers buy you:
|
|
57
59
|
- feature_tree {} lists the blocks; open_feature { id | index } opens that block's card, edit_feature { params } merges fields (keys depend on the kind: height, radius, distance; for a move dx, dy, dz, at), confirm_feature {} writes and runs. A confirm that changes nothing on a failing part answers ok: false with the errors.
|
|
58
|
-
- delete_feature { id | index } removes the block and runs
|
|
60
|
+
- delete_feature { id | index, part_id? } removes the block from the active part and runs it; one undo restores it. A face pick does not retarget it. part_id (an opaque surf id) deletes from that part instead; a path or name is unknown_part. Deleting the block that declares part while later blocks use it is confirm_required (details.dependents) until the user agrees and you pass confirm: true.
|
|
59
61
|
- rollback_to { id | index } moves the rollback bar and re-evaluates up to there without editing the script; rollback_to { clear: true } removes it.
|
|
60
62
|
- undo / redo step the feature-bar stack (sketch session, assembly joints, or the active part) and return applied / reverted labels; a new committed edit clears redo.
|
|
61
63
|
- get_script { range: { fromFeature: "cube1", toFeature: "fillet2" } } reads one span of blocks.
|
|
@@ -66,15 +68,15 @@ Sketch sessions. sketch_begin → sketch_add { tool, ... } / pick_points { kind,
|
|
|
66
68
|
|
|
67
69
|
const SELECTION = `Selection. Faces and edges are addressed by keys that survive a rerun of the same script and are invalid after a remesh.
|
|
68
70
|
|
|
69
|
-
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). 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; page { offset, limit } returns one slice; the result carries total (after the filter) and returned. 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.
|
|
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; page { offset, limit } returns one slice; the result carries total (after the filter) and returned. 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.
|
|
70
72
|
|
|
71
|
-
Edges. list_feature_edges gives grouped ids e0, e1, ... (a whole edge chain, the stable choice); list_edges gives raw mesh edges. Both take filter { between: [faceKeyA, faceKeyB], minLength, maxLength, bbox } and page.
|
|
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.
|
|
72
74
|
|
|
73
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 }.
|
|
74
76
|
|
|
75
77
|
use_selection is single use. Every successful rebuild (each insert_*, set_script, undo) clears the picks because they index the mesh that was replaced. Pick, insert once with use_selection: true, then pick again before the next one. With nothing selected that insert answers no_selection and writes nothing (never the default face). Every insert_* / invoke_helper result carries usedSelection: true | false. Omit use_selection to take the helper default: the +Z top face for holes, every convex edge for fillet and chamfer.
|
|
76
78
|
|
|
77
|
-
Fillet
|
|
79
|
+
Fillet from a face pick. insert_fillet_edges { use_selection: true, radius } with a face selected takes the convex edges whose adjacent face normal is within about 18 degrees of the picked face normal, over the whole body, so on a large part that set can be big and slow (see guide limits). Chamfer from a face pick. insert_chamfer_edges { use_selection: true, chamfer } writes edgesOf for a named face, including one the face graph calls irregular: that face's boundary only. A face pick with no name that is not planar or cylindrical is refused, not every convex edge. A chamfer that would split the solid fails as feature_failed and the part stays as it was. For a precise set, pick grouped edges (list_feature_edges, select_edges { keys: ["e3", "e4"] }) and insert with use_selection: true, or run the card: pick_begin → pick_next → pick_done.
|
|
78
80
|
|
|
79
81
|
Bodies. insert_move { dx, dy, dz } must name its body: body_index or at (a centroid) from list_bodies {}, face_id or face (key) from list_faces, or use_selection: true with a face selected; nothing named is no_body.`;
|
|
80
82
|
|
|
@@ -108,32 +110,34 @@ Before a screenshot for the user: select_clear {} so highlights and pick rings d
|
|
|
108
110
|
|
|
109
111
|
const ASSEMBLY = `Assemblies, placement and joints.
|
|
110
112
|
|
|
111
|
-
Documents. create_assembly { name? } seeds an empty assembly with one empty part (no seed cube; single-flight per tab; no git write). open_assembly { assembly_id } opens a saved one; list_assemblies {} returns [{ id, name, open }]. parts {} returns assemblyId, activeId and every part row with runState and crash, so a failed part that is not active is visible without switching.
|
|
113
|
+
Documents. create_assembly { name? } seeds an empty assembly with one empty part (no seed cube; single-flight per tab; no git write). open_assembly { assembly_id } opens a saved one; list_assemblies {} returns [{ id, name, open }]. parts {} returns assemblyId, activeId, unjointedParts and every part row with runState and crash, so a failed part that is not active is visible without switching. status carries the same unjointedParts list. unjointedParts is empty for a single-part document; a base part with a fixed joint is omitted.
|
|
112
114
|
|
|
113
|
-
Parts. create_part { name?, script?, position? } adds a part, makes it active and returns its new opaque id. Agent-created parts land at the assembly origin unless position [x, y, z] mm is given; parts created from the UI stagger along +X. The part starts empty; the first insert_* creates the body. Feature tools write the active part, so set_active_part { part_id } before inserting. rename_part changes the label only; delete_part { part_id, scope: "assembly" | "repo" } drops the row (repo also plans the file delete and needs confirm: true).
|
|
115
|
+
Parts. create_part { name?, script?, position? } adds a part, makes it active and returns its new opaque id. Agent-created parts land at the assembly origin unless position [x, y, z] mm is given (a rough block-out; joint_create sets the final pose of a part that touches another); parts created from the UI stagger along +X. The part starts empty; the first insert_* creates the body. Feature tools write the active part, so set_active_part { part_id } before inserting. rename_part changes the label only; delete_part { part_id, scope: "assembly" | "repo" } drops the row (repo also plans the file delete and needs confirm: true).
|
|
114
116
|
|
|
115
117
|
Reuse. insert_part { part_id } or { assembly_id } inserts by reference (the same id; one definition shared across assemblies). copy: true mints a new id and sets copiedFrom. open_part { part_id } opens a vault part into the document.
|
|
116
118
|
|
|
117
|
-
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
|
|
119
|
+
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.
|
|
120
|
+
|
|
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.
|
|
118
122
|
|
|
119
|
-
|
|
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. Fixed takes one pick; every other type takes two, one per part. Distance is mm, angle is degrees.
|
|
120
124
|
|
|
121
|
-
Joints
|
|
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" }.
|
|
122
126
|
|
|
123
|
-
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; insert_pattern_points { points: [{ at, axis }, ...], up } on the fastener part places one instance per hole; insert_array3_d
|
|
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.
|
|
124
128
|
|
|
125
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.`;
|
|
126
130
|
|
|
127
131
|
/** Topic name → one-line summary and the text. Order is the listing order. */
|
|
128
132
|
export const GUIDE_TOPICS = Object.freeze({
|
|
129
|
-
start: { summary: 'How to build in SurfCAD (block, build, polish, place), a three-call example, how to read results', text: START },
|
|
133
|
+
start: { summary: 'How to build in SurfCAD (block, build, polish, place), a three-call example, how to read results, and the closing reply for an in-viewer prompt', text: START },
|
|
130
134
|
dialect: { summary: DIALECT_SUMMARY, text: renderDialectTopic() },
|
|
131
135
|
features: { summary: 'Marker blocks, feature ids, edit / delete / rollback / undo, script snippets, sketches', text: FEATURES },
|
|
132
136
|
selection: { summary: 'Face and edge keys, list_faces filters, single-use picks, no_selection, fillet edge sets', text: SELECTION },
|
|
133
137
|
paint: { summary: 'paint_open → paint_set_color → paint_part / paint_faces → paint_confirm; colours persist with the assembly', text: PAINT },
|
|
134
138
|
limits: { summary: 'The 30 s kernel budget, what is slow, worker restarts and stale status, result sizes, pairing errors', text: LIMITS },
|
|
135
139
|
camera: { summary: 'Which side each named view looks from, explicit poses, select_clear before a screenshot, screenshot to file', text: CAMERA },
|
|
136
|
-
assembly: { summary: 'Documents, create_part placement, insert by reference, part instances,
|
|
140
|
+
assembly: { summary: 'Documents, create_part placement, insert by reference, part instances, joint_create as the default assembly path, hardware, git_save', text: ASSEMBLY },
|
|
137
141
|
});
|
|
138
142
|
|
|
139
143
|
/** The core topics, in listing order (the error topics are listed on one line after them). */
|
|
@@ -214,7 +218,7 @@ export const SERVER_INSTRUCTIONS = [
|
|
|
214
218
|
PROMPT_SERVER_INSTRUCTIONS,
|
|
215
219
|
'',
|
|
216
220
|
`SurfCAD quick start. Pair, then call guide { topic: "start" } before the first model call; guide {} lists every topic (${GUIDE_TOPIC_NAMES.join(', ')}; every error payload carries hint, and see names its errors.<code> topic).`,
|
|
217
|
-
'Flow, in ribbon order, each stage across the whole assembly before the next: 1 Block: create_part, then insert_cube / insert_cylinder / insert_tube at rough size, screenshot for the user. 2 Build: insert_hole, insert_cut, insert_shell, insert_make_extrude / revolve / sweep / loft. 3 Polish: insert_fillet_edges, insert_chamfer_edges on small edge sets. 4 Place:
|
|
221
|
+
'Flow, in ribbon order, each stage across the whole assembly before the next: 1 Block: create_part, then insert_cube / insert_cylinder / insert_tube at rough size and position, screenshot for the user. 2 Build: insert_hole, insert_cut, insert_shell, insert_make_extrude / revolve / sweep / loft. 3 Polish: insert_fillet_edges, insert_chamfer_edges on small edge sets. 4 Place: fix one base part with a fixed joint, then joint_create for every part that touches or attaches to another (one call creates the joint and solves placement). part_set_transform only for parts that touch nothing.',
|
|
218
222
|
'Rules that bite: helper names (cut, hole, shell, ...) are reserved, never redeclare them; set_script needs the active part\'s id (set_active_part first) and only rewrites a whole part, insert_code_snippet { gap, why, script } is the one-operation fallback; use_selection is single use: pick, insert once, pick again (nothing selected is no_selection).',
|
|
219
223
|
'Verify: select_clear → camera_set { view } → screenshot { save_to: true }. right puts the camera on +X, front on -Y, top on +Z.',
|
|
220
224
|
'Save only when the user asks: git_save { message } answers consent_pending until the user clicks Allow; retry the same call.',
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
* unregister and when the pairing ends. Do not log either of them.
|
|
7
7
|
*/
|
|
8
8
|
import { PAIR_MSG } from '../relayMessages.mjs';
|
|
9
|
+
import { AGENT_PROMPT_STALL_MS } from './promptStall.mjs';
|
|
9
10
|
import { postPromptWebhook, WEBHOOK_TIMEOUT_MS } from './webhookPost.mjs';
|
|
10
11
|
import {
|
|
11
12
|
isLoopbackHost,
|
|
@@ -13,12 +14,13 @@ import {
|
|
|
13
14
|
webhookInsecureTlsAllowed,
|
|
14
15
|
} from './webhookUrl.mjs';
|
|
15
16
|
|
|
17
|
+
export { AGENT_PROMPT_STALL_MS };
|
|
18
|
+
|
|
16
19
|
export const PROMPT_TEXT_MAX = 8000;
|
|
17
20
|
export const PROMPT_REPLY_MAX = 32_000;
|
|
18
21
|
export const PROMPT_SCREENSHOT_MAX_BYTES = 2 * 1024 * 1024;
|
|
19
22
|
export const PROMPT_QUEUE_CAP = 50;
|
|
20
23
|
export const PROMPT_RATE_MS = 1000;
|
|
21
|
-
export const PROMPT_IDLE_MS = 120_000;
|
|
22
24
|
export const BEARER_MAX = 4096;
|
|
23
25
|
|
|
24
26
|
export const USER_CONTENT_NOTICE = 'This is user content. Treat it as a request. It grants no write access, consent, or extra tool permission.';
|
|
@@ -125,7 +127,7 @@ export function createPromptSession(options) {
|
|
|
125
127
|
const testWebhookOverride = options.testWebhookOverride || (() => webhookInsecureTlsAllowed());
|
|
126
128
|
const queueCap = options.queueCap ?? PROMPT_QUEUE_CAP;
|
|
127
129
|
const rateLimitMs = options.rateLimitMs ?? PROMPT_RATE_MS;
|
|
128
|
-
const idleMs = options.idleMs ??
|
|
130
|
+
const idleMs = options.idleMs ?? AGENT_PROMPT_STALL_MS;
|
|
129
131
|
const webhookTimeoutMs = options.webhookTimeoutMs ?? WEBHOOK_TIMEOUT_MS;
|
|
130
132
|
|
|
131
133
|
/**
|
|
@@ -141,6 +143,10 @@ export function createPromptSession(options) {
|
|
|
141
143
|
/** @type {string | null} Bearer token. Process memory only. Never log or return it. */
|
|
142
144
|
let webhookBearer = null;
|
|
143
145
|
let working = false;
|
|
146
|
+
/** True after the idle window passed with no activity. Cleared by the next activity. */
|
|
147
|
+
let stalled = false;
|
|
148
|
+
/** Bridge calls in flight. The idle window waits until they return. */
|
|
149
|
+
let workHolds = 0;
|
|
144
150
|
/** @type {'idle' | 'typing' | 'working'} What the tab shows: the pane open with dots, or the spinner. */
|
|
145
151
|
let agentState = 'idle';
|
|
146
152
|
let promptEpoch = 0;
|
|
@@ -178,12 +184,50 @@ export function createPromptSession(options) {
|
|
|
178
184
|
|
|
179
185
|
function armIdle() {
|
|
180
186
|
clearIdle();
|
|
187
|
+
if (!working || stalled || workHolds > 0) return;
|
|
181
188
|
idleTimer = setTimer(() => {
|
|
182
189
|
idleTimer = null;
|
|
183
|
-
if (working
|
|
190
|
+
if (!working || stalled || workHolds > 0) return;
|
|
191
|
+
stalled = true;
|
|
192
|
+
const msg = { type: PAIR_MSG.AGENT_STATUS, v: 1, working: true, state: agentState, stalled: true };
|
|
193
|
+
if (typeof lastId === 'string' && lastId) msg.id = lastId;
|
|
194
|
+
emit(msg);
|
|
184
195
|
}, idleMs);
|
|
185
196
|
}
|
|
186
197
|
|
|
198
|
+
/**
|
|
199
|
+
* The agent did something that is not a state change (another tool call,
|
|
200
|
+
* a read_messages poll). Restart the idle window and tell the tab, so its
|
|
201
|
+
* own deadline restarts too. A stall notice is replaced by the live state.
|
|
202
|
+
*/
|
|
203
|
+
function noteActivity() {
|
|
204
|
+
if (lastId && states.get(lastId) === 'cancelled') return;
|
|
205
|
+
if (!working) return;
|
|
206
|
+
if (stalled) {
|
|
207
|
+
emitState(agentState, lastId, true);
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
armIdle();
|
|
211
|
+
if (workHolds > 0) return;
|
|
212
|
+
const msg = { type: PAIR_MSG.AGENT_ACTIVITY, v: 1 };
|
|
213
|
+
if (typeof lastId === 'string' && lastId) msg.id = lastId;
|
|
214
|
+
emit(msg);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* @param {boolean} held
|
|
219
|
+
*/
|
|
220
|
+
function holdWork(held) {
|
|
221
|
+
if (held) {
|
|
222
|
+
workHolds += 1;
|
|
223
|
+
clearIdle();
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
workHolds = Math.max(0, workHolds - 1);
|
|
227
|
+
if (workHolds > 0 || !working) return;
|
|
228
|
+
noteActivity();
|
|
229
|
+
}
|
|
230
|
+
|
|
187
231
|
/**
|
|
188
232
|
* Send the agent state to the tab. `working` stays on the message for tabs
|
|
189
233
|
* that predate `state`: true for typing and working, false for idle.
|
|
@@ -194,10 +238,11 @@ export function createPromptSession(options) {
|
|
|
194
238
|
*/
|
|
195
239
|
function emitState(state, id, force, label) {
|
|
196
240
|
const next = state !== 'idle';
|
|
197
|
-
if (!force && agentState === state) {
|
|
241
|
+
if (!force && agentState === state && !stalled) {
|
|
198
242
|
if (next) armIdle();
|
|
199
243
|
return true;
|
|
200
244
|
}
|
|
245
|
+
stalled = false;
|
|
201
246
|
working = next;
|
|
202
247
|
agentState = state;
|
|
203
248
|
const msg = { type: PAIR_MSG.AGENT_STATUS, v: 1, working: next, state };
|
|
@@ -513,6 +558,7 @@ export function createPromptSession(options) {
|
|
|
513
558
|
? { data: item.screenshot.data, mimeType: 'image/png' }
|
|
514
559
|
: null);
|
|
515
560
|
}
|
|
561
|
+
noteActivity();
|
|
516
562
|
return { messages, images };
|
|
517
563
|
}
|
|
518
564
|
|
|
@@ -610,10 +656,10 @@ export function createPromptSession(options) {
|
|
|
610
656
|
if (promptEpoch > workedEpoch) {
|
|
611
657
|
workedEpoch = promptEpoch;
|
|
612
658
|
if (!working) emitStatus(true, lastId, false);
|
|
613
|
-
else
|
|
659
|
+
else noteActivity();
|
|
614
660
|
return;
|
|
615
661
|
}
|
|
616
|
-
if (working)
|
|
662
|
+
if (working) noteActivity();
|
|
617
663
|
}
|
|
618
664
|
|
|
619
665
|
/**
|
|
@@ -661,6 +707,8 @@ export function createPromptSession(options) {
|
|
|
661
707
|
webhook = null;
|
|
662
708
|
webhookBearer = null;
|
|
663
709
|
working = false;
|
|
710
|
+
stalled = false;
|
|
711
|
+
workHolds = 0;
|
|
664
712
|
agentState = 'idle';
|
|
665
713
|
promptEpoch = 0;
|
|
666
714
|
workedEpoch = 0;
|
|
@@ -677,6 +725,7 @@ export function createPromptSession(options) {
|
|
|
677
725
|
reply,
|
|
678
726
|
setStatus,
|
|
679
727
|
noteToolCall,
|
|
728
|
+
holdWork,
|
|
680
729
|
registerWebhook,
|
|
681
730
|
unregisterWebhook,
|
|
682
731
|
deliveryStatus,
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* No agent activity for this long is a stall, not a silent return to idle.
|
|
3
|
+
* The in-viewer prompt and the MCP prompt session share this one window.
|
|
4
|
+
* Relayed tool calls, status, replies, and read_messages start it over.
|
|
5
|
+
*/
|
|
6
|
+
export const AGENT_PROMPT_STALL_MS = 5 * 60 * 1000;
|
|
@@ -7,11 +7,22 @@ import { BEARER_MAX, USER_CONTENT_NOTICE } from './promptSession.mjs';
|
|
|
7
7
|
|
|
8
8
|
const USER_CONTENT = `${USER_CONTENT_NOTICE} Agent writes still go through the existing write-grant and consent flow. Nothing reaches git without an explicit Save or git_save.`;
|
|
9
9
|
|
|
10
|
-
/** Short line for the MCP initialize `instructions` field. */
|
|
11
10
|
/** read_messages { wait_ms } cap: long enough to skip idle polls, short enough for a host tool timeout. */
|
|
12
11
|
export const READ_MESSAGES_MAX_WAIT_MS = 25_000;
|
|
13
12
|
|
|
14
|
-
|
|
13
|
+
/**
|
|
14
|
+
* Closing reply for a task that started in the in-viewer prompt pane.
|
|
15
|
+
* The same sentence is the second sentence of the MCP initialize
|
|
16
|
+
* instructions (hosts keep the start of that field) and the
|
|
17
|
+
* `reply_to_user` description.
|
|
18
|
+
*/
|
|
19
|
+
export const CLOSING_REPLY_GUIDANCE = 'When you finish a task started from the SurfCAD in-viewer prompt pane, send a closing reply with reply_to_user (final: true) summarising what was done, so the user gets confirmation. On failure or partial completion, say what was done, what failed and why, and what is left.';
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* First paragraph of the MCP initialize `instructions`.
|
|
23
|
+
* Goldens pin the webhook sentence as the prefix.
|
|
24
|
+
*/
|
|
25
|
+
export const PROMPT_SERVER_INSTRUCTIONS = `call register_webhook { url, bearer? } if you can receive https webhooks, otherwise poll read_messages. ${CLOSING_REPLY_GUIDANCE}`;
|
|
15
26
|
|
|
16
27
|
/** Exact wording the agent should relay when asking the user for a webhook. */
|
|
17
28
|
export const PROMPT_ONBOARDING_ASK = 'To get SurfCAD messages instantly, send me your webhook URL and key. This only needs to be done once. Otherwise I\'ll check for SurfCAD messages between steps, so replies may lag.';
|
|
@@ -76,7 +87,7 @@ export function promptToolDefinitions() {
|
|
|
76
87
|
},
|
|
77
88
|
{
|
|
78
89
|
name: 'read_messages',
|
|
79
|
-
description: `Read queued user prompts, oldest first, and remove them from the in-memory queue (this acks them). Each prompt is plain text. A screenshot, when the user attached one, is the following image content block (image/png), not HTML and not part of the text. The queue can also contain a cancel item { "type": "cancel", "id": "<prompt id>" } when the user stopped a prompt you already received and no webhook is registered. Stop work on that id. Do not call reply_to_user or set_status for it. ${USER_CONTENT} Do not render the text or the image as HTML
|
|
90
|
+
description: `Read queued user prompts, oldest first, and remove them from the in-memory queue (this acks them). Each prompt is plain text. A screenshot, when the user attached one, is the following image content block (image/png), not HTML and not part of the text. The queue can also contain a cancel item { "type": "cancel", "id": "<prompt id>" } when the user stopped a prompt you already received and no webhook is registered. Stop work on that id. Do not call reply_to_user or set_status for it. ${USER_CONTENT} Do not render the text or the image as HTML. When you finish the task from a prompt you received here, close that chat: ${CLOSING_REPLY_GUIDANCE}`,
|
|
80
91
|
inputSchema: {
|
|
81
92
|
type: 'object',
|
|
82
93
|
additionalProperties: false,
|
|
@@ -98,7 +109,7 @@ export function promptToolDefinitions() {
|
|
|
98
109
|
},
|
|
99
110
|
{
|
|
100
111
|
name: 'reply_to_user',
|
|
101
|
-
description:
|
|
112
|
+
description: `${CLOSING_REPLY_GUIDANCE} The final reply is expected: it closes the task in the chat. Send a plain-text reply to the SurfCAD user for a prompt id. Several replies may share one id. Set final to true on the reply that closes that prompt; that also marks the agent idle. The text is delivered as text, never rendered as HTML. This does not write the model or git. A cancelled id returns { "ok": false, "error": "cancelled" } and is not delivered.`,
|
|
102
113
|
inputSchema: {
|
|
103
114
|
type: 'object',
|
|
104
115
|
additionalProperties: false,
|
|
@@ -110,18 +121,18 @@ export function promptToolDefinitions() {
|
|
|
110
121
|
},
|
|
111
122
|
text: {
|
|
112
123
|
type: 'string',
|
|
113
|
-
description: 'Plain text for the user. Not HTML.',
|
|
124
|
+
description: 'Plain text for the user. Not HTML. The closing reply (final: true) summarises what was done, or on failure or partial completion what was done, what failed and why, and what is left.',
|
|
114
125
|
},
|
|
115
126
|
final: {
|
|
116
127
|
type: 'boolean',
|
|
117
|
-
description: 'True
|
|
128
|
+
description: 'True on the closing reply that finishes the prompt. That reply is expected and summarises the result or the failure. Defaults to false.',
|
|
118
129
|
},
|
|
119
130
|
},
|
|
120
131
|
},
|
|
121
132
|
},
|
|
122
133
|
{
|
|
123
134
|
name: 'set_status',
|
|
124
|
-
description:
|
|
135
|
+
description: `Tell the SurfCAD tab what you are doing with the user's prompt: state typing (writing an answer: the chat stays open with typing dots), working (changing the model: the chat collapses and the field shows a spinner), or idle. set_status is for progress and does not close the task. You do not have to call it for working: the first model-changing tool call after a prompt sets working, a streamed reply_to_user (final false) sets typing, and a final reply or 120 seconds without activity sets idle. Set typing before a long answer so the user reads the chat instead of watching the viewport. Without id it targets the latest prompt. A cancelled id returns { ok: false, error: cancelled }. ${CLOSING_REPLY_GUIDANCE}`,
|
|
125
136
|
inputSchema: {
|
|
126
137
|
type: 'object',
|
|
127
138
|
additionalProperties: false,
|
|
@@ -129,7 +140,7 @@ export function promptToolDefinitions() {
|
|
|
129
140
|
state: {
|
|
130
141
|
type: 'string',
|
|
131
142
|
enum: ['typing', 'working', 'idle'],
|
|
132
|
-
description: 'typing: you are writing an answer (the tab keeps the chat open with typing dots). working: you are changing the model (the tab collapses the chat and shows a spinner). idle:
|
|
143
|
+
description: 'typing: you are writing an answer (the tab keeps the chat open with typing dots). working: you are changing the model (the tab collapses the chat and shows a spinner). idle: not typing or changing the model. Idle does not close the task; a closing reply_to_user does. Set typing before a long answer; model-changing tool calls set working on their own; a final reply_to_user sets idle.',
|
|
133
144
|
},
|
|
134
145
|
label: {
|
|
135
146
|
type: 'string',
|
package/src/relay.mjs
CHANGED
|
@@ -156,6 +156,19 @@ export class RelaySession {
|
|
|
156
156
|
}
|
|
157
157
|
}
|
|
158
158
|
|
|
159
|
+
/**
|
|
160
|
+
* Pause the working deadline while a bridge call is in flight, then
|
|
161
|
+
* start it again when the call returns. A long tool call is activity.
|
|
162
|
+
* @param {boolean} held
|
|
163
|
+
*/
|
|
164
|
+
holdAgentWork(held) {
|
|
165
|
+
try {
|
|
166
|
+
this.#prompts.holdWork(held === true);
|
|
167
|
+
} catch {
|
|
168
|
+
/* status is advisory */
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
159
172
|
/**
|
|
160
173
|
* @param {object} payload
|
|
161
174
|
*/
|
package/src/relayMessages.mjs
CHANGED
|
@@ -21,6 +21,8 @@ export const PAIR_MSG = Object.freeze({
|
|
|
21
21
|
AGENT_REPLY: 'agent.reply',
|
|
22
22
|
/** Agent → page. Contract v:1. */
|
|
23
23
|
AGENT_STATUS: 'agent.status',
|
|
24
|
+
/** Agent → page. Contract v:1. Refreshes the working deadline without changing state. */
|
|
25
|
+
AGENT_ACTIVITY: 'agent.activity',
|
|
24
26
|
/** Page → paired agent. Contract v:1. `{ id }`. */
|
|
25
27
|
AGENT_PROMPT_CANCEL: 'agent.prompt.cancel',
|
|
26
28
|
/** Agent → page. Contract v:1. `{ id, state }`. */
|
package/src/server.mjs
CHANGED
|
@@ -289,9 +289,17 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
289
289
|
|
|
290
290
|
try {
|
|
291
291
|
// A model-changing tool switches the tab to working on its own.
|
|
292
|
+
// The call holds the idle window until it returns: a long tool call
|
|
293
|
+
// is the agent working, not a stall.
|
|
292
294
|
const row = catalog.commands.find((c) => c.name === name);
|
|
293
295
|
session.noteAgentToolCall({ mutates: row?.mutates === true || (row?.mutates == null && mutatingTool(name)) });
|
|
294
|
-
|
|
296
|
+
session.holdAgentWork(true);
|
|
297
|
+
let out;
|
|
298
|
+
try {
|
|
299
|
+
out = await callPairedBridgeTool(session, name, withDefaultReturn(row, args));
|
|
300
|
+
} finally {
|
|
301
|
+
session.holdAgentWork(false);
|
|
302
|
+
}
|
|
295
303
|
if (name === 'status' && out.isError !== true && out.value && typeof out.value === 'object' && !Array.isArray(out.value)) {
|
|
296
304
|
return textResult({ ...out.value, ...session.prompts.deliveryStatus() });
|
|
297
305
|
}
|