@floless/app 0.138.1 → 0.139.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.
Files changed (109) hide show
  1. package/autostart.mjs +6 -2
  2. package/desktop-access-production-manifest.mjs +7 -0
  3. package/dist/floless-server.cjs +157133 -70500
  4. package/dist/schemas/model.continuation.v1.schema.json +19 -0
  5. package/dist/schemas/model.continuation.v2.schema.json +19 -0
  6. package/dist/schemas/model.query-response.v1.schema.json +95 -0
  7. package/dist/schemas/model.query-response.v2.schema.json +80 -0
  8. package/dist/schemas/model.query.v1.schema.json +87 -0
  9. package/dist/schemas/model.query.v2.schema.json +87 -0
  10. package/dist/schemas/model.snap-candidate.v1.schema.json +48 -0
  11. package/dist/schemas/model.snap-constraint.v1.schema.json +18 -0
  12. package/dist/schemas/model.snap-query.v1.schema.json +24 -0
  13. package/dist/schemas/model.snap-result.v1.schema.json +33 -0
  14. package/dist/schemas/model.snapshot.v1.schema.json +136 -0
  15. package/dist/schemas/revit.model.v1.schema.json +24 -0
  16. package/dist/schemas/steel.model.v2.schema.json +45 -6
  17. package/dist/skills/floless-app-approval/SKILL.md +19 -5
  18. package/dist/skills/floless-app-bridge/SKILL.md +19 -6
  19. package/dist/skills/floless-app-knowledge/SKILL.md +22 -1
  20. package/dist/skills/floless-app-new-workflow/SKILL.md +31 -27
  21. package/dist/skills/floless-app-new-workflow/references/build-and-verify.md +13 -12
  22. package/dist/skills/floless-app-onboarding/SKILL.md +3 -3
  23. package/dist/skills/floless-app-onboarding/references/floless-app-tour.md +16 -9
  24. package/dist/skills/floless-app-steel-model/SKILL.md +11 -2
  25. package/dist/skills/floless-app-steel-model/references/detail-from-a-screenshot.md +95 -0
  26. package/dist/skills/floless-app-steel-takeoff/SKILL.md +146 -21
  27. package/dist/skills/floless-app-steel-takeoff/references/elevation-registration.md +19 -0
  28. package/dist/skills/floless-app-tweak-contract/SKILL.md +42 -8
  29. package/dist/skills/floless-app-vectorize/SKILL.md +19 -6
  30. package/dist/skills/floless-app-workflows/SKILL.md +30 -3
  31. package/dist/skills/floless-app-workflows/references/workspace-data.md +77 -4
  32. package/dist/templates/floless-workspace-model-report.flo +77 -0
  33. package/dist/templates/revit-model.flo +111 -0
  34. package/dist/web/app.css +415 -177
  35. package/dist/web/app.js +302 -51
  36. package/dist/web/aware.js +1430 -1040
  37. package/dist/web/chat.css +692 -0
  38. package/dist/web/chat.js +2651 -0
  39. package/dist/web/commands-revit.js +42 -0
  40. package/dist/web/commands-shell.js +536 -70
  41. package/dist/web/commands-steel.js +344 -146
  42. package/dist/web/commands.js +1 -1
  43. package/dist/web/index.html +283 -77
  44. package/dist/web/instructor.js +217 -36
  45. package/dist/web/left-pane.js +636 -0
  46. package/dist/web/model-artifact-loader.js +75 -0
  47. package/dist/web/model-authoring-gestures.js +141 -0
  48. package/dist/web/model-cad-tools.js +20 -0
  49. package/dist/web/model-clip-gesture.js +148 -0
  50. package/dist/web/model-clip-list.js +156 -0
  51. package/dist/web/model-clip-session.js +274 -0
  52. package/dist/web/model-clip-three-overlay.js +295 -0
  53. package/dist/web/model-clip-three-preview.js +59 -0
  54. package/dist/web/model-editor-contract.js +519 -0
  55. package/dist/web/model-editor-revit-adapter.js +139 -0
  56. package/dist/web/model-editor-shell.js +271 -0
  57. package/dist/web/model-editor-state-recovery.js +44 -0
  58. package/dist/web/model-editor-steel-adapter.js +410 -0
  59. package/dist/web/model-editor.css +268 -0
  60. package/dist/web/model-frame.js +192 -0
  61. package/dist/web/model-inspector.js +128 -0
  62. package/dist/web/model-measure.js +390 -0
  63. package/dist/web/model-navigation-controls.js +246 -0
  64. package/dist/web/model-orientation-overlay.js +217 -0
  65. package/dist/web/model-panel-bridge.js +230 -0
  66. package/dist/web/model-pointer-dock.js +164 -0
  67. package/dist/web/model-revit-module.js +83 -0
  68. package/dist/web/model-selection-coordinator.js +151 -0
  69. package/dist/web/model-selection-tools.js +290 -0
  70. package/dist/web/model-snap-contract.js +267 -0
  71. package/dist/web/model-snapping.js +497 -0
  72. package/dist/web/model-spatial-panel.js +294 -0
  73. package/dist/web/model-spatial-tools.js +249 -0
  74. package/dist/web/model-tree.js +47 -0
  75. package/dist/web/model-viewport-lighting.js +166 -0
  76. package/dist/web/model-viewport-revit-adapter.js +1224 -0
  77. package/dist/web/model-viewport-state.js +505 -0
  78. package/dist/web/model-viewport-steel-adapter.js +150 -0
  79. package/dist/web/model-viewport-toolbar.js +516 -0
  80. package/dist/web/model-viewport.js +717 -0
  81. package/dist/web/panels.js +8 -15
  82. package/dist/web/renderers.js +3 -0
  83. package/dist/web/revit-editor.css +35 -0
  84. package/dist/web/revit-editor.html +74 -0
  85. package/dist/web/revit-editor.js +845 -0
  86. package/dist/web/steel-3d-core.js +16 -44
  87. package/dist/web/steel-3d-view.js +1384 -633
  88. package/dist/web/steel-canvas-guidance.js +3 -1
  89. package/dist/web/steel-editor.html +2121 -1253
  90. package/dist/web/steel-filter.html +5 -1
  91. package/dist/web/steel-model-v2-commands.js +72 -1
  92. package/dist/web/steel-split-view.js +5 -39
  93. package/dist/web/steel-view-generation.js +107 -17
  94. package/dist/web/vector-3d.html +12 -0
  95. package/dist/web/workspaces.js +2190 -277
  96. package/distribution-profile-active.mjs +2 -0
  97. package/distribution-profile-production.mjs +47 -0
  98. package/distribution-profile-shared.mjs +8 -0
  99. package/distribution-profile.mjs +18 -0
  100. package/distribution-resource-inventory.mjs +81 -0
  101. package/launch.mjs +18 -10
  102. package/log.mjs +2 -1
  103. package/managed-runtime-policy.mjs +104 -0
  104. package/model-reader-policy-active.mjs +7 -0
  105. package/network-policy-active.mjs +6 -0
  106. package/package.json +17 -2
  107. package/post-update-marker.mjs +3 -1
  108. package/rvt-production-uat-authority.mjs +60 -0
  109. package/teardown.mjs +4 -3
