surfcad-mcp 0.2.5 → 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.
@@ -0,0 +1,289 @@
1
+ /**
2
+ * The `guide` tool: agent know-how delivered by the MCP server itself, so a
3
+ * fresh agent does not learn the dialect by inserting scratch features.
4
+ *
5
+ * The initialize `instructions` stay a short quick-start (under 2 KB, hosts
6
+ * truncate long ones) and point here. The long text lives in the topics
7
+ * below. `start` carries the build guidance verbatim (BUILD_GUIDANCE is the
8
+ * one copy, shared with the app side and pinned by a freshness test).
9
+ *
10
+ * Every statement here describes the current tool contract; the catalog
11
+ * (data/commands.json) and docs/agent/SKILL.md are the sources. Keep each
12
+ * topic under 1,500 words.
13
+ */
14
+ import { BUILD_GUIDANCE, JOINT_PLACEMENT_GUIDANCE } from './buildGuidance.mjs';
15
+ import { CLOSING_REPLY_GUIDANCE, PROMPT_SERVER_INSTRUCTIONS } from './promptTools.mjs';
16
+ import {
17
+ ERROR_TOPIC_CODES,
18
+ ERROR_TOPIC_PREFIX,
19
+ errorTopic,
20
+ errorTopicName,
21
+ EXTRA_ERROR_TOPICS,
22
+ withErrorHint,
23
+ } from './errorHints.mjs';
24
+ import { loadPackageVersion } from '../packageVersion.mjs';
25
+ import { DIALECT_SUMMARY, renderDialectTopic } from '../helpers.mjs';
26
+
27
+ export const GUIDE_TOOL_NAME = 'guide';
28
+
29
+ /** Instructions are truncated by some hosts past a few KB; the test pins this. */
30
+ export const INSTRUCTIONS_MAX_BYTES = 2048;
31
+
32
+ const START = `${BUILD_GUIDANCE}
33
+
34
+ Quick start, three calls after pair:
35
+ 1. create_part { name: "Hub" } then insert_tube { outerRadius: 20, innerRadius: 14, height: 40 }. The part is active when create_part returns; its result carries the opaque partId. Numbers are mm.
36
+ 2. list_faces { filter: { kind: "planar", normalWithin: { n: [0, 0, 1], deg: 5 } } } → select_faces { keys: [<that row's key>] } → insert_tap_drill_hole { use_selection: true, size: "M5", u: 0, v: 0 } (or insert_hole). The pick is consumed by this one insert.
37
+ 3. paint_open {} → paint_set_color { color: "#2f6fdb" } → paint_part {} (or paint_faces { keys }) → paint_confirm {}.
38
+ Then select_clear {} → camera_set { view: "iso" } → screenshot { save_to: true } and show the user.
39
+
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
+ 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.
43
+
44
+ In-viewer prompt pane. ${CLOSING_REPLY_GUIDANCE} set_status is for progress and does not close the task.`;
45
+
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:
47
+
48
+ // --- cube begin id=cube1 ---
49
+ part = Manifold.cube([40, 40, 20], true);
50
+ // --- cube end id=cube1 ---
51
+
52
+ The kind sits between "--- " and " begin"; the optional id=<name> follows it. The strip lists blocks in script order and feature_tree returns them as { id, kind, label, chipLabel, index }; a block without id= is still found and addressed by index. Contour, fillet and chamfer blocks use mode markers (contour-mode extrude / revolve / loft / sweep, fillet-mode, chamfer-mode); a saved contour is its own statement that owns its plane:
53
+
54
+ const c1 = makeCrossSection({ center, normal, x, y }, solveContour({ ... })); // @contour id=c1
55
+
56
+ That trailing marker is the contour id (c1, c2, ...). Extrude, Revolve, Loft and Sweep blocks name the contours they use. A freehand script that keeps this marker style keeps per-feature undo, delete and rollback; a set_script without markers is one feature.
57
+
58
+ What the markers buy you:
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.
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.
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.
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.
63
+ - get_script { range: { fromFeature: "cube1", toFeature: "fillet2" } } reads one span of blocks.
64
+
65
+ 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.
66
+
67
+ Sketch sessions. sketch_begin → sketch_add { tool, ... } / pick_points { kind, keys } → sketch_commit saves a contour; sketch_cancel leaves. In-contour entities are p0, e0, a0, ...; a saved contour is @contour id=c1 in the script.`;
68
+
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.
70
+
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.
72
+
73
+ Edges. list_feature_edges gives grouped ids e0, e1, ... (a whole edge chain, the stable choice); list_edges gives raw mesh edges. Both set frame to "local" (midpoints in the same part frame as list_faces) and take filter { between: [faceKeyA, faceKeyB], minLength, maxLength, bbox } and page.
74
+
75
+ Picking. select_faces { keys: [...] } and select_edges { keys } set the viewport selection; select_clear {} clears faces, edges and contour picks. pick_begin → pick_next { keys: ["e3"] } → pick_done { accept: true } drives a card's pick session; a keys item is a grouped edge id (eN), a face id (fN), a face key, or an edge face pair { faceKeyA, faceKeyB }.
76
+
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.
78
+
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.
80
+
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.`;
82
+
83
+ const PAINT = `Paint. Colours live on the assembly document (a colors map keyed by the part's surf id), so they persist across reloads and are written by the next git_save; the same part can carry different colours in two assemblies.
84
+
85
+ Sequence: set_active_part { part_id } → paint_open {} → paint_set_color { color: "#rrggbb" } (hex is an alias) → paint_part {} for the whole part, or paint_faces { keys: [...] } with keys from list_faces → paint_confirm {}. paint_undo {} steps back inside the session, paint_clear {} removes the part's colours, paint_cancel {} / paint_close {} leave without writing.
86
+
87
+ paint_open is safe straight after create_part or set_active_part: it waits up to 1.5 s for the viewport to take paint mode. Past that it answers not_ready with details.reason (prompt_working while an in-viewer prompt is being worked, or mode_not_ready) and details.retryable: true; call paint_open again. Already open answers { open: true, already: true }. Game mode is bad_view.
88
+
89
+ Paint writes the working copy only; nothing reaches the vault until git_save.`;
90
+
91
+ const LIMITS = `Limits and budgets.
92
+
93
+ Each kernel job has 30 seconds. A run past that budget is treated like a crash: the geometry worker is killed and replaced, the mutate result carries crash { reason: "timeout" }, and errors has one geometry_worker_crashed row with workerRestarted: true. Out of memory and wasm aborts report the same way with reason out_of_memory or wasm_abort. Other parts keep building. Do not ask for a reload and do not retry the same script: simplify the part, lower segment counts, split the body, or pick a smaller edge set, then run again.
94
+
95
+ What is expensive: filletEdges / chamferEdges over many edges (a face pick on a large body selects every aligned convex edge; pick grouped edges instead), fillets on swept or lofted bodies, high segment counts on tubes, spheres and revolves, boolean chains over dozens of bodies, list_faces on a detailed part (filter and page it), list_commands without a group.
96
+
97
+ After a timeout. undo waits for the replaced worker, re-runs the restored script and reports that run (with return: "full", status.script is the restored script). If the run still did not report, status.stale: true says the numbers are the previous run's: call run {} again and read status. A status without stale is current.
98
+
99
+ 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 whole catalog, about 130 KB.
100
+
101
+ Pairing. A bridge call before pair is not_paired. pair returns pair_pending while the user has not clicked Allow. pairing_lost means the tab or relay dropped and the server re-pairs on its own: retry in a few seconds, do not ask for a new code. Numbers are finite and within ±1,000,000 mm; NaN and Infinity are bad_args.`;
102
+
103
+ const CAMERA = `Camera and screenshots.
104
+
105
+ 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).
106
+
107
+ 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.
108
+
109
+ Before a screenshot for the user: select_clear {} so highlights and pick rings do not paint the frame, then camera_set, then screenshot { save_to: true } (or a path), which writes the PNG on the MCP host and returns { path, size } instead of base64; max_width or scale downscale, format jpeg with quality shrinks further. An open feature card's view offset is not applied to the capture. Take one after each build stage, and before asking the user to judge proportions.`;
110
+
111
+ const ASSEMBLY = `Assemblies, placement and joints.
112
+
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.
114
+
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).
116
+
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.
118
+
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.
122
+
123
+ Joints. joint_create { type, picks } is the call. type is coincident, parallel, perpendicular, distance, angle, concentric, symmetric or fixed (planar is coincident). picks come from list_faces: face_id with its key, a cylindrical face as an axis, or { part_id } alone for a whole-part pick. Fixed takes one pick; every other type takes two, one per part. Distance is mm, angle is degrees.
124
+
125
+ The Joints card is the advanced path for the same write: joint_open {} → joint_pick { part_id, face_id?, key? } (a whole part, a face with its key, or an edge) → joint_set_params { type, value?, sense?, opposed? } → joint_commit {}. Fixed takes one pick and no second reference: joint_pick { part_id } alone suggests fixed; a face pick needs joint_set_params { type: "fixed" }.
126
+
127
+ Hardware. One part per unique fastener type, patterned to every place it goes: list_faces on the fastened part (cylindrical rows, filter by radius) gives each hole's center and axis in that part's frame (frame is "local"); compose with part_get_transform when the fastener does not share it. insert_pattern_points { points: [{ at, axis }, ...], up } on the fastener part places one instance per hole; insert_array3_d covers a grid. A bolt circle of holes is insert_polar_array { count, boltCircleRadius, axis, boreRadius, boreHeight } on the part being drilled (boreRadius greater than 0 subtracts the holes and does not copy the body; boreRadius 0 copies it; boltCircleRadius defaults to 0, on the axis). Do not record a bolt-circle hole pattern as a FEATURE-GAP.
128
+
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.`;
130
+
131
+ /** Topic name → one-line summary and the text. Order is the listing order. */
132
+ export const GUIDE_TOPICS = Object.freeze({
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 },
134
+ dialect: { summary: DIALECT_SUMMARY, text: renderDialectTopic() },
135
+ features: { summary: 'Marker blocks, feature ids, edit / delete / rollback / undo, script snippets, sketches', text: FEATURES },
136
+ selection: { summary: 'Face and edge keys, list_faces filters, single-use picks, no_selection, fillet edge sets', text: SELECTION },
137
+ paint: { summary: 'paint_open → paint_set_color → paint_part / paint_faces → paint_confirm; colours persist with the assembly', text: PAINT },
138
+ limits: { summary: 'The 30 s kernel budget, what is slow, worker restarts and stale status, result sizes, pairing errors', text: LIMITS },
139
+ camera: { summary: 'Which side each named view looks from, explicit poses, select_clear before a screenshot, screenshot to file', text: CAMERA },
140
+ assembly: { summary: 'Documents, create_part placement, insert by reference, part instances, joint_create as the default assembly path, hardware, git_save', text: ASSEMBLY },
141
+ });
142
+
143
+ /** The core topics, in listing order (the error topics are listed on one line after them). */
144
+ export const GUIDE_TOPIC_NAMES = Object.freeze(Object.keys(GUIDE_TOPICS));
145
+
146
+ /**
147
+ * errors.<code> topics, rendered from the hint table (errorHints.mjs) so a
148
+ * payload's hint and its topic come from one row. sweep_path has no code of
149
+ * its own (the bridge says insert_failed) and is listed with them.
150
+ */
151
+ export const ERROR_GUIDE_TOPICS = Object.freeze(Object.fromEntries([
152
+ ...ERROR_TOPIC_CODES.map((code) => [errorTopicName(code), errorTopic(code)]),
153
+ ...Object.entries(EXTRA_ERROR_TOPICS).map(([name, topic]) => [errorTopicName(name), topic]),
154
+ ]));
155
+
156
+ export const ERROR_GUIDE_TOPIC_NAMES = Object.freeze(Object.keys(ERROR_GUIDE_TOPICS));
157
+
158
+ /** Every topic the guide tool and the resources serve: core first, then errors.<code>. */
159
+ export const ALL_GUIDE_TOPICS = Object.freeze({ ...GUIDE_TOPICS, ...ERROR_GUIDE_TOPICS });
160
+ export const ALL_GUIDE_TOPIC_NAMES = Object.freeze(Object.keys(ALL_GUIDE_TOPICS));
161
+
162
+ /** MCP resource URI of a topic: the same text as guide { topic }. */
163
+ export const GUIDE_RESOURCE_SCHEME = 'surfcad://guide/';
164
+
165
+ /** @param {string} topic */
166
+ export function guideResourceUri(topic) {
167
+ return `${GUIDE_RESOURCE_SCHEME}${topic}`;
168
+ }
169
+
170
+ /** The topic a guide resource URI names, or null. */
171
+ export function topicFromResourceUri(uri) {
172
+ if (typeof uri !== 'string' || !uri.startsWith(GUIDE_RESOURCE_SCHEME)) return null;
173
+ const topic = uri.slice(GUIDE_RESOURCE_SCHEME.length);
174
+ return Object.prototype.hasOwnProperty.call(ALL_GUIDE_TOPICS, topic) ? topic : null;
175
+ }
176
+
177
+ /**
178
+ * resources/list rows: one per topic, versioned with the package so a host
179
+ * that pins or caches them can tell a newer server's text apart.
180
+ * @param {string} [version]
181
+ */
182
+ export function guideResourceList(version = loadPackageVersion()) {
183
+ return ALL_GUIDE_TOPIC_NAMES.map((topic) => ({
184
+ uri: guideResourceUri(topic),
185
+ name: topic,
186
+ title: topic.startsWith(ERROR_TOPIC_PREFIX) ? `SurfCAD error: ${topic.slice(ERROR_TOPIC_PREFIX.length)}` : `SurfCAD guide: ${topic}`,
187
+ description: ALL_GUIDE_TOPICS[topic].summary,
188
+ mimeType: 'text/plain',
189
+ _meta: { version },
190
+ }));
191
+ }
192
+
193
+ /**
194
+ * resources/read contents for one topic URI, or null for a URI this server
195
+ * does not serve.
196
+ * @param {string} uri
197
+ * @param {string} [version]
198
+ */
199
+ export function guideResourceContents(uri, version = loadPackageVersion()) {
200
+ const topic = topicFromResourceUri(uri);
201
+ if (!topic) return null;
202
+ return {
203
+ contents: [{
204
+ uri: guideResourceUri(topic),
205
+ mimeType: 'text/plain',
206
+ text: ALL_GUIDE_TOPICS[topic].text,
207
+ _meta: { version },
208
+ }],
209
+ };
210
+ }
211
+
212
+ /**
213
+ * The initialize `instructions`: the webhook line first (clients and
214
+ * goldens pin it), then a quick-start that fits under INSTRUCTIONS_MAX_BYTES
215
+ * and points at `guide start` for the rest.
216
+ */
217
+ export const SERVER_INSTRUCTIONS = [
218
+ PROMPT_SERVER_INSTRUCTIONS,
219
+ '',
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).`,
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.',
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).',
223
+ 'Verify: select_clear → camera_set { view } → screenshot { save_to: true }. right puts the camera on +X, front on -Y, top on +Z.',
224
+ 'Save only when the user asks: git_save { message } answers consent_pending until the user clicks Allow; retry the same call.',
225
+ 'Keep results small: tools default to return: "status" (no script echo; get_script reads it), list_faces { filter, page }, list_commands { group }.',
226
+ ].join('\n');
227
+
228
+ export function guideToolDefinition() {
229
+ return {
230
+ name: GUIDE_TOOL_NAME,
231
+ description: `SurfCAD agent guide, plain text. guide { topic } returns one topic; guide {} lists them. Read "start" before the first model call. Topics: ${GUIDE_TOPIC_NAMES.map((n) => `${n} (${GUIDE_TOPICS[n].summary})`).join('; ')}. Error recoveries: errors.<code> for the code an error payload carries (its see field names the topic), e.g. ${ERROR_GUIDE_TOPIC_NAMES.slice(0, 3).join(', ')}. The same texts are the ${GUIDE_RESOURCE_SCHEME}<topic> resources.`,
232
+ inputSchema: {
233
+ type: 'object',
234
+ additionalProperties: false,
235
+ properties: {
236
+ topic: {
237
+ type: 'string',
238
+ enum: [...ALL_GUIDE_TOPIC_NAMES],
239
+ description: 'Which topic to read. Omit to list the topics with one line each.',
240
+ },
241
+ },
242
+ },
243
+ };
244
+ }
245
+
246
+ function topicList() {
247
+ return [
248
+ `SurfCAD guide topics (guide { topic }; also resources ${GUIDE_RESOURCE_SCHEME}<topic>, surfcad-mcp ${loadPackageVersion()}):`,
249
+ ...GUIDE_TOPIC_NAMES.map((n) => `- ${n}: ${GUIDE_TOPICS[n].summary}`),
250
+ `- error recoveries, one per code an error payload names in see: ${ERROR_GUIDE_TOPIC_NAMES.join(', ')}`,
251
+ ].join('\n');
252
+ }
253
+
254
+ /** Second content item of a topic answer: where the same text lives as a resource. */
255
+ function resourcePointer(topic) {
256
+ return `Resource: ${guideResourceUri(topic)} (surfcad-mcp ${loadPackageVersion()}).`;
257
+ }
258
+
259
+ /**
260
+ * @param {Record<string, unknown>} args
261
+ * @returns {{ content: Array<{ type: 'text', text: string }>, isError: boolean }}
262
+ */
263
+ export function callGuideTool(args) {
264
+ const topic = args && typeof args.topic === 'string' ? args.topic.trim() : '';
265
+ if (!topic) {
266
+ return { content: [{ type: 'text', text: topicList() }], isError: false };
267
+ }
268
+ const entry = ALL_GUIDE_TOPICS[topic];
269
+ if (!entry) {
270
+ return {
271
+ content: [{
272
+ type: 'text',
273
+ text: JSON.stringify(withErrorHint({
274
+ code: 'unknown_topic',
275
+ message: `Unknown guide topic: ${topic}. Topics: ${GUIDE_TOPIC_NAMES.join(', ')}; error topics: ${ERROR_GUIDE_TOPIC_NAMES.join(', ')}.`,
276
+ topics: ALL_GUIDE_TOPIC_NAMES,
277
+ })),
278
+ }],
279
+ isError: true,
280
+ };
281
+ }
282
+ return {
283
+ content: [
284
+ { type: 'text', text: entry.text },
285
+ { type: 'text', text: resourcePointer(topic) },
286
+ ],
287
+ isError: false,
288
+ };
289
+ }
@@ -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 ?? PROMPT_IDLE_MS;
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,12 @@ 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;
150
+ /** @type {'idle' | 'typing' | 'working'} What the tab shows: the pane open with dots, or the spinner. */
151
+ let agentState = 'idle';
144
152
  let promptEpoch = 0;
145
153
  let workedEpoch = 0;
146
154
  let lastAcceptedAt = -Infinity;
@@ -150,6 +158,15 @@ export function createPromptSession(options) {
150
158
  let idleTimer = null;
151
159
  let chain = Promise.resolve();
152
160
  let life = 0;
161
+ /** read_messages { wait_ms } long-poll: resolved when the queue gains an item. */
162
+ /** @type {Array<() => void>} */
163
+ let waiters = [];
164
+ function wakeReaders() {
165
+ if (!waiters.length) return;
166
+ const list = waiters;
167
+ waiters = [];
168
+ for (const resolve of list) resolve();
169
+ }
153
170
 
154
171
  function emit(payload) {
155
172
  try {
@@ -167,31 +184,85 @@ export function createPromptSession(options) {
167
184
 
168
185
  function armIdle() {
169
186
  clearIdle();
187
+ if (!working || stalled || workHolds > 0) return;
170
188
  idleTimer = setTimer(() => {
171
189
  idleTimer = null;
172
- if (working) emitStatus(false, lastId, false);
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);
173
195
  }, idleMs);
174
196
  }
175
197
 
176
198
  /**
177
- * @param {boolean} next
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
+
231
+ /**
232
+ * Send the agent state to the tab. `working` stays on the message for tabs
233
+ * that predate `state`: true for typing and working, false for idle.
234
+ * @param {'idle' | 'typing' | 'working'} state
178
235
  * @param {string | null | undefined} id
179
236
  * @param {boolean} force
237
+ * @param {string} [label]
180
238
  */
181
- function emitStatus(next, id, force) {
182
- if (!force && working === next) {
239
+ function emitState(state, id, force, label) {
240
+ const next = state !== 'idle';
241
+ if (!force && agentState === state && !stalled) {
183
242
  if (next) armIdle();
184
243
  return true;
185
244
  }
245
+ stalled = false;
186
246
  working = next;
187
- const msg = { type: PAIR_MSG.AGENT_STATUS, v: 1, working: next };
247
+ agentState = state;
248
+ const msg = { type: PAIR_MSG.AGENT_STATUS, v: 1, working: next, state };
188
249
  if (typeof id === 'string' && id) msg.id = id;
250
+ if (typeof label === 'string' && label) msg.label = label.slice(0, 120);
189
251
  const sent = emit(msg);
190
252
  if (next) armIdle();
191
253
  else clearIdle();
192
254
  return sent;
193
255
  }
194
256
 
257
+ /**
258
+ * @param {boolean} next
259
+ * @param {string | null | undefined} id
260
+ * @param {boolean} force
261
+ */
262
+ function emitStatus(next, id, force) {
263
+ return emitState(next ? 'working' : 'idle', id, force);
264
+ }
265
+
195
266
  function ack(id, delivery, error) {
196
267
  const msg = { type: PAIR_MSG.AGENT_PROMPT_ACK, id, delivery };
197
268
  if (error) msg.error = error;
@@ -278,9 +349,37 @@ export function createPromptSession(options) {
278
349
  dropped.push(queue.splice(idx, 1)[0]);
279
350
  }
280
351
  queue.push({ kind: 'prompt', ...prompt });
352
+ wakeReaders();
281
353
  return dropped;
282
354
  }
283
355
 
356
+ /**
357
+ * Long-poll for `read_messages { wait_ms }`: resolves true as soon as the
358
+ * queue has an item (a prompt or a cancel notice), false after `ms` with the
359
+ * queue still empty. Never holds a timer past the wait.
360
+ * @param {number} ms
361
+ * @returns {Promise<boolean>}
362
+ */
363
+ function waitForMessage(ms) {
364
+ if (queue.length > 0) return Promise.resolve(true);
365
+ const wait = Math.max(0, Number(ms) || 0);
366
+ if (wait === 0) return Promise.resolve(false);
367
+ return new Promise((resolve) => {
368
+ let done = false;
369
+ let timer = null;
370
+ const settle = (value) => {
371
+ if (done) return;
372
+ done = true;
373
+ clearTimer(timer);
374
+ waiters = waiters.filter((w) => w !== wake);
375
+ resolve(value);
376
+ };
377
+ const wake = () => settle(true);
378
+ waiters.push(wake);
379
+ timer = setTimer(() => settle(false), wait);
380
+ });
381
+ }
382
+
284
383
  /**
285
384
  * @param {string} id
286
385
  * @param {number} epoch
@@ -293,6 +392,7 @@ export function createPromptSession(options) {
293
392
  }
294
393
  if (epoch !== life) return;
295
394
  queue.push({ kind: 'cancel', id });
395
+ wakeReaders();
296
396
  }
297
397
 
298
398
  /**
@@ -458,6 +558,7 @@ export function createPromptSession(options) {
458
558
  ? { data: item.screenshot.data, mimeType: 'image/png' }
459
559
  : null);
460
560
  }
561
+ noteActivity();
461
562
  return { messages, images };
462
563
  }
463
564
 
@@ -493,17 +594,31 @@ export function createPromptSession(options) {
493
594
  queue = queue.filter((item) => item.kind === 'cancel' || item.id !== inReplyTo);
494
595
  states.set(inReplyTo, 'replied');
495
596
  emitStatus(false, inReplyTo, true);
496
- } else if (working) armIdle();
597
+ } else {
598
+ // A streamed reply means the agent is writing: the tab reopens the chat.
599
+ workedEpoch = promptEpoch;
600
+ emitState('typing', inReplyTo, false);
601
+ }
497
602
  return { id: inReplyTo, final: isFinal };
498
603
  }
499
604
 
500
605
  /**
501
- * @param {{ working?: unknown, id?: unknown }} args
606
+ * `state` (typing | working | idle) or the legacy `working` boolean; one is
607
+ * required. `label` is optional text for the tab.
608
+ * @param {{ working?: unknown, state?: unknown, label?: unknown, id?: unknown }} args
502
609
  */
503
610
  function setStatus(args) {
504
- if (typeof args?.working !== 'boolean') {
505
- throw Object.assign(new Error('working must be a boolean'), { code: 'bad_args' });
611
+ const hasState = typeof args?.state === 'string';
612
+ if (hasState && !['typing', 'working', 'idle'].includes(args.state)) {
613
+ throw Object.assign(new Error('state must be typing, working, or idle'), { code: 'bad_args' });
614
+ }
615
+ if (!hasState && typeof args?.working !== 'boolean') {
616
+ throw Object.assign(new Error('state (typing | working | idle) or working (boolean) is required'), { code: 'bad_args' });
506
617
  }
618
+ if (args.label != null && (typeof args.label !== 'string' || args.label.length > 120)) {
619
+ throw Object.assign(new Error('label must be a string of at most 120 characters'), { code: 'bad_args' });
620
+ }
621
+ const state = hasState ? args.state : (args.working ? 'working' : 'idle');
507
622
  let id;
508
623
  if (args.id != null) {
509
624
  if (typeof args.id !== 'string' || !args.id || args.id.length > 80) {
@@ -516,23 +631,35 @@ export function createPromptSession(options) {
516
631
  return { ok: false, error: 'cancelled' };
517
632
  }
518
633
  workedEpoch = promptEpoch;
519
- const sent = emitStatus(args.working, id || lastId, true);
634
+ const sent = emitState(state, id || lastId, true, typeof args.label === 'string' ? args.label : undefined);
520
635
  if (!sent) throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
521
- return { working: args.working };
636
+ return { working: state !== 'idle', state };
522
637
  }
523
638
 
524
- function noteToolCall() {
639
+ /**
640
+ * A tool call after a prompt. A call that changes the model (`mutates`)
641
+ * switches the tab to working on its own, even when the agent never set
642
+ * a state; a read-only call only keeps the current state alive.
643
+ * @param {{ mutates?: boolean }} [info]
644
+ */
645
+ function noteToolCall(info = {}) {
525
646
  if (lastId && states.get(lastId) === 'cancelled') {
526
647
  if (working) emitStatus(false, lastId, true);
527
648
  return;
528
649
  }
650
+ const mutates = info?.mutates === true;
651
+ if (mutates && agentState !== 'working') {
652
+ workedEpoch = promptEpoch;
653
+ emitState('working', lastId, false);
654
+ return;
655
+ }
529
656
  if (promptEpoch > workedEpoch) {
530
657
  workedEpoch = promptEpoch;
531
658
  if (!working) emitStatus(true, lastId, false);
532
- else armIdle();
659
+ else noteActivity();
533
660
  return;
534
661
  }
535
- if (working) armIdle();
662
+ if (working) noteActivity();
536
663
  }
537
664
 
538
665
  /**
@@ -580,6 +707,9 @@ export function createPromptSession(options) {
580
707
  webhook = null;
581
708
  webhookBearer = null;
582
709
  working = false;
710
+ stalled = false;
711
+ workHolds = 0;
712
+ agentState = 'idle';
583
713
  promptEpoch = 0;
584
714
  workedEpoch = 0;
585
715
  lastAcceptedAt = -Infinity;
@@ -591,9 +721,11 @@ export function createPromptSession(options) {
591
721
  acceptPrompt,
592
722
  cancel,
593
723
  readMessages,
724
+ waitForMessage,
594
725
  reply,
595
726
  setStatus,
596
727
  noteToolCall,
728
+ holdWork,
597
729
  registerWebhook,
598
730
  unregisterWebhook,
599
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;