surfcad-mcp 0.2.4 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -3
- package/data/commands.json +11252 -4296
- package/data/helpers.json +1765 -0
- package/package.json +1 -1
- package/src/helpers.mjs +209 -0
- package/src/prompt/buildGuidance.mjs +21 -0
- package/src/prompt/errorHints.mjs +288 -0
- package/src/prompt/guide.mjs +285 -0
- package/src/prompt/promptSession.mjs +94 -11
- package/src/prompt/promptTools.mjs +31 -3
- package/src/relay.mjs +9 -3
- package/src/server.mjs +107 -19
package/package.json
CHANGED
package/src/helpers.mjs
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The helper registry inside the package: data/helpers.json is a copy of
|
|
3
|
+
* src/lib/surfcad/catalog/helpers.json (every HELPER_FUNCTIONS key with its
|
|
4
|
+
* signature, params, description, doc and examples), refreshed by
|
|
5
|
+
* `npm run export:agent` and pinned by a freshness test. `guide dialect`
|
|
6
|
+
* and the `list_helpers` tool are rendered from it at load time, so a
|
|
7
|
+
* helper change updates both in the same commit as the registry.
|
|
8
|
+
*/
|
|
9
|
+
import { readFileSync } from 'node:fs';
|
|
10
|
+
import { dirname, join } from 'node:path';
|
|
11
|
+
import { fileURLToPath } from 'node:url';
|
|
12
|
+
|
|
13
|
+
const PKG_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
|
|
14
|
+
export const HELPERS_JSON_REL = 'data/helpers.json';
|
|
15
|
+
|
|
16
|
+
export const LIST_HELPERS_TOOL_NAME = 'list_helpers';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Ribbon-order groups for the dialect topic and the list_helpers filter.
|
|
20
|
+
* A helper the map does not name lands in "other" (the test flags it).
|
|
21
|
+
*/
|
|
22
|
+
export const HELPER_GROUPS = Object.freeze({
|
|
23
|
+
blocks: ['roundedBox', 'tube', 'rectTube', 'hexPrism', 'sheetMetalSolid'],
|
|
24
|
+
shapes: ['makeCrossSection', 'solveContour', 'profileCircle', 'profileRectangle', 'profilePolygon', 'makeExtrude', 'makeRevolve', 'makeLoft', 'loft', 'sweep', 'sweepPoints', 'makeSweepPath', 'rotateContour', 'offsetPlaneFrame'],
|
|
25
|
+
build: ['cut', 'hollow', 'shell', 'hole', 'holeSpan', 'cboreHole', 'cskHole', 'clearanceHole', 'tapDrillHole', 'holePattern', 'holesOnContour', 'booleanBodies', 'externalBody', 'addDraft', 'draftFaces', 'moveFace', 'deleteFace'],
|
|
26
|
+
polish: ['filletEdges', 'chamferEdges', 'filletAlongPath', 'convexEdges', 'concaveEdges', 'signedFeatureEdges', 'edge', 'edgesBetween', 'boundaryEdges'],
|
|
27
|
+
place: ['move', 'rotateAbout', 'center', 'align', 'mirror', 'array3D', 'polarArray', 'patternOnPoints', 'getDimensions'],
|
|
28
|
+
faces: ['faceNames', 'facesNamed', 'edgesOf', 'surfaceOf', 'facesByNormal', 'planarFaceAt', 'edgesByOrientation', 'workplaneFromFace', 'placeInFrame', 'transformByFrame', 'placeOnFace'],
|
|
29
|
+
fasteners: ['fastenerClearanceDia', 'fastenerTapDrillDia', 'fastenerMajorDia', 'listFastenerSizes', 'resolveFastenerSize'],
|
|
30
|
+
vectors: ['vecAdd', 'vecSub', 'vecMul', 'vecDot', 'vecCross', 'vecNorm', 'vecNormalize', 'sumSqDist'],
|
|
31
|
+
legacy: ['getScaleRatio'],
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
const GROUP_TITLES = Object.freeze({
|
|
35
|
+
blocks: 'Blocks (primitives; Manifold.cube / cylinder / sphere are the kernel\'s own)',
|
|
36
|
+
shapes: 'Shapes from contours (sketch profiles, extrude, revolve, loft, sweep)',
|
|
37
|
+
build: 'Build (cuts, holes, shells, booleans, draft, face edits)',
|
|
38
|
+
polish: 'Polish (edges: fillet, chamfer, edge sets)',
|
|
39
|
+
place: 'Place and pattern',
|
|
40
|
+
faces: 'Faces, names and frames (selection and workplanes)',
|
|
41
|
+
fasteners: 'Fastener tables',
|
|
42
|
+
vectors: 'Vectors',
|
|
43
|
+
legacy: 'Legacy',
|
|
44
|
+
other: 'Other',
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
export const HELPER_GROUP_NAMES = Object.freeze([...Object.keys(HELPER_GROUPS), 'other']);
|
|
48
|
+
|
|
49
|
+
const GROUP_OF = new Map();
|
|
50
|
+
for (const [group, names] of Object.entries(HELPER_GROUPS)) for (const name of names) GROUP_OF.set(name, group);
|
|
51
|
+
|
|
52
|
+
/** @param {string} name */
|
|
53
|
+
export function helperGroup(name) {
|
|
54
|
+
return GROUP_OF.get(name) || 'other';
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* @returns {{ generatedFrom: string, count: number, helpers: Array<{ name: string, signature: string, params: Array<{ name: string, text: string, default?: string }>, description: string, doc: string, examples: string[] }> }}
|
|
59
|
+
*/
|
|
60
|
+
export function loadHelpersCatalog(path = join(PKG_ROOT, HELPERS_JSON_REL)) {
|
|
61
|
+
const doc = JSON.parse(readFileSync(path, 'utf8'));
|
|
62
|
+
if (!doc || typeof doc !== 'object' || !Array.isArray(doc.helpers)) {
|
|
63
|
+
throw new Error('Invalid helpers catalog');
|
|
64
|
+
}
|
|
65
|
+
return doc;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const SHORT_MAX = 110;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* One short line for a helper: the first sentence of its description with
|
|
72
|
+
* a leading "name(...) —" (the signature again) dropped.
|
|
73
|
+
* @param {{ name: string, description?: string, doc?: string }} helper
|
|
74
|
+
*/
|
|
75
|
+
export function shortDescription(helper) {
|
|
76
|
+
let text = String(helper.description || helper.doc || '').replace(/\s+/g, ' ').trim();
|
|
77
|
+
text = text.replace(new RegExp(`^${helper.name}\\([^)]*\\)\\s*(→|—|-|:)\\s*`), '');
|
|
78
|
+
const first = text.split(/(?<=[.!?])\s+(?=[A-Z`(])/)[0] || text;
|
|
79
|
+
text = first.replace(/[.\s]+$/, '');
|
|
80
|
+
if (text.length > SHORT_MAX) text = `${text.slice(0, SHORT_MAX - 1).trimEnd()}…`;
|
|
81
|
+
return text;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const DIALECT_INTRO = `The SurfCAD dialect. A part's script is plain JavaScript over the Manifold kernel plus the helpers below, which the runtime passes in as function parameters (so their names are reserved: never declare them with const, let, class or function). The script sets and returns part; numbers are mm; insert_* tools write one marker block each (see guide features) and their descriptions quote the code they write with default arguments. list_helpers { names: [...] } returns a helper's full doc and examples; list_helpers { group } or { match } lists a slice.`;
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The dialect topic text, rendered from the registry: one signature line per
|
|
88
|
+
* helper, in ribbon-order groups.
|
|
89
|
+
* @param {ReturnType<typeof loadHelpersCatalog>} [catalog]
|
|
90
|
+
*/
|
|
91
|
+
export function renderDialectTopic(catalog = loadHelpersCatalog()) {
|
|
92
|
+
const byGroup = new Map(HELPER_GROUP_NAMES.map((g) => [g, []]));
|
|
93
|
+
for (const helper of catalog.helpers) byGroup.get(helperGroup(helper.name)).push(helper);
|
|
94
|
+
// Within a group, the order of HELPER_GROUPS (basic before derived), not registry order.
|
|
95
|
+
for (const [group, rows] of byGroup) {
|
|
96
|
+
const order = HELPER_GROUPS[group] || [];
|
|
97
|
+
rows.sort((x, y) => order.indexOf(x.name) - order.indexOf(y.name));
|
|
98
|
+
}
|
|
99
|
+
const sections = [];
|
|
100
|
+
for (const group of HELPER_GROUP_NAMES) {
|
|
101
|
+
const rows = byGroup.get(group);
|
|
102
|
+
if (!rows.length) continue;
|
|
103
|
+
sections.push([
|
|
104
|
+
`${GROUP_TITLES[group]}:`,
|
|
105
|
+
...rows.map((h) => ` ${h.signature} — ${shortDescription(h)}`),
|
|
106
|
+
].join('\n'));
|
|
107
|
+
}
|
|
108
|
+
return `${DIALECT_INTRO}\n\n${sections.join('\n\n')}\n\nGenerated from ${catalog.generatedFrom} (${catalog.count} helpers).`;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export const DIALECT_SUMMARY = 'Every script helper by signature, in ribbon-order groups, rendered from the helper registry; list_helpers has the full docs';
|
|
112
|
+
|
|
113
|
+
export function listHelpersToolDefinition() {
|
|
114
|
+
return {
|
|
115
|
+
name: LIST_HELPERS_TOOL_NAME,
|
|
116
|
+
description: `The script helper registry as JSON, no pairing needed: name, group, signature, params (with defaults) and a one-line description per helper; with names, the full doc and examples too. list_helpers {} is every helper (compact); { names: ["tube", "filletEdges"] } those with docs (unknown names in missing); { group } one of ${HELPER_GROUP_NAMES.join(', ')}; { match: "hole" } name or description substring; page { offset, limit } slices. The same registry renders guide { topic: "dialect" } and the insert_* descriptions.`,
|
|
117
|
+
inputSchema: {
|
|
118
|
+
type: 'object',
|
|
119
|
+
additionalProperties: false,
|
|
120
|
+
properties: {
|
|
121
|
+
names: { type: 'array', items: { type: 'string' }, description: 'Only these helpers, with full doc and examples. Unknown names come back in missing.' },
|
|
122
|
+
group: { type: 'string', enum: [...HELPER_GROUP_NAMES], description: 'Only the helpers in this group.' },
|
|
123
|
+
match: { type: 'string', description: 'Case-insensitive substring of the name or description.' },
|
|
124
|
+
page: {
|
|
125
|
+
type: 'object',
|
|
126
|
+
additionalProperties: false,
|
|
127
|
+
properties: {
|
|
128
|
+
offset: { type: 'integer', minimum: 0 },
|
|
129
|
+
limit: { type: 'integer', minimum: 1, maximum: 200 },
|
|
130
|
+
},
|
|
131
|
+
description: 'One slice of the filtered rows; the result carries total and returned.',
|
|
132
|
+
},
|
|
133
|
+
},
|
|
134
|
+
},
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function compactRow(helper) {
|
|
139
|
+
return {
|
|
140
|
+
name: helper.name,
|
|
141
|
+
group: helperGroup(helper.name),
|
|
142
|
+
signature: helper.signature,
|
|
143
|
+
params: helper.params,
|
|
144
|
+
description: shortDescription(helper),
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function fullRow(helper) {
|
|
149
|
+
return { ...compactRow(helper), doc: helper.doc, examples: helper.examples };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* @param {Record<string, unknown>} args
|
|
154
|
+
* @param {ReturnType<typeof loadHelpersCatalog>} [catalog]
|
|
155
|
+
* @returns {{ content: Array<{ type: 'text', text: string }>, isError: boolean }}
|
|
156
|
+
*/
|
|
157
|
+
export function callListHelpersTool(args, catalog = loadHelpersCatalog()) {
|
|
158
|
+
const bad = (message) => ({
|
|
159
|
+
content: [{ type: 'text', text: JSON.stringify({ code: 'bad_args', message }) }],
|
|
160
|
+
isError: true,
|
|
161
|
+
});
|
|
162
|
+
const src = args && typeof args === 'object' ? args : {};
|
|
163
|
+
if (src.names != null && (!Array.isArray(src.names) || !src.names.every((n) => typeof n === 'string'))) {
|
|
164
|
+
return bad('list_helpers names must be an array of helper names');
|
|
165
|
+
}
|
|
166
|
+
if (src.group != null && !HELPER_GROUP_NAMES.includes(src.group)) {
|
|
167
|
+
return bad(`list_helpers group must be one of ${HELPER_GROUP_NAMES.join(', ')}`);
|
|
168
|
+
}
|
|
169
|
+
if (src.match != null && typeof src.match !== 'string') return bad('list_helpers match must be a string');
|
|
170
|
+
const page = src.page;
|
|
171
|
+
if (page != null && (typeof page !== 'object' || Array.isArray(page)
|
|
172
|
+
|| (page.offset != null && !(Number.isInteger(page.offset) && page.offset >= 0))
|
|
173
|
+
|| (page.limit != null && !(Number.isInteger(page.limit) && page.limit >= 1 && page.limit <= 200)))) {
|
|
174
|
+
return bad('list_helpers page must be { offset?: integer >= 0, limit?: 1..200 }');
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const wanted = Array.isArray(src.names) ? new Set(src.names) : null;
|
|
178
|
+
const match = typeof src.match === 'string' && src.match.trim() ? src.match.trim().toLowerCase() : null;
|
|
179
|
+
let rows = catalog.helpers;
|
|
180
|
+
if (wanted) rows = rows.filter((h) => wanted.has(h.name));
|
|
181
|
+
if (src.group) rows = rows.filter((h) => helperGroup(h.name) === src.group);
|
|
182
|
+
if (match) rows = rows.filter((h) => h.name.toLowerCase().includes(match) || String(h.description || '').toLowerCase().includes(match));
|
|
183
|
+
const total = rows.length;
|
|
184
|
+
const offset = page?.offset ?? 0;
|
|
185
|
+
const limit = page?.limit ?? total;
|
|
186
|
+
const slice = page ? rows.slice(offset, offset + limit) : rows;
|
|
187
|
+
const groups = {};
|
|
188
|
+
for (const h of catalog.helpers) {
|
|
189
|
+
const g = helperGroup(h.name);
|
|
190
|
+
groups[g] = (groups[g] || 0) + 1;
|
|
191
|
+
}
|
|
192
|
+
const result = {
|
|
193
|
+
helpers: slice.map((h) => (wanted ? fullRow(h) : compactRow(h))),
|
|
194
|
+
total,
|
|
195
|
+
returned: slice.length,
|
|
196
|
+
groups,
|
|
197
|
+
};
|
|
198
|
+
if (page) {
|
|
199
|
+
result.offset = offset;
|
|
200
|
+
result.limit = limit;
|
|
201
|
+
}
|
|
202
|
+
if (wanted) {
|
|
203
|
+
const found = new Set(slice.map((h) => h.name));
|
|
204
|
+
const missing = [...wanted].filter((n) => !found.has(n));
|
|
205
|
+
if (missing.length) result.missing = missing;
|
|
206
|
+
}
|
|
207
|
+
if (src.group) result.group = src.group;
|
|
208
|
+
return { content: [{ type: 'text', text: JSON.stringify(result) }], isError: false };
|
|
209
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copy of src/agent/buildGuidance.js for the self-contained package.
|
|
3
|
+
* test/buildGuidanceFreshness.test.mjs fails when the two differ.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export const FEATURE_GAP_PREFIX = '// FEATURE-GAP:';
|
|
7
|
+
|
|
8
|
+
/** One line for the tools that create parts and insert features. */
|
|
9
|
+
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.';
|
|
10
|
+
|
|
11
|
+
/** The full guidance, served by the MCP `guide` tool's `start` topic. */
|
|
12
|
+
export const BUILD_GUIDANCE = [
|
|
13
|
+
'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.',
|
|
15
|
+
'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
|
+
'3. Polish. insert_fillet_edges, insert_chamfer_edges, insert_move_face, insert_delete_face.',
|
|
17
|
+
'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) for repeats and hardware, then insert_move, insert_rotate, insert_center, insert_align, insert_mirror, and part_set_transform or joints for final positions.',
|
|
18
|
+
'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 } (the Script button in Build): 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.',
|
|
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 the center and axis of each hole; pass them to insert_pattern_points { points: [{ at, axis }, …], up } on the fastener part (insert_array3_d or insert_polar_array for a regular grid or bolt circle), and run it 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
|
+
].join('\n');
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One table from error code to recovery. Every error payload the MCP server
|
|
3
|
+
* hands an agent gets `hint` (one sentence, what to do next) from here, and
|
|
4
|
+
* the codes with a longer story are also `guide { topic: "errors.<code>" }`
|
|
5
|
+
* topics and `surfcad://guide/errors.<code>` resources, rendered from the
|
|
6
|
+
* same rows so the two cannot drift.
|
|
7
|
+
*
|
|
8
|
+
* The bridge (src/agent) sends `code`, `message`, `details`; the hint is
|
|
9
|
+
* added on this side so a tab that predates a hint still gets one. A hint
|
|
10
|
+
* the bridge sent itself wins.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const SELECTION_GUIDE = 'use_selection reads the viewport pick once. Every successful rebuild (each insert_*, set_script, undo) clears the picks because they index the mesh that was replaced, so the second insert in a row finds nothing and answers no_selection without writing. Pick again before each insert that uses the selection: list_faces { filter } → select_faces { keys } (or { names }) → insert_* { use_selection: true }. Omit use_selection to take the helper default instead (the +Z top face for holes, every convex edge for fillet and chamfer). Every insert result carries usedSelection: true | false.';
|
|
14
|
+
|
|
15
|
+
const SWEEP_GUIDE = 'insert_sweep_path and insert_make_sweep build the path from selected edges: list_feature_edges, select_edges { keys: ["e3", "e4"] } (a connected tangent chain), then insert with use_selection: true. With no edge to follow, author the path from points in one feature block instead: insert_code_snippet { gap: "sweep along points", why: "no model edge follows the path", script } where the script calls makeSweepPath / sweepPoints with your [x, y, z] mm points and sets part. guide { topic: "features" } shows the block shape.';
|
|
16
|
+
|
|
17
|
+
const TIMEOUT_GUIDE = 'One marked feature block ran past the 30 s kernel budget. The geometry worker was replaced and the part was rebuilt without that block, so the other features are on screen and the part keeps working; the errors row names the block (featureId, featureLabel, elapsedMs, budgetMs). Make it cheaper, then edit_feature / confirm_feature it, or delete_feature / undo: fewer edges (the picked face\'s edges by name or an explicit list instead of every convex edge), a smaller radius, lower segment counts, or split the body. Do not retry the same block unchanged and do not ask for a reload.';
|
|
18
|
+
|
|
19
|
+
const CRASH_GUIDE = 'The whole run was treated as a crash (reason timeout, out_of_memory or wasm_abort): the worker was killed and replaced, errors has one geometry_worker_crashed row with workerRestarted: true, and other parts keep building. Do not retry the same script: simplify the part (smaller edge sets, lower segments, fewer boolean bodies), then run again. After undo the restored script is re-run; if status.stale is true the numbers are the previous run\'s, call run {} and read status.';
|
|
20
|
+
|
|
21
|
+
const NAMES_GUIDE = 'Faces and edges are addressed by the keys and names list_faces / list_feature_edges return for the current mesh. A key from before a rebuild, a display label, or a guess answers unknown_face / unknown_edge; a key that matches several patches answers ambiguous_face / ambiguous_edge with details.candidates. List again (filter and page the list on a detailed part), then select_faces { keys } or { names } with a row from that answer. Faces a helper built carry a name (feature.role) that survives upstream edits; prefer names when you will edit the part again.';
|
|
22
|
+
|
|
23
|
+
const PAIRING_GUIDE = 'A bridge call before pair is not_paired: call pair { code } with the 6-character code from SurfCAD → Local agent → Show pairing code (or set SURFCAD_PAIRING_CODE). pair_pending means the user has not clicked Allow yet; wait and retry the same call. pair_rejected means they clicked Deny; ask before trying again. pairing_lost means the tab or relay dropped and the server re-pairs on its own: retry in a few seconds, do not ask for a new code. Webhook errors (bad_webhook_url) need a public https URL; a local session polls read_messages { wait_ms: 25000 } instead.';
|
|
24
|
+
|
|
25
|
+
const CONTOUR_GUIDE = 'open_feature on an extrude, revolve, loft or sweep that owns a contour reopens its sketch; edit_feature then patches the sketch (points, radius, width / height, polygon_preset, or tool) and confirm_feature saves the sketch and the feature in one step. no_feature_edit means nothing is open: open_feature { id } first (feature_tree {} lists ids), then edit, then confirm. sketch_cancel leaves a reopened sketch without writing.';
|
|
26
|
+
|
|
27
|
+
const CONSENT_GUIDE = 'Vault writes on a real GitHub repository need the user\'s Allow once per session. consent_pending: the dialog is up, nothing was written; ask the user to click Allow, then retry the same call after details.retry_after_ms. real_repo_blocked: this session cannot get consent (headless, or the user denied); tell the user and stop, do not loop. confirm_required: a destructive change (delete_feature on the base feature, delete_part scope repo, git_force_overwrite, ...) was called without confirm: true; nothing changed; ask the user, only then retry with confirm: true.';
|
|
28
|
+
|
|
29
|
+
const BUSY_GUIDE = 'Another mode owns the canvas (a sketch, paint, joint, sheet, measure or pick card) or the viewport is still switching. details.viewport names the mode and details.hint says what to call instead when there is one. Close or finish that mode (sketch_commit / sketch_cancel, paint_confirm / paint_cancel, joint_commit, pick_done / pick_cancel) and call again; not_ready from paint_open is retryable after a moment.';
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* code → { hint, guide? }. `hint` is one sentence that fits in a payload;
|
|
33
|
+
* `guide` is the errors.<code> topic text (only where the story needs more
|
|
34
|
+
* than a sentence). Keep hints concrete: the next call to make.
|
|
35
|
+
* @type {Readonly<Record<string, { hint: string, guide?: string }>>}
|
|
36
|
+
*/
|
|
37
|
+
export const ERROR_HINTS = Object.freeze({
|
|
38
|
+
// Selection and names
|
|
39
|
+
no_selection: { hint: 'Picks clear after every rebuild: list_faces { filter } → select_faces { keys } (or { names }), then insert again with use_selection: true, or omit use_selection for the helper default.', guide: SELECTION_GUIDE },
|
|
40
|
+
unknown_face: { hint: 'The key or name is not on the current mesh: list_faces { filter, page } again and pass a key or name from that answer.', guide: NAMES_GUIDE },
|
|
41
|
+
unknown_edge: { hint: 'The key or pair is not on the current mesh: list_feature_edges (grouped ids) or list_edges again and pass a key from that answer.', guide: NAMES_GUIDE },
|
|
42
|
+
ambiguous_face: { hint: 'The key matched several patches: pick one of details.candidates (list_faces keys) and select it by that key, or by name.', guide: NAMES_GUIDE },
|
|
43
|
+
ambiguous_edge: { hint: 'The face-key pair matched several edges: use a grouped edge id from list_feature_edges instead.', guide: NAMES_GUIDE },
|
|
44
|
+
ambiguous: { hint: 'More than one entity matched: pass an id or key from the matching list_* call.' },
|
|
45
|
+
unknown_entity: { hint: 'The sketch entity id is not in the open contour: list_sketch_entities {} and use an id from it (p0, e0, a0, ...).' },
|
|
46
|
+
no_body: { hint: 'Name the body: body_index or at from list_bodies {}, face or face_id from list_faces, or select a face and pass use_selection: true.' },
|
|
47
|
+
no_mesh: { hint: 'No solid is shown yet: insert a block (insert_cube, insert_cylinder, ...) or run {} the part, then call again.' },
|
|
48
|
+
not_picked: { hint: 'pick_next { remove: true } named keys that are not picked: pick_next with no remove to see the live picks, or pick_clear {}.' },
|
|
49
|
+
empty_pick: { hint: 'The card needs at least one pick: pick_next { keys } before pick_done, or pick_cancel {}.' },
|
|
50
|
+
pick_count: { hint: 'Fewer picks than the card\'s minimum: pick_next more keys, then pick_done again.' },
|
|
51
|
+
pick_limit: { hint: 'The card takes at most max picks: pick_next { remove: true } some, or pick_begin again with fewer keys.' },
|
|
52
|
+
pick_rejected: { hint: 'The card kept fewer picks than sent (not on the solid or wrong kind): re-list the faces or edges and pick again.' },
|
|
53
|
+
pick_timeout: { hint: 'The pick session expired or the viewport did not respond: pick_begin again and finish within timeout_ms.' },
|
|
54
|
+
pick_closed: { hint: 'The card closed or the Face / Edge mode changed: open the card again (open_feature or the insert) and pick_begin.' },
|
|
55
|
+
pick_open: { hint: 'A pick session is live (details): pick_done or pick_cancel it, or pass replace: true to pick_begin.' },
|
|
56
|
+
no_pick_session: { hint: 'No pick session: pick_begin first, or use select_faces / select_edges with use_selection: true instead.' },
|
|
57
|
+
picker_busy: { hint: 'Another mode owns the canvas (details.viewport): finish or cancel it, then call again; details.hint names the call when there is one.', guide: BUSY_GUIDE },
|
|
58
|
+
wrong_kind: { hint: 'The card picks details.kind (faces or edges): pass keys of that kind.' },
|
|
59
|
+
bad_pick: { hint: 'The key is not a grouped edge id, face id, face key or { faceKeyA, faceKeyB } pair: copy one from list_faces / list_feature_edges.' },
|
|
60
|
+
pick_failed: { hint: 'The viewport could not apply the pick: re-list and pick again, or select_clear {} and start over.' },
|
|
61
|
+
no_card: { hint: 'Nothing to accept on a bare selection: call the insert with use_selection: true instead of pick_done { accept: true }.' },
|
|
62
|
+
accept_refused: { hint: 'The card\'s Accept gate refused (message is its toast): fix what it names, then pick_done again; the session stays open.' },
|
|
63
|
+
// Features and script
|
|
64
|
+
insert_failed: { hint: 'Read message: it names the missing body, face, edge or profile; insert that first (a block for an empty part, a sketch for extrude / revolve), then insert again.' },
|
|
65
|
+
feature_failed: { hint: 'The kernel rejected this block (detail says why): edit_feature its params or delete_feature it; a script fix goes through set_script with the markers kept.' },
|
|
66
|
+
feature_timeout: { hint: 'This block ran past the 30 s budget and the part was rebuilt without it: make it cheaper (fewer edges, smaller radius, lower segments), then edit or delete it; do not retry it unchanged.', guide: TIMEOUT_GUIDE },
|
|
67
|
+
geometry_worker_crashed: { hint: 'The worker was replaced and other parts keep building: simplify the part (smaller edge sets, lower segments, fewer bodies) and run again; do not retry the same script or ask for a reload.', guide: CRASH_GUIDE },
|
|
68
|
+
build_failed: { hint: 'The script did not run: read errors {} for the feature rows, fix that block with edit_feature or set_script, then run {}.' },
|
|
69
|
+
run_failed: { hint: 'The run did not complete: read status {} (stale: true means call run {} again) and errors {}.' },
|
|
70
|
+
timeout: { hint: 'The tab did not answer in time: call status {} to see the current run, then retry once; a 30 s kernel budget applies per run.' },
|
|
71
|
+
unknown_feature: { hint: 'The id is not in the active part\'s strip: feature_tree {} lists ids and indexes; set_active_part if the block is on another part.' },
|
|
72
|
+
bad_index: { hint: 'The index is out of range: feature_tree {} gives the current count; indexes start at 0 in script order.' },
|
|
73
|
+
no_feature_edit: { hint: 'No feature card is open: open_feature { id | index } first, then edit_feature { params }, then confirm_feature {}.', guide: CONTOUR_GUIDE },
|
|
74
|
+
edit_failed: { hint: 'The edit could not be applied (stale feature or a lock): feature_tree {} again, open_feature, and retry; cancel_feature {} leaves.' },
|
|
75
|
+
delete_failed: { hint: 'The block could not be removed from the editor: feature_tree {} again and retry delete_feature with the current id.' },
|
|
76
|
+
no_write_part: { hint: 'The active part is not writable (none active or still loading): parts {} then set_active_part { part_id }, and retry.' },
|
|
77
|
+
part_mismatch: { hint: 'part_id is not the active part: set_active_part { part_id } first, or pass the active id from parts {}.' },
|
|
78
|
+
unknown_helper: { hint: 'Not a helper id: list_commands { group: "insert" } lists the insert_* tools, invoke_helper takes a HELPER_PALETTE id.' },
|
|
79
|
+
unknown_chip: { hint: 'The chip id is not in the strip: feature_tree {} lists the current chips.' },
|
|
80
|
+
unknown_sku: { hint: 'Not a fastener size: pass size as "M3", "M5", "1/4-20", ...; listFastenerSizes() in a script lists them.' },
|
|
81
|
+
bad_tool: { hint: 'tool is not a sketch tool: use line, polyline, rectangle, circle, polygon or arc (the sketch_add description lists them).' },
|
|
82
|
+
bad_stage: { hint: 'The call is out of order for this card: follow its sequence (open, pick or set params, commit) and call again.' },
|
|
83
|
+
wrong_entry: { hint: 'This helper is opened from a different ribbon entry: use the insert_* tool the description names.' },
|
|
84
|
+
no_draft: { hint: 'No pending change to confirm: make the edit first (edit_feature, sketch_add, joint_set_params), then confirm.' },
|
|
85
|
+
nothing_to_cancel: { hint: 'Nothing is open to cancel: no call needed; continue with the next step.' },
|
|
86
|
+
// Sketches, slots, contours
|
|
87
|
+
no_sketch: { hint: 'Sketch mode is closed: sketch_begin { plane } first, or open_feature on a contour feature to reopen its sketch.' },
|
|
88
|
+
sketch_open: { hint: 'A sketch or slot card is already open: sketch_commit or sketch_cancel it, then sketch_begin.' },
|
|
89
|
+
plane_card_open: { hint: 'Accept the plane first: sketch_begin { plane, accept_plane: true } or sketch_accept_plane {}, then sketch_add.' },
|
|
90
|
+
empty_sketch: { hint: 'Nothing is drawn: sketch_add { tool, ... } at least one closed profile before sketch_commit, or sketch_cancel.' },
|
|
91
|
+
invalid_profile: { hint: 'The profile params are invalid (message names the field): fix radius / width / height / points and sketch_add again.' },
|
|
92
|
+
no_profile: { hint: 'The feature needs a closed profile: sketch a contour (sketch_begin → sketch_add → sketch_commit) or pass one with insert_cross_section first.' },
|
|
93
|
+
no_cross_section: { hint: 'No saved contour to use: insert_cross_section or a sketch_commit first; feature_tree {} shows the @contour ids.' },
|
|
94
|
+
unknown_contour: { hint: 'The contour id is not in the script: get_script shows the @contour id= markers; use one of those (c1, c2, ...).' },
|
|
95
|
+
not_a_contour: { hint: 'That chip is another feature, not a saved contour: sketch_edit takes a contour:<id> chip; use open_feature / edit_feature / confirm_feature for the rest.' },
|
|
96
|
+
no_slot: { hint: 'The slot card is closed: open the feature (insert_make_loft / open_feature) before slot_* calls.' },
|
|
97
|
+
slot_not_ready: { hint: 'A required contour slot is empty: slot_assign_contour each slot, then slot_commit.' },
|
|
98
|
+
commit_failed: { hint: 'The commit was refused (message is the toast): fix the sketch or params it names and commit again; sketch_cancel leaves.' },
|
|
99
|
+
dimension_failed: { hint: 'The dimension could not be applied: check the entity ids with list_sketch_entities and that the value is finite.' },
|
|
100
|
+
constraint_failed: { hint: 'The constraint could not be solved: remove a conflicting one (sketch_undo) or change the value and retry.' },
|
|
101
|
+
// Documents, parts, assemblies
|
|
102
|
+
unknown_part: { hint: 'Not an open part id (paths and names are never ids): parts {} and pass a row\'s id.' },
|
|
103
|
+
unknown_assembly: { hint: 'Not a saved assembly id: list_assemblies {} and pass a row\'s id.' },
|
|
104
|
+
no_assembly: { hint: 'No document is open: create_assembly {} or open_assembly { assembly_id } first.' },
|
|
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
|
+
no_joint_card: { hint: 'The joint card is closed: joint_open {} first, then joint_pick / joint_set_params / joint_commit.' },
|
|
107
|
+
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
|
+
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.' },
|
|
109
|
+
joint_unsolvable: { hint: 'The solver refused that joint (details.reason is its message): check that the two picks are on different parts and fit the type, for example concentric needs two cylindrical faces (axes); nothing was written.' },
|
|
110
|
+
part_still_referenced: { hint: 'Another assembly lists this part: delete it with scope: "assembly", or delete those parents first.' },
|
|
111
|
+
origin_blocked: { hint: 'This change would move the assembly origin: place the part with part_set_transform instead.' },
|
|
112
|
+
off_study_part: { hint: 'The FEA study belongs to another part: set_active_part to the study\'s part (fea_state {} names it) and retry.' },
|
|
113
|
+
no_fea: { hint: 'No FEA study is open: fea_open {} (or the study tool the description names) first.' },
|
|
114
|
+
no_paint_mode: { hint: 'Paint mode is closed: paint_open {} first (it waits up to 1.5 s for the viewport), or use paint { color } for one call.' },
|
|
115
|
+
bad_paint: { hint: 'color must be a #rrggbb hex (color or hex): paint_set_color { color: "#2f6fdb" }.' },
|
|
116
|
+
no_sheet_mode: { hint: 'Sheet-metal mode is closed: sheet_open {} first.' },
|
|
117
|
+
no_measure_mode: { hint: 'Measure mode is closed: measure_open {} first.' },
|
|
118
|
+
not_ready: { hint: 'The viewport is still switching (details.reason): wait a moment and call again; details.retryable is true.', guide: BUSY_GUIDE },
|
|
119
|
+
busy: { hint: 'The tab is still working on the previous call: status {} and retry when runState is not working.' },
|
|
120
|
+
unavailable: { hint: 'This tool is not available in the current page state (message says why): check status {} and the tool description.' },
|
|
121
|
+
nothing_to_undo: { hint: 'The active stack is at its bottom: nothing to undo; history {} shows the stack.' },
|
|
122
|
+
nothing_to_redo: { hint: 'The active stack is at its top, or sketch mode (no redo): nothing to redo.' },
|
|
123
|
+
// Git and vault
|
|
124
|
+
consent_pending: { hint: 'Nothing was written: ask the user to click Allow in SurfCAD, then retry the same call after details.retry_after_ms.', guide: CONSENT_GUIDE },
|
|
125
|
+
real_repo_blocked: { hint: 'This session cannot get consent for a real-repo write: tell the user and stop; do not loop.', guide: CONSENT_GUIDE },
|
|
126
|
+
confirm_required: { hint: 'Nothing changed: ask the user (details lists what the change touches), and only then retry with confirm: true.', guide: CONSENT_GUIDE },
|
|
127
|
+
pending_save: { hint: 'The write is planned offline: ask the user to Save again when online; nothing more to do now.' },
|
|
128
|
+
upgrade_required: { hint: 'Legacy vault: after the user agrees, git_upgrade_vault { confirm: true }, then git_save again.' },
|
|
129
|
+
upgrade_unavailable: { hint: 'The vault cannot be upgraded from here (message says why): tell the user and stop.' },
|
|
130
|
+
conflict: { hint: 'A remote edit overlaps this save: git_behind_resolve { action: "reload" | "branch", confirm: true } after the user chooses, or git_force_overwrite with confirm: true.' },
|
|
131
|
+
'repo-moved': { hint: 'The repository moved or was renamed: ask the user; git_behind_resolve { action: "reload", confirm: true } reloads from it.' },
|
|
132
|
+
git_blocked: { hint: 'Git is unavailable here (local document or no vault): git_move_to_repo first, or keep working locally; nothing was written.' },
|
|
133
|
+
git_only: { hint: 'This tool needs a vault: git_move_to_repo first, or stay local and use create_part / insert_* instead.' },
|
|
134
|
+
git_error: { hint: 'The git handler failed (message): retry once; stop and tell the user with the message if it repeats.' },
|
|
135
|
+
working_copy_unpersisted: { hint: 'The working copy has not been written yet: git_save { message } (the user clicks Allow), then retry.' },
|
|
136
|
+
not_found: { hint: 'The id or path does not exist in the vault: list_assemblies {} / parts {} and use a listed id.' },
|
|
137
|
+
bind_failed: { hint: 'The part could not be bound to the vault: retry once; tell the user if it repeats.' },
|
|
138
|
+
open_failed: { hint: 'The document could not be opened (message): list_assemblies {} and retry with a listed id.' },
|
|
139
|
+
// Camera, export, screenshot
|
|
140
|
+
bad_view: { hint: 'view must be iso, front, back, right, left, top, bottom, side, front_of_model or normal_to_sketch; or pass position and target.' },
|
|
141
|
+
camera_failed: { hint: 'The viewport could not apply the camera: camera_fit {} then camera_set again.' },
|
|
142
|
+
screenshot_failed: { hint: 'The viewport returned no image: camera_fit {}, wait a moment, then screenshot { save_to: true } again.' },
|
|
143
|
+
screenshot_save_failed: { hint: 'The PNG could not be written on the MCP host (message): pass save_to with a writable path, or save_to: true for a temp file.' },
|
|
144
|
+
unsupported_format: { hint: 'format must be png or jpeg (screenshot) or stl, 3mf, step (export).' },
|
|
145
|
+
export_failed: { hint: 'The mesh could not be exported (message): run {} the part to a runState of ok, then export again.' },
|
|
146
|
+
// Args and envelope
|
|
147
|
+
bad_args: { hint: 'Fix the argument the message names (numbers finite and within ±1000000 mm); list_commands { names: ["<tool>"] } shows the schema.' },
|
|
148
|
+
bad_json: { hint: 'argsJson must be valid JSON: send args as an object instead.' },
|
|
149
|
+
bad_call: { hint: 'The call shape is wrong (message): pass arguments as an object with the keys the tool schema names.' },
|
|
150
|
+
internal: { hint: 'The command threw unexpectedly: retry once; if it repeats, status {} and tell the user with the message.' },
|
|
151
|
+
refused: { hint: 'The tab refused this call (message says why): fix what it names and call again.' },
|
|
152
|
+
forbidden: { hint: 'This call is not allowed for the agent (message): ask the user to do it in the SurfCAD UI.' },
|
|
153
|
+
unknown_tool: { hint: 'Not a tool of this server: list_commands { group } or the tools list shows the names.' },
|
|
154
|
+
unknown_command: { hint: 'Not a bridge command: list_commands {} shows the names.' },
|
|
155
|
+
unknown_topic: { hint: 'guide {} lists the topics; error topics are errors.<code>.' },
|
|
156
|
+
// Pairing and prompts (MCP side)
|
|
157
|
+
not_paired: { hint: 'pair { code } with the code from SurfCAD → Local agent → Show pairing code, then the user clicks Allow; or set SURFCAD_PAIRING_CODE.', guide: PAIRING_GUIDE },
|
|
158
|
+
pair_pending: { hint: 'The user has not clicked Allow yet: wait a few seconds and retry the same call; do not ask for a new code.', guide: PAIRING_GUIDE },
|
|
159
|
+
pair_rejected: { hint: 'The user clicked Deny: ask them before calling pair again.', guide: PAIRING_GUIDE },
|
|
160
|
+
pair_cancelled: { hint: 'The pairing attempt was cancelled: pair { code } again when the user is ready.', guide: PAIRING_GUIDE },
|
|
161
|
+
pair_failed: { hint: 'Pairing failed (message): check the code (6 characters, from the open tab) and that the tab shows it, then pair again.', guide: PAIRING_GUIDE },
|
|
162
|
+
pairing_lost: { hint: 'The tab or relay dropped and the server re-pairs on its own: retry in a few seconds; do not ask for a new code.', guide: PAIRING_GUIDE },
|
|
163
|
+
bad_pairing_code: { hint: 'pair { code: "......" } with the 6-character code from SurfCAD → Local agent → Show pairing code.', guide: PAIRING_GUIDE },
|
|
164
|
+
relay_unavailable: { hint: 'The local relay is not running: start surfcad-mcp normally (it owns the relay) or set SURFCAD_AGENT_BRIDGE_WS_URL.', guide: PAIRING_GUIDE },
|
|
165
|
+
bridge_error: { hint: 'The tab refused the call without a code: status {} and retry once; tell the user if it repeats.' },
|
|
166
|
+
bad_webhook_url: { hint: 'Webhooks need a public https URL (no credentials, localhost or private hosts): fix it, or poll read_messages { wait_ms: 25000 } instead.', guide: PAIRING_GUIDE },
|
|
167
|
+
no_request: { hint: 'in_reply_to is not an open prompt id: read_messages {} lists the queued prompts.' },
|
|
168
|
+
reply_too_long: { hint: 'Shorten the reply (message gives the limit) or send it in several reply_to_user calls with final on the last.' },
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
export const ERROR_TOPIC_PREFIX = 'errors.';
|
|
172
|
+
|
|
173
|
+
/** Codes that carry a guide topic (errors.<code>), in table order. */
|
|
174
|
+
export const ERROR_TOPIC_CODES = Object.freeze(
|
|
175
|
+
Object.keys(ERROR_HINTS).filter((code) => typeof ERROR_HINTS[code].guide === 'string'),
|
|
176
|
+
);
|
|
177
|
+
|
|
178
|
+
/** @param {string} code */
|
|
179
|
+
export function errorTopicName(code) {
|
|
180
|
+
return `${ERROR_TOPIC_PREFIX}${code}`;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* The errors.<code> topic for a code, or null.
|
|
185
|
+
* @param {string} code
|
|
186
|
+
* @returns {{ summary: string, text: string } | null}
|
|
187
|
+
*/
|
|
188
|
+
export function errorTopic(code) {
|
|
189
|
+
const row = ERROR_HINTS[code];
|
|
190
|
+
if (!row || typeof row.guide !== 'string') return null;
|
|
191
|
+
return {
|
|
192
|
+
summary: row.hint,
|
|
193
|
+
text: `${code}. ${row.hint}\n\n${row.guide}`,
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** A hint for a code the table does not know, naming the tool when known. */
|
|
198
|
+
function fallbackHint(tool) {
|
|
199
|
+
const schema = tool ? `list_commands { names: ["${tool}"] } shows its args and error codes; ` : '';
|
|
200
|
+
return `Read message and details; ${schema}guide { topic: "limits" } covers budgets and pairing.`;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Message-aware hints: a code whose recovery depends on what the message says.
|
|
205
|
+
* @param {string} code
|
|
206
|
+
* @param {string} message
|
|
207
|
+
* @returns {{ hint: string, see?: string } | null}
|
|
208
|
+
*/
|
|
209
|
+
function hintFromMessage(code, message) {
|
|
210
|
+
if (code === 'insert_failed' && /needs a selected edge|could not use the .* selected edge/i.test(message)) {
|
|
211
|
+
return { hint: 'Select a connected edge chain (list_feature_edges → select_edges) and insert with use_selection: true, or author the path from points with sweepPoints / makeSweepPath in an insert_code_snippet block.', see: 'sweep_path' };
|
|
212
|
+
}
|
|
213
|
+
if (code === 'insert_failed' && /needs a body first/i.test(message)) {
|
|
214
|
+
return { hint: 'The part is empty: insert_cube / insert_cylinder / insert_tube (or an extrude from a sketch) first, then this insert again.' };
|
|
215
|
+
}
|
|
216
|
+
if (code === 'insert_failed' && /needs a sketch profile|needs two or more sketch profiles/i.test(message)) {
|
|
217
|
+
return { hint: 'Sketch the profile first: sketch_begin → sketch_add → sketch_commit (one contour per profile), then insert again.' };
|
|
218
|
+
}
|
|
219
|
+
return null;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** The sweep-path story is a topic of its own (M10) even though its code is the generic insert_failed. */
|
|
223
|
+
export const EXTRA_ERROR_TOPICS = Object.freeze({
|
|
224
|
+
sweep_path: { summary: 'insert_sweep_path / insert_make_sweep with no edge to follow: pick a chain, or author the path from points', text: `sweep_path. ${SWEEP_GUIDE}` },
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* The hint and guide pointer for one error.
|
|
229
|
+
* @param {string} code
|
|
230
|
+
* @param {string} [message]
|
|
231
|
+
* @param {{ tool?: string }} [context]
|
|
232
|
+
* @returns {{ hint: string, see?: string }}
|
|
233
|
+
*/
|
|
234
|
+
export function hintFor(code, message = '', context = {}) {
|
|
235
|
+
const byMessage = hintFromMessage(code, String(message || ''));
|
|
236
|
+
if (byMessage) {
|
|
237
|
+
return byMessage.see
|
|
238
|
+
? { hint: byMessage.hint, see: `guide { topic: "${errorTopicName(byMessage.see)}" }` }
|
|
239
|
+
: { hint: byMessage.hint };
|
|
240
|
+
}
|
|
241
|
+
const row = ERROR_HINTS[code];
|
|
242
|
+
if (!row) return { hint: fallbackHint(context.tool) };
|
|
243
|
+
const out = { hint: row.hint };
|
|
244
|
+
if (typeof row.guide === 'string') out.see = `guide { topic: "${errorTopicName(code)}" }`;
|
|
245
|
+
return out;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function isPlainObject(value) {
|
|
249
|
+
return !!value && typeof value === 'object' && !Array.isArray(value);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Add `hint` (and `see` when a topic exists) to an error payload. A hint
|
|
254
|
+
* the bridge already sent is kept. Anything that is not an object with a
|
|
255
|
+
* string code is returned as is.
|
|
256
|
+
* @template T
|
|
257
|
+
* @param {T} payload
|
|
258
|
+
* @param {{ tool?: string }} [context]
|
|
259
|
+
* @returns {T}
|
|
260
|
+
*/
|
|
261
|
+
export function withErrorHint(payload, context = {}) {
|
|
262
|
+
if (!isPlainObject(payload) || typeof payload.code !== 'string') return payload;
|
|
263
|
+
const { hint, see } = hintFor(payload.code, payload.message, context);
|
|
264
|
+
const out = { ...payload };
|
|
265
|
+
if (typeof out.hint !== 'string' || !out.hint) out.hint = hint;
|
|
266
|
+
if (see && typeof out.see !== 'string') out.see = see;
|
|
267
|
+
return out;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Hints on the error rows inside a successful tool result: `errors` rows
|
|
272
|
+
* (feature_failed, feature_timeout, geometry_worker_crashed) and the
|
|
273
|
+
* `crash` record. Plain-string rows and rows without a code are left alone.
|
|
274
|
+
* @template T
|
|
275
|
+
* @param {T} value
|
|
276
|
+
* @returns {T}
|
|
277
|
+
*/
|
|
278
|
+
export function withRowHints(value) {
|
|
279
|
+
if (!isPlainObject(value)) return value;
|
|
280
|
+
let out = value;
|
|
281
|
+
if (Array.isArray(value.errors) && value.errors.some((row) => isPlainObject(row) && typeof row.code === 'string')) {
|
|
282
|
+
out = { ...out, errors: value.errors.map((row) => (isPlainObject(row) ? withErrorHint(row) : row)) };
|
|
283
|
+
}
|
|
284
|
+
if (isPlainObject(value.crash) && typeof value.crash.code === 'string') {
|
|
285
|
+
out = { ...out, crash: withErrorHint(value.crash) };
|
|
286
|
+
}
|
|
287
|
+
return out;
|
|
288
|
+
}
|