@@ -0,0 +1,497 @@
1
+ // Provider-neutral mesh acquisition. Semantic endpoints/axes/grids are separate authenticated
2
+ // provider candidates; tessellation data is never relabelled as authored model meaning.
3
+ import { MODEL_SNAP_KIND_ORDER, MODEL_SNAP_LIMITS_V1, MODEL_SNAP_SCHEMA } from './model-snap-contract.js';
4
+ import { projectPointOnSegment2d, SEG_DEGENERACY } from './steel-3d-core.js';
5
+
6
+ export const MODEL_SNAP_ACQUISITION_RADIUS_PX = MODEL_SNAP_LIMITS_V1.acquisitionRadiusCssPx;
7
+ export const MODEL_SNAP_TIE_EPSILON_PX = MODEL_SNAP_LIMITS_V1.distanceTieCssPx;
8
+ export const MODEL_SNAP_QUERY_CAP = 256;
9
+ export const MODEL_SNAP_INDEX_MAX_CANDIDATES = 2_000_000;
10
+ export const MODEL_SNAP_INDEX_MAX_BYTES = 256 * 1024 * 1024;
11
+
12
+ const KIND_RANK = new Map(MODEL_SNAP_KIND_ORDER.map((kind, index) => [kind, index]));
13
+ const EDGE_CARRIER_KIND = 'mesh-edge-carrier';
14
+ const ESTIMATED_CANDIDATE_BYTES = 96;
15
+ const finitePoint = (point) => Array.isArray(point) && point.length === 3 && point.every(Number.isFinite);
16
+ const frozenPoint = (point) => Object.freeze([...point]);
17
+ const midpoint = (a, b) => a.map((value, axis) => (value + b[axis]) / 2);
18
+ const interpolate = (a, b, t) => a.map((value, axis) => value + (b[axis] - value) * t);
19
+
20
+ function disabledIndex(code, message, limits) {
21
+ const refusal = Object.freeze({ code, message });
22
+ return Object.freeze({ available: false, candidates: Object.freeze([]), refusal, truncated: false, ...limits,
23
+ query: () => Object.freeze([]) });
24
+ }
25
+
26
+ /**
27
+ * Build a complete bounded index. If the complete topology cannot fit, snapping is disabled visibly;
28
+ * a traversal prefix is never exposed because that would make nearby geometry depend on file order.
29
+ */
30
+ export function buildModelSnapIndex(meshes, {
31
+ maxCandidates = MODEL_SNAP_INDEX_MAX_CANDIDATES,
32
+ maxBytes = MODEL_SNAP_INDEX_MAX_BYTES,
33
+ } = {}) {
34
+ if (!Number.isSafeInteger(maxCandidates) || maxCandidates < 1 || !Number.isSafeInteger(maxBytes) || maxBytes < 1) {
35
+ throw new TypeError('Model snap index limits must be positive safe integers.');
36
+ }
37
+ const candidates = [];
38
+ const limits = Object.freeze({ maxCandidates, maxBytes });
39
+ const push = (candidate) => {
40
+ if (candidates.length + 1 > maxCandidates || (candidates.length + 1) * ESTIMATED_CANDIDATE_BYTES > maxBytes) return false;
41
+ candidates.push(Object.freeze(candidate)); return true;
42
+ };
43
+ for (const [meshOrdinal, mesh] of [...(meshes ?? [])].entries()) {
44
+ mesh.updateWorldMatrix?.(true, false);
45
+ const position = mesh.geometry?.getAttribute?.('position');
46
+ if (!position?.count) continue;
47
+ const Vector = mesh.position?.constructor;
48
+ if (!Vector) continue;
49
+ const world = (index) => {
50
+ const point = new Vector(position.getX(index), position.getY(index), position.getZ(index));
51
+ const value = mesh.localToWorld ? mesh.localToWorld(point).toArray() : point.toArray();
52
+ return finitePoint(value) ? value : null;
53
+ };
54
+ const entityId = mesh.userData?.entityId ?? null;
55
+ const meshId = `${meshOrdinal}:${String(entityId ?? 'unowned')}`;
56
+ const indices = mesh.geometry.index?.array;
57
+ const triangleCount = indices ? Math.floor(indices.length / 3) : Math.floor(position.count / 3);
58
+ const points = new Map();
59
+ const pointAt = (index) => { if (!points.has(index)) points.set(index, world(index)); return points.get(index); };
60
+ const vertexKeys = new Set(); const edgeKeys = new Set();
61
+ for (let triangle = 0; triangle < triangleCount; triangle++) {
62
+ const source = indices
63
+ ? [Number(indices[triangle * 3]), Number(indices[triangle * 3 + 1]), Number(indices[triangle * 3 + 2])]
64
+ : [triangle * 3, triangle * 3 + 1, triangle * 3 + 2];
65
+ const trianglePoints = source.map(pointAt);
66
+ if (!trianglePoints.every(finitePoint)) continue;
67
+ for (let corner = 0; corner < 3; corner++) {
68
+ const feature = indices ? String(source[corner]) : `${triangle}:${corner}`;
69
+ if (!vertexKeys.has(feature)) {
70
+ vertexKeys.add(feature);
71
+ if (!push({ id: `${meshId}:v:${feature}`, kind: 'mesh-vertex', point: frozenPoint(trianglePoints[corner]), entityId,
72
+ meshOrdinal, triangleOrdinal: triangle, featureOrdinal: indices ? source[corner] : corner })) {
73
+ return disabledIndex('over-budget', 'Mesh snapping is unavailable because the complete topology exceeds its fixed index budget.', limits);
74
+ }
75
+ }
76
+ }
77
+ const edges = [[0, 1], [1, 2], [2, 0]];
78
+ for (const [edgeOrdinal, [left, right]] of edges.entries()) {
79
+ const pair = indices ? [source[left], source[right]].sort((a, b) => a - b) : [left, right];
80
+ const edgeFeature = indices ? `${pair[0]}:${pair[1]}` : `${triangle}:${edgeOrdinal}`;
81
+ if (edgeKeys.has(edgeFeature)) continue;
82
+ edgeKeys.add(edgeFeature);
83
+ const a = frozenPoint(trianglePoints[left]); const b = frozenPoint(trianglePoints[right]);
84
+ const shared = { entityId, meshOrdinal, triangleOrdinal: triangle, featureOrdinal: edgeOrdinal,
85
+ sourceIndices: Object.freeze(pair), segment: Object.freeze([a, b]) };
86
+ // Midpoint and nearest-on-edge are two query-time interpretations of the same authenticated
87
+ // segment. Store that topology once so large indexed BIM models do not pay twice for every edge.
88
+ if (!push({ id: `${meshId}:e:${edgeFeature}`, kind: EDGE_CARRIER_KIND, point: frozenPoint(midpoint(a, b)), ...shared })) {
89
+ return disabledIndex('over-budget', 'Mesh snapping is unavailable because the complete topology exceeds its fixed index budget.', limits);
90
+ }
91
+ }
92
+ }
93
+ }
94
+
95
+ const frozen = Object.freeze(candidates);
96
+ if (!frozen.length) return Object.freeze({ available: true, candidates: frozen, refusal: null, truncated: false, ...limits,
97
+ cellSize: 1, query: () => Object.freeze([]) });
98
+ const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
99
+ for (const candidate of frozen) for (let axis = 0; axis < 3; axis++) {
100
+ min[axis] = Math.min(min[axis], candidate.point[axis]); max[axis] = Math.max(max[axis], candidate.point[axis]);
101
+ }
102
+ const diagonal = Math.hypot(max[0] - min[0], max[1] - min[1], max[2] - min[2]);
103
+ // Sixteen cells across the model keeps a surface hit and the midpoint carrier of its incident edge
104
+ // in the same bounded neighbourhood without indexing one long edge into thousands of buckets.
105
+ const cellSize = Math.max(diagonal / 16, 1e-6);
106
+ const cell = (point) => point.map((value, axis) => Math.floor((value - min[axis]) / cellSize));
107
+ const buckets = new Map();
108
+ frozen.forEach((candidate, index) => { const key = cell(candidate.point).join(','); const bucket = buckets.get(key) ?? []; bucket.push(index); buckets.set(key, bucket); });
109
+ const query = (hint, limit = MODEL_SNAP_QUERY_CAP) => {
110
+ if (!finitePoint(hint)) return Object.freeze([]);
111
+ const cap = Math.max(1, Math.min(MODEL_SNAP_QUERY_CAP, Math.floor(limit) || MODEL_SNAP_QUERY_CAP));
112
+ const center = cell(hint); const found = [];
113
+ for (let radius = 0; radius <= 4; radius++) {
114
+ for (let x = -radius; x <= radius; x++) for (let y = -radius; y <= radius; y++) for (let z = -radius; z <= radius; z++) {
115
+ if (radius && Math.max(Math.abs(x), Math.abs(y), Math.abs(z)) !== radius) continue;
116
+ for (const index of buckets.get(`${center[0] + x},${center[1] + y},${center[2] + z}`) ?? []) found.push(frozen[index]);
117
+ }
118
+ if (found.length >= cap) break;
119
+ }
120
+ found.sort((a, b) => Math.hypot(...a.point.map((value, axis) => value - hint[axis]))
121
+ - Math.hypot(...b.point.map((value, axis) => value - hint[axis])) || a.id.localeCompare(b.id));
122
+ return Object.freeze(found.slice(0, cap));
123
+ };
124
+ return Object.freeze({ available: true, candidates: frozen, refusal: null, truncated: false, ...limits, cellSize, query });
125
+ }
126
+
127
+ function screenPoint(candidate, project) {
128
+ if (candidate.kind !== 'mesh-edge-nearest' || !candidate.segment) {
129
+ const screen = project(candidate.point); return screen?.visible ? { point: candidate.point, screen } : null;
130
+ }
131
+ const [a, b] = candidate.segment; const pa = project(a), pb = project(b);
132
+ if (!pa?.visible || !pb?.visible) return null;
133
+ return { a, b, pa, pb };
134
+ }
135
+
136
+ function edgeCarrierVariants(candidate, client, project, enabled) {
137
+ const variants = [];
138
+ if (enabled['mesh-edge-midpoint'] !== false) {
139
+ const screen = project(candidate.point);
140
+ if (screen?.visible) variants.push({ ...candidate, id: `${candidate.id}:midpoint`, kind: 'mesh-edge-midpoint', screen });
141
+ }
142
+ if (enabled['mesh-edge-nearest'] !== false && candidate.segment) {
143
+ const [a, b] = candidate.segment; const pa = project(a), pb = project(b);
144
+ if (pa?.visible && pb?.visible) {
145
+ const t = projectPointOnSegment2d(
146
+ [client.x, client.y], [pa.x, pa.y], [pb.x, pb.y], SEG_DEGENERACY.atMost(1e-12),
147
+ ).t;
148
+ const point = frozenPoint(interpolate(a, b, t)); const screen = project(point);
149
+ if (screen?.visible) variants.push({ ...candidate, id: `${candidate.id}:nearest`, kind: 'mesh-edge-nearest', point, screen });
150
+ }
151
+ }
152
+ return variants;
153
+ }
154
+
155
+ function preferred(next, current) {
156
+ if (!current) return true;
157
+ const delta = next.distance - current.distance;
158
+ if (Math.abs(delta) > MODEL_SNAP_TIE_EPSILON_PX) return delta < 0;
159
+ const rank = (KIND_RANK.get(next.kind) ?? Number.MAX_SAFE_INTEGER) - (KIND_RANK.get(current.kind) ?? Number.MAX_SAFE_INTEGER);
160
+ return rank < 0 || (rank === 0 && next.id.localeCompare(current.id) < 0);
161
+ }
162
+
163
+ /**
164
+ * Resolve a complete index using screen-stable tolerance and deterministic ties.
165
+ * @param {any} index
166
+ * @param {{x:number,y:number}} client
167
+ * @param {(point:readonly number[])=>any} project
168
+ * @param {Record<string,boolean>} enabled
169
+ * @param {number} radiusPx
170
+ * @param {readonly number[]|null} worldHint
171
+ * @param {number} queryCap
172
+ */
173
+ export function closestModelSnap(index, client, project, enabled = {}, radiusPx = MODEL_SNAP_ACQUISITION_RADIUS_PX, worldHint = null, queryCap = MODEL_SNAP_QUERY_CAP) {
174
+ if (!index?.available || !finitePoint(worldHint) || !Number.isFinite(client?.x) || !Number.isFinite(client?.y)) return null;
175
+ let best = null;
176
+ for (const candidate of index.query(worldHint, queryCap)) {
177
+ if (candidate.kind === EDGE_CARRIER_KIND) {
178
+ for (const variant of edgeCarrierVariants(candidate, client, project, enabled)) {
179
+ const distance = Math.hypot(variant.screen.x - client.x, variant.screen.y - client.y);
180
+ const next = { ...variant, distance };
181
+ if (distance <= radiusPx && preferred(next, best)) best = next;
182
+ }
183
+ continue;
184
+ }
185
+ if (enabled[candidate.kind] === false) continue;
186
+ const projected = screenPoint(candidate, project); if (!projected) continue;
187
+ let point = candidate.point, screen = projected.screen;
188
+ if (candidate.kind === 'mesh-edge-nearest') {
189
+ const t = projectPointOnSegment2d(
190
+ [client.x, client.y], [projected.pa.x, projected.pa.y], [projected.pb.x, projected.pb.y],
191
+ SEG_DEGENERACY.atMost(1e-12),
192
+ ).t;
193
+ point = frozenPoint(interpolate(projected.a, projected.b, t)); screen = project(point);
194
+ if (!screen?.visible) continue;
195
+ }
196
+ const distance = Math.hypot(screen.x - client.x, screen.y - client.y);
197
+ const next = { ...candidate, point, screen, distance };
198
+ if (distance <= radiusPx && preferred(next, best)) best = next;
199
+ }
200
+ return best ? Object.freeze(best) : null;
201
+ }
202
+
203
+ const add = (a, b) => a.map((value, axis) => value + b[axis]);
204
+ const subtract = (a, b) => a.map((value, axis) => value - b[axis]);
205
+ const scale = (value, amount) => value.map((component) => component * amount);
206
+ const dot = (a, b) => a.reduce((sum, value, axis) => sum + value * b[axis], 0);
207
+ const cross = (a, b) => [
208
+ a[1] * b[2] - a[2] * b[1],
209
+ a[2] * b[0] - a[0] * b[2],
210
+ a[0] * b[1] - a[1] * b[0],
211
+ ];
212
+ const length = (value) => Math.hypot(...value);
213
+ const distance = (a, b) => length(subtract(a, b));
214
+ const normalized = (value) => {
215
+ const size = length(value);
216
+ return size >= MODEL_SNAP_LIMITS_V1.directionMinLength ? scale(value, 1 / size) : null;
217
+ };
218
+ const canonicalPoint = (point) => Object.freeze(point.map((value) => Math.abs(value) < 1e-12 ? 0 : value));
219
+ const canonicalPrimitive = (primitive) => {
220
+ const frozen = {};
221
+ for (const [key, value] of Object.entries(primitive)) {
222
+ frozen[key] = Array.isArray(value) ? Object.freeze(value.map((item) => Array.isArray(item) ? canonicalPoint(item) : item)) : value;
223
+ }
224
+ return Object.freeze(frozen);
225
+ };
226
+
227
+ function stableId(value) {
228
+ // FNV-1a is used only for a bounded, deterministic session id; it is not a trust or provenance digest.
229
+ let hash = 0x811c9dc5;
230
+ for (const character of JSON.stringify(value)) {
231
+ hash ^= character.codePointAt(0);
232
+ hash = Math.imul(hash, 0x01000193);
233
+ }
234
+ return (hash >>> 0).toString(16).padStart(8, '0');
235
+ }
236
+
237
+ function refusal(generation, code, message) {
238
+ return Object.freeze({ schemaVersion: MODEL_SNAP_SCHEMA.result, status: 'refused', generation, code, message });
239
+ }
240
+
241
+ function liveRay(query, cameraPort) {
242
+ const ray = cameraPort?.rayForCss?.(query?.pointerCssPx);
243
+ const direction = finitePoint(ray?.direction) ? normalized(ray.direction) : null;
244
+ return finitePoint(ray?.originMm) && direction ? { originMm: ray.originMm, direction } : null;
245
+ }
246
+
247
+ function projectedPoint(point, cameraPort) {
248
+ const projected = cameraPort?.projectPoint?.(point);
249
+ if (Array.isArray(projected) && projected.length >= 2 && projected.slice(0, 2).every(Number.isFinite)) {
250
+ return { point: [projected[0], projected[1]], visible: projected.length < 3 || Number.isFinite(projected[2]) };
251
+ }
252
+ if (Number.isFinite(projected?.x) && Number.isFinite(projected?.y)) {
253
+ return { point: [projected.x, projected.y], visible: projected.visible !== false };
254
+ }
255
+ return null;
256
+ }
257
+
258
+ function acquiredResult({ query, point, guides, solverKind, kind = 'free-point', cameraPort }) {
259
+ if (!query.enabledKinds?.includes(kind)) return refusal(query.generation, 'filtered', `${kind} snapping is disabled.`);
260
+ const projected = projectedPoint(point, cameraPort);
261
+ if (!projected?.visible) return refusal(query.generation, 'occluded', 'The solved snap point is not visible in the active camera.');
262
+ const screenDistance = Math.hypot(projected.point[0] - query.pointerCssPx[0], projected.point[1] - query.pointerCssPx[1]);
263
+ if (screenDistance > MODEL_SNAP_LIMITS_V1.acquisitionRadiusCssPx) {
264
+ return refusal(query.generation, 'outside-radius', 'The solved snap point is outside the fixed screen-space acquisition radius.');
265
+ }
266
+ const opaqueId = `context:${solverKind}:${stableId({ point, guides })}`;
267
+ const providerRef = Object.freeze({ type: 'session', generation: query.generation, opaqueId });
268
+ if (cameraPort?.isOccluded?.(point, providerRef, MODEL_SNAP_LIMITS_V1.workPlaneToleranceMm)) {
269
+ return refusal(query.generation, 'occluded', 'The solved snap point is hidden by nearer geometry.');
270
+ }
271
+ return Object.freeze({
272
+ schemaVersion: MODEL_SNAP_SCHEMA.result,
273
+ status: 'acquired',
274
+ generation: query.generation,
275
+ candidateId: opaqueId,
276
+ pointMm: canonicalPoint(point),
277
+ projectedCssPx: Object.freeze(projected.point),
278
+ distanceCssPx: screenDistance,
279
+ kind,
280
+ providerRef,
281
+ guides: Object.freeze(guides.map(canonicalPrimitive)),
282
+ });
283
+ }
284
+
285
+ function pointOnPlane(point, plane) {
286
+ return Math.abs(dot(subtract(point, plane.originMm), plane.normal)) <= MODEL_SNAP_LIMITS_V1.workPlaneToleranceMm;
287
+ }
288
+
289
+ function rayPlaneHit(ray, plane) {
290
+ const denominator = dot(ray.direction, plane.normal);
291
+ if (Math.abs(denominator) < MODEL_SNAP_LIMITS_V1.nearParallelCrossLength) return null;
292
+ return add(ray.originMm, scale(ray.direction, dot(subtract(plane.originMm, ray.originMm), plane.normal) / denominator));
293
+ }
294
+
295
+ function closestLineParameters(a, u, b, v) {
296
+ const uv = dot(u, v), denominator = 1 - uv * uv;
297
+ if (Math.sqrt(Math.max(0, denominator)) < MODEL_SNAP_LIMITS_V1.nearParallelCrossLength) return null;
298
+ const w = subtract(a, b);
299
+ return {
300
+ a: (uv * dot(v, w) - dot(u, w)) / denominator,
301
+ b: (dot(v, w) - uv * dot(u, w)) / denominator,
302
+ };
303
+ }
304
+
305
+ function linearPrimitive(primitive) {
306
+ if (primitive?.type === 'line') {
307
+ const direction = normalized(primitive.direction);
308
+ return direction ? { origin: primitive.originMm, direction, min: -Infinity, max: Infinity } : null;
309
+ }
310
+ if (primitive?.type === 'segment') {
311
+ const delta = subtract(primitive.endMm, primitive.startMm), size = length(delta);
312
+ return size >= MODEL_SNAP_LIMITS_V1.directionMinLength
313
+ ? { origin: primitive.startMm, direction: scale(delta, 1 / size), min: 0, max: size, size }
314
+ : null;
315
+ }
316
+ return null;
317
+ }
318
+
319
+ function pointerPoint(query, ray, workPlane, fallbackPlane) {
320
+ if (query.mode === 'work-plane') return workPlane ? rayPlaneHit(ray, workPlane) : null;
321
+ if (workPlane) return rayPlaneHit(ray, workPlane);
322
+ return fallbackPlane ? rayPlaneHit(ray, fallbackPlane) : null;
323
+ }
324
+
325
+ function workPlaneRefusal(constraint, point, direction = null) {
326
+ if (constraint.query.mode !== 'work-plane') return null;
327
+ if (!constraint.workPlane) return refusal(constraint.query.generation, 'work-plane', 'Work-plane snapping requires an active working plane.');
328
+ if (!pointOnPlane(constraint.firstAnchorMm, constraint.workPlane)
329
+ || (point && !pointOnPlane(point, constraint.workPlane))
330
+ || (direction && Math.abs(dot(direction, constraint.workPlane.normal)) > MODEL_SNAP_LIMITS_V1.nearParallelCrossLength)) {
331
+ return refusal(constraint.query.generation, 'work-plane', 'The contextual construction does not lie on the active working plane.');
332
+ }
333
+ return null;
334
+ }
335
+
336
+ function arcContains(primitive, point) {
337
+ if (primitive.type !== 'arc') return true;
338
+ const radial = normalized(subtract(point, primitive.centerMm));
339
+ if (!radial) return false;
340
+ const side = cross(primitive.normal, primitive.startDirection);
341
+ let angle = Math.atan2(dot(radial, side), dot(radial, primitive.startDirection));
342
+ if (primitive.sweepRadians >= 0) {
343
+ if (angle < 0) angle += Math.PI * 2;
344
+ return angle <= primitive.sweepRadians + 1e-9;
345
+ }
346
+ if (angle > 0) angle -= Math.PI * 2;
347
+ return angle >= primitive.sweepRadians - 1e-9;
348
+ }
349
+
350
+ function solvePerpendicular(constraint, cameraPort, ray) {
351
+ const target = linearPrimitive(constraint.target);
352
+ let points = [];
353
+ let guides = [];
354
+ if (target) {
355
+ const along = dot(subtract(constraint.firstAnchorMm, target.origin), target.direction);
356
+ if (constraint.target.type === 'segment' && constraint.extentPolicy === 'finite' && (along < 0 || along > target.size)) {
357
+ return refusal(constraint.query.generation, 'outside-extent', 'The perpendicular foot lies outside the finite target segment.');
358
+ }
359
+ const point = add(target.origin, scale(target.direction, along));
360
+ if (distance(constraint.firstAnchorMm, point) < MODEL_SNAP_LIMITS_V1.directionMinLength) {
361
+ return refusal(constraint.query.generation, 'degenerate', 'The first anchor already lies on the perpendicular target.');
362
+ }
363
+ const gate = workPlaneRefusal(constraint, point, target.direction); if (gate) return gate;
364
+ points = [point];
365
+ guides = [
366
+ { type: 'line', originMm: point, direction: target.direction },
367
+ { type: 'segment', startMm: constraint.firstAnchorMm, endMm: point },
368
+ ];
369
+ } else if (constraint.target?.type === 'circle' || constraint.target?.type === 'arc') {
370
+ const radial = subtract(constraint.firstAnchorMm, constraint.target.centerMm);
371
+ const planar = subtract(radial, scale(constraint.target.normal, dot(radial, constraint.target.normal)));
372
+ const direction = normalized(planar);
373
+ if (!direction) return refusal(constraint.query.generation, 'degenerate', 'A perpendicular direction cannot be derived from the circle centre.');
374
+ points = [1, -1].map((sign) => add(constraint.target.centerMm, scale(direction, constraint.target.radiusMm * sign)))
375
+ .filter((point) => arcContains(constraint.target, point));
376
+ if (!points.length) return refusal(constraint.query.generation, 'outside-extent', 'The perpendicular feet lie outside the finite arc sweep.');
377
+ points = points.filter((point) => distance(point, constraint.firstAnchorMm) >= MODEL_SNAP_LIMITS_V1.directionMinLength);
378
+ if (!points.length) return refusal(constraint.query.generation, 'degenerate', 'The first anchor already lies on the only perpendicular target.');
379
+ } else return refusal(constraint.query.generation, 'degenerate', 'Perpendicular snapping requires a non-degenerate line, segment, arc, or circle.');
380
+
381
+ const ranked = points.map((point) => {
382
+ const projected = projectedPoint(point, cameraPort);
383
+ return { point, projected, distance: projected ? Math.hypot(projected.point[0] - constraint.query.pointerCssPx[0], projected.point[1] - constraint.query.pointerCssPx[1]) : Infinity };
384
+ }).sort((a, b) => {
385
+ const delta = a.distance - b.distance;
386
+ return Math.abs(delta) > MODEL_SNAP_TIE_EPSILON_PX ? delta : a.point.join(',').localeCompare(b.point.join(','));
387
+ });
388
+ const point = ranked[0].point;
389
+ const gate = workPlaneRefusal(constraint, point); if (gate) return gate;
390
+ if (!guides.length) guides = [
391
+ constraint.target.type === 'arc' ? constraint.target
392
+ : { type: 'circle', centerMm: constraint.target.centerMm, normal: constraint.target.normal, radiusMm: constraint.target.radiusMm },
393
+ { type: 'segment', startMm: constraint.firstAnchorMm, endMm: point },
394
+ ];
395
+ return acquiredResult({ query: constraint.query, point, guides, solverKind: 'perpendicular', cameraPort });
396
+ }
397
+
398
+ function solveParallel(constraint, cameraPort, ray) {
399
+ const target = linearPrimitive(constraint.target);
400
+ if (!target) return refusal(constraint.query.generation, 'degenerate', 'Parallel snapping requires a non-degenerate line or segment direction.');
401
+ const gate = workPlaneRefusal(constraint, constraint.firstAnchorMm, target.direction); if (gate) return gate;
402
+ let point;
403
+ if (constraint.query.mode === 'work-plane') {
404
+ const hit = pointerPoint(constraint.query, ray, constraint.workPlane, null);
405
+ if (!hit) return refusal(constraint.query.generation, 'near-parallel', 'The pointer ray is parallel to the active working plane.');
406
+ point = add(constraint.firstAnchorMm, scale(target.direction, dot(subtract(hit, constraint.firstAnchorMm), target.direction)));
407
+ } else {
408
+ const parameters = closestLineParameters(constraint.firstAnchorMm, target.direction, ray.originMm, ray.direction);
409
+ if (!parameters) return refusal(constraint.query.generation, 'near-parallel', 'The pointer ray is parallel to the requested construction line.');
410
+ point = add(constraint.firstAnchorMm, scale(target.direction, parameters.a));
411
+ }
412
+ return acquiredResult({ query: constraint.query, point,
413
+ guides: [{ type: 'line', originMm: point, direction: target.direction }], solverKind: 'parallel', cameraPort });
414
+ }
415
+
416
+ function solveExtension(constraint, cameraPort, ray) {
417
+ const target = linearPrimitive(constraint.target);
418
+ if (!target || constraint.target?.type !== 'segment') {
419
+ return refusal(constraint.query.generation, 'degenerate', 'Extension snapping requires a non-degenerate finite segment.');
420
+ }
421
+ const gate = workPlaneRefusal(constraint, constraint.firstAnchorMm, target.direction); if (gate) return gate;
422
+ if (constraint.query.mode === 'work-plane'
423
+ && (!pointOnPlane(constraint.target.startMm, constraint.workPlane) || !pointOnPlane(constraint.target.endMm, constraint.workPlane))) {
424
+ return refusal(constraint.query.generation, 'work-plane', 'The source segment does not lie on the active working plane.');
425
+ }
426
+ let along;
427
+ if (constraint.query.mode === 'work-plane') {
428
+ const hit = pointerPoint(constraint.query, ray, constraint.workPlane, null);
429
+ if (!hit) return refusal(constraint.query.generation, 'near-parallel', 'The pointer ray is parallel to the active working plane.');
430
+ along = dot(subtract(hit, target.origin), target.direction);
431
+ } else {
432
+ const parameters = closestLineParameters(target.origin, target.direction, ray.originMm, ray.direction);
433
+ if (!parameters) return refusal(constraint.query.generation, 'near-parallel', 'The pointer ray is parallel to the source segment.');
434
+ along = parameters.a;
435
+ }
436
+ if (along >= 0 && along <= target.size) return refusal(constraint.query.generation, 'outside-extent', 'Extension snapping only acquires beyond a source endpoint.');
437
+ const beyond = along < 0 ? -along : along - target.size;
438
+ if (beyond < MODEL_SNAP_LIMITS_V1.directionMinLength) {
439
+ return refusal(constraint.query.generation, 'outside-extent', 'Extension snapping only acquires a non-zero distance beyond an endpoint.');
440
+ }
441
+ const maximum = Math.min(target.size * MODEL_SNAP_LIMITS_V1.extensionSourceLengths, MODEL_SNAP_LIMITS_V1.extensionMaximumMm);
442
+ if (beyond > maximum) return refusal(constraint.query.generation, 'outside-extent', 'The requested extension exceeds the fixed safety extent.');
443
+ const point = add(target.origin, scale(target.direction, along));
444
+ const endpoint = along < 0 ? constraint.target.startMm : constraint.target.endMm;
445
+ return acquiredResult({ query: constraint.query, point,
446
+ guides: [{ type: 'segment', startMm: endpoint, endMm: point }], solverKind: 'extension', cameraPort });
447
+ }
448
+
449
+ /**
450
+ * Solve a provider-neutral contextual snap. The live ray is always read from the camera port; the
451
+ * serialised query ray is an audit receipt and is deliberately never used as runtime authority.
452
+ */
453
+ export function solveModelSnapConstraint(constraint, cameraPort) {
454
+ const ray = liveRay(constraint?.query, cameraPort);
455
+ if (!ray) return refusal(constraint?.query?.generation, 'stale', 'The active camera cannot provide a current canonical pointer ray.');
456
+ if (constraint.solverKind === 'perpendicular') return solvePerpendicular(constraint, cameraPort, ray);
457
+ if (constraint.solverKind === 'parallel') return solveParallel(constraint, cameraPort, ray);
458
+ if (constraint.solverKind === 'extension') return solveExtension(constraint, cameraPort, ray);
459
+ return refusal(constraint.query.generation, 'filtered', 'The requested contextual snap solver is not enabled.');
460
+ }
461
+
462
+ function withinLinearExtent(linear, amount, extentPolicy) {
463
+ return extentPolicy === 'infinite' || (amount >= linear.min - MODEL_SNAP_LIMITS_V1.workPlaneToleranceMm
464
+ && amount <= linear.max + MODEL_SNAP_LIMITS_V1.workPlaneToleranceMm);
465
+ }
466
+
467
+ /**
468
+ * Intersect two canonical linear primitives. The result is a session-derived
469
+ * intersection with both construction lines returned as visible guide primitives.
470
+ */
471
+ export function solveModelSnapIntersection({ query, left, right, workPlane = null, extentPolicy = 'finite' }, cameraPort) {
472
+ const a = linearPrimitive(left), b = linearPrimitive(right);
473
+ if (!a || !b) return refusal(query.generation, 'degenerate', 'Intersection snapping requires two non-degenerate lines or segments.');
474
+ const parameters = closestLineParameters(a.origin, a.direction, b.origin, b.direction);
475
+ if (!parameters) return refusal(query.generation, 'near-parallel', 'The target lines are parallel or too nearly parallel for a stable intersection.');
476
+ const pointA = add(a.origin, scale(a.direction, parameters.a));
477
+ const pointB = add(b.origin, scale(b.direction, parameters.b));
478
+ if (distance(pointA, pointB) > MODEL_SNAP_LIMITS_V1.workPlaneToleranceMm) {
479
+ return refusal(query.generation, 'work-plane', 'The target lines are skew and do not meet in one canonical point.');
480
+ }
481
+ if (!withinLinearExtent(a, parameters.a, extentPolicy) || !withinLinearExtent(b, parameters.b, extentPolicy)) {
482
+ return refusal(query.generation, 'outside-extent', 'The intersection lies outside a finite target segment.');
483
+ }
484
+ const point = midpoint(pointA, pointB);
485
+ if (query.mode === 'work-plane') {
486
+ if (!workPlane || !pointOnPlane(point, workPlane)
487
+ || Math.abs(dot(a.direction, workPlane.normal)) > MODEL_SNAP_LIMITS_V1.nearParallelCrossLength
488
+ || Math.abs(dot(b.direction, workPlane.normal)) > MODEL_SNAP_LIMITS_V1.nearParallelCrossLength) {
489
+ return refusal(query.generation, 'work-plane', 'The intersection does not lie on the active working plane.');
490
+ }
491
+ }
492
+ return acquiredResult({ query, point, kind: 'semantic-intersection', solverKind: 'intersection', cameraPort,
493
+ guides: [
494
+ { type: 'line', originMm: point, direction: a.direction },
495
+ { type: 'line', originMm: point, direction: b.direction },
496
+ ] });
497
+ }