@womp/spark-agent 1.0.1 → 2.1.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 (89) hide show
  1. package/README.md +42 -19
  2. package/dist/capabilities/health.d.ts +9 -0
  3. package/dist/capabilities/health.js +27 -0
  4. package/dist/capabilities/scene-draft.d.ts +2 -404
  5. package/dist/capabilities/scene.d.ts +1 -1
  6. package/dist/capabilities/scene.js +13 -4
  7. package/dist/capabilities.d.ts +3 -1
  8. package/dist/capabilities.js +1 -0
  9. package/dist/cli.js +20 -2
  10. package/dist/client.js +15 -15
  11. package/dist/coordinates.d.ts +23 -0
  12. package/dist/coordinates.js +132 -0
  13. package/dist/generated/health-declarations.d.ts +1 -0
  14. package/dist/generated/health-declarations.js +3 -0
  15. package/dist/generated/scene-declarations.d.ts +1 -1
  16. package/dist/generated/scene-declarations.js +1 -1
  17. package/dist/geometry/backendRegistry.d.ts +37 -0
  18. package/dist/geometry/backendRegistry.js +61 -0
  19. package/dist/geometry/common.d.ts +26 -0
  20. package/dist/geometry/common.js +78 -0
  21. package/dist/geometry/compiler.d.ts +35 -0
  22. package/dist/geometry/compiler.js +115 -0
  23. package/dist/geometry/graph.d.ts +39 -0
  24. package/dist/geometry/graph.js +32 -0
  25. package/dist/geometry/index.d.ts +9 -0
  26. package/dist/geometry/index.js +12 -0
  27. package/dist/geometry/lift.d.ts +7 -0
  28. package/dist/geometry/lift.js +376 -0
  29. package/dist/geometry/lower.d.ts +9 -0
  30. package/dist/geometry/lower.js +363 -0
  31. package/dist/geometry/parameters.d.ts +23 -0
  32. package/dist/geometry/parameters.js +46 -0
  33. package/dist/geometry/schemas/backend-schema.json +3394 -0
  34. package/dist/geometry/schemas/flowir-dialect.json +976 -0
  35. package/dist/geometry/writeParamData.d.ts +18 -0
  36. package/dist/geometry/writeParamData.js +47 -0
  37. package/dist/geometry.d.ts +10 -0
  38. package/dist/geometry.js +19 -0
  39. package/dist/index.d.ts +2 -0
  40. package/dist/index.js +2 -0
  41. package/dist/kakapo.d.ts +9 -5
  42. package/dist/kakapo.js +7 -6
  43. package/dist/openscad.d.ts +85 -0
  44. package/dist/openscad.js +223 -0
  45. package/dist/pricing.js +9 -29
  46. package/dist/repair-state.d.ts +50 -0
  47. package/dist/repair-state.js +96 -0
  48. package/dist/runtime.d.ts +16 -36
  49. package/dist/runtime.js +132 -139
  50. package/dist/scene-environment.d.ts +25 -0
  51. package/dist/scene-environment.js +76 -0
  52. package/dist/scene-health.d.ts +49 -0
  53. package/dist/scene-health.js +176 -0
  54. package/dist/scene-metadata.d.ts +6 -0
  55. package/dist/scene-metadata.js +65 -0
  56. package/dist/scene-operations.d.ts +47 -0
  57. package/dist/scene-operations.js +126 -0
  58. package/dist/sdk-geometry-host.d.ts +12 -0
  59. package/dist/sdk-geometry-host.js +306 -0
  60. package/dist/sdk-openscad-host.d.ts +14 -0
  61. package/dist/sdk-openscad-host.js +296 -0
  62. package/dist/sdk-openscad-renderer.d.ts +11 -0
  63. package/dist/sdk-openscad-renderer.js +71 -0
  64. package/dist/sdk-scene-health-host.d.ts +4 -0
  65. package/dist/sdk-scene-health-host.js +13 -0
  66. package/dist/sdk-scene-host.d.ts +312 -0
  67. package/dist/sdk-scene-host.js +202 -0
  68. package/dist/sdk-scene-screenshot.d.ts +7 -0
  69. package/dist/sdk-scene-screenshot.js +17 -0
  70. package/dist/server/demo-scene-materials.d.ts +3 -0
  71. package/dist/server/demo-scene-materials.js +18 -0
  72. package/dist/server/express.js +2 -4
  73. package/dist/server/fixtures/materials/matte-blue.json +14 -0
  74. package/dist/server/fixtures/materials/polished-copper.json +14 -0
  75. package/dist/server/index.d.ts +2 -1
  76. package/dist/server/index.js +2 -1
  77. package/dist/server/service.d.ts +4 -0
  78. package/dist/server/service.js +26 -2
  79. package/dist/server/sqlite-store.d.ts +31 -0
  80. package/dist/server/sqlite-store.js +224 -0
  81. package/dist/server/standalone.d.ts +14 -1
  82. package/dist/server/standalone.js +160 -27
  83. package/dist/server/store.js +3 -1
  84. package/dist/types.d.ts +1 -1
  85. package/dist/womp-scene-api.d.ts +283 -0
  86. package/dist/womp-scene-api.js +974 -0
  87. package/package.json +22 -10
  88. package/dist/kakapo-capability.d.ts +0 -45
  89. package/dist/kakapo-capability.js +0 -169
@@ -0,0 +1,306 @@
1
+ import { compileGeometry, migrateGraphExt, readEditableGeometry, } from "./geometry/compiler.js";
2
+ import { graphExtSchema } from "./geometry/graph.js";
3
+ import { migrateParameterOverrides, readParameterOverrides, } from "./geometry/parameters.js";
4
+ import { getSdkSceneAreaId, readStableSdkSceneHealth } from "./scene-health.js";
5
+ import { createGeometryRepairTracker, } from "./repair-state.js";
6
+ function errorMessage(error) {
7
+ return error instanceof Error ? error.message : String(error);
8
+ }
9
+ function unusedId(entries) {
10
+ let id = 0;
11
+ while (id in entries)
12
+ id++;
13
+ return id;
14
+ }
15
+ function scriptStorage(source) {
16
+ const scripts = source.getSceneStorage().scripts;
17
+ if (!scripts || typeof scripts !== "object" || Array.isArray(scripts))
18
+ return { graphs: {}, instances: {} };
19
+ const value = scripts;
20
+ return {
21
+ graphs: value.graphs && typeof value.graphs === "object"
22
+ ? value.graphs
23
+ : {},
24
+ instances: value.instances && typeof value.instances === "object"
25
+ ? value.instances
26
+ : {},
27
+ };
28
+ }
29
+ function objectIdsFor(source, instanceId) {
30
+ return source
31
+ .listNodes({ kind: "union" })
32
+ .filter((node) => node.kind === "union" && node.scriptInstanceId === instanceId)
33
+ .map((node) => node.id);
34
+ }
35
+ function resolveTarget(source, objectId) {
36
+ const node = source.getNode(objectId);
37
+ if (objectId !== 0 && node.kind !== "union" && node.kind !== "group")
38
+ throw new Error("Geometry Nodes requires an Area, Group, or scene root target.");
39
+ const instanceId = node.kind === "union" ? node.scriptInstanceId : undefined;
40
+ const scripts = scriptStorage(source);
41
+ const instance = instanceId === undefined ? undefined : scripts.instances[instanceId];
42
+ if (instanceId !== undefined && !instance)
43
+ throw new Error("The target's Geometry Nodes instance is missing. Inspect it before editing.");
44
+ const graphId = instance?.graph_id;
45
+ const graph = graphId === undefined ? undefined : scripts.graphs[graphId];
46
+ if (instance && (graph === undefined || !Number.isInteger(graphId)))
47
+ throw new Error("The target's Geometry Nodes graph is missing. Inspect it before editing.");
48
+ return { node, graph, graphId, instanceId, scripts };
49
+ }
50
+ async function readTarget(api, objectId, target = resolveTarget(api, objectId)) {
51
+ const result = {
52
+ kind: target.graphId === undefined ? "container" : "graph",
53
+ objectId,
54
+ title: target.node.name,
55
+ graphId: target.graphId,
56
+ instanceId: target.instanceId,
57
+ source: null,
58
+ instances: [],
59
+ revision: await api.getSceneRevision(),
60
+ diagnostics: [],
61
+ };
62
+ if (target.graphId === undefined || target.graph === undefined)
63
+ return result;
64
+ try {
65
+ const ext = graphExtSchema.parse(api.getSceneExt().graphsExt?.[target.graphId] ?? {});
66
+ const editable = readEditableGeometry(target.graph, ext);
67
+ result.source = editable.source;
68
+ for (const [id, instance] of Object.entries(target.scripts.instances)) {
69
+ if (instance.graph_id !== target.graphId)
70
+ continue;
71
+ const { params } = readParameterOverrides(editable.graph, ext, instance.data ?? {});
72
+ result.instances.push({
73
+ instanceId: Number(id),
74
+ objectIds: objectIdsFor(api, Number(id)),
75
+ params,
76
+ });
77
+ }
78
+ }
79
+ catch (error) {
80
+ result.source = null;
81
+ result.diagnostics.push(errorMessage(error));
82
+ }
83
+ return structuredClone(result);
84
+ }
85
+ function writeGraphStorage(draft, graphId, graph, instances) {
86
+ const scripts = draft.getSceneStorage().scripts;
87
+ if (!scripts || typeof scripts !== "object" || Array.isArray(scripts)) {
88
+ draft.patchSceneStorage([
89
+ {
90
+ op: "add",
91
+ path: "/scripts",
92
+ value: { graphs: {}, instances: {} },
93
+ },
94
+ ]);
95
+ }
96
+ else {
97
+ const record = scripts;
98
+ const additions = [];
99
+ if (!record.graphs)
100
+ additions.push({
101
+ op: "add",
102
+ path: "/scripts/graphs",
103
+ value: {},
104
+ });
105
+ if (!record.instances)
106
+ additions.push({
107
+ op: "add",
108
+ path: "/scripts/instances",
109
+ value: {},
110
+ });
111
+ if (additions.length)
112
+ draft.patchSceneStorage(additions);
113
+ }
114
+ draft.patchSceneStorage([
115
+ {
116
+ op: "add",
117
+ path: `/scripts/graphs/${graphId}`,
118
+ value: graph,
119
+ },
120
+ ...[...instances].map(([id, instance]) => ({
121
+ op: "add",
122
+ path: `/scripts/instances/${id}`,
123
+ value: instance,
124
+ })),
125
+ ]);
126
+ }
127
+ export function createSdkGeometryHost(options) {
128
+ const editor = options.editor;
129
+ const repairs = createGeometryRepairTracker(options.repairs, "geometry");
130
+ const pendingTargets = new Set();
131
+ return {
132
+ read: (objectId, invocation) => editor.read(invocation, (api) => readTarget(api, objectId)),
133
+ write: async (input, invocation) => {
134
+ invocation.signal.throwIfAborted();
135
+ const inspected = await editor.read(invocation, async (api) => {
136
+ const current = resolveTarget(api, input.objectId);
137
+ return {
138
+ target: await readTarget(api, input.objectId, current),
139
+ current,
140
+ graphExt: current.graphId === undefined
141
+ ? undefined
142
+ : api.getSceneExt().graphsExt?.[current.graphId],
143
+ };
144
+ });
145
+ const { target } = inspected;
146
+ const pendingKey = target.graphId === undefined
147
+ ? `object:${input.objectId}`
148
+ : `graph:${target.graphId}`;
149
+ if (pendingTargets.has(pendingKey))
150
+ throw new Error("This Geometry Nodes target is still being updated. Await its current update first.");
151
+ pendingTargets.add(pendingKey);
152
+ try {
153
+ if (target.revision !== input.expectedRevision)
154
+ throw new Error("The scene changed. Read it again before editing.");
155
+ const repairingGeometry = target.graphId !== undefined &&
156
+ (await repairs.isPending(String(target.graphId)));
157
+ if (target.graphId !== undefined)
158
+ await repairs.assertCanWrite(String(target.graphId));
159
+ const rejected = (diagnostics) => ({
160
+ status: "rejected",
161
+ objectId: input.objectId,
162
+ graphId: target.graphId,
163
+ instanceId: target.instanceId,
164
+ affectedObjectIds: [],
165
+ revision: target.revision,
166
+ diagnostics,
167
+ });
168
+ let compiled;
169
+ let nextExt;
170
+ const updates = new Map();
171
+ const diagnostics = [];
172
+ try {
173
+ compiled = compileGeometry(input.source);
174
+ readEditableGeometry(compiled.graph, compiled.graphExt);
175
+ if (target.graphId === undefined) {
176
+ nextExt = migrateGraphExt({ nodes: {} }, {}, compiled);
177
+ }
178
+ else {
179
+ const { current } = inspected;
180
+ if (current.graph === undefined)
181
+ throw new Error("The Geometry Nodes graph is missing.");
182
+ const ext = graphExtSchema.parse(inspected.graphExt ?? {});
183
+ const previous = readEditableGeometry(current.graph, ext);
184
+ nextExt = migrateGraphExt(ext, previous.nodeIds, compiled);
185
+ for (const [id, instance] of Object.entries(current.scripts.instances)) {
186
+ if (instance.graph_id !== target.graphId)
187
+ continue;
188
+ const old = readParameterOverrides(previous.graph, ext, instance.data ?? {});
189
+ const migrated = migrateParameterOverrides(previous.graph, ext, compiled.graph, nextExt, old.data);
190
+ updates.set(id, {
191
+ graph_id: target.graphId,
192
+ data: migrated.data,
193
+ });
194
+ if (migrated.removed.length)
195
+ diagnostics.push(`Instance ${id}: removed or type-changed overrides ${migrated.removed.join(", ")} now use graph defaults where present.`);
196
+ }
197
+ }
198
+ }
199
+ catch (error) {
200
+ return rejected([errorMessage(error)]);
201
+ }
202
+ if (repairingGeometry === false && options.canGrow?.() === false)
203
+ return rejected(["Scene memory limits prevent applying this graph."]);
204
+ const receiptTarget = {
205
+ objectId: input.objectId,
206
+ };
207
+ let operationId;
208
+ let applied;
209
+ try {
210
+ applied = await editor.edit({
211
+ capability: "geometry",
212
+ operation: "write",
213
+ target: () => receiptTarget,
214
+ }, async (_api, draft, id) => {
215
+ operationId = id;
216
+ const current = resolveTarget(draft, input.objectId);
217
+ if (repairingGeometry === false && options.canGrow?.() === false)
218
+ throw new Error("Scene memory limits prevent applying this graph.");
219
+ if (current.graphId !== target.graphId)
220
+ throw new Error("The Geometry Nodes target changed. Read it again.");
221
+ if (current.graphId !== undefined)
222
+ await repairs.reserve(String(current.graphId), id);
223
+ let objectId = input.objectId;
224
+ let graphId = current.graphId;
225
+ let instanceId = current.instanceId;
226
+ const nextInstances = new Map(updates);
227
+ if (graphId === undefined) {
228
+ graphId = unusedId(current.scripts.graphs);
229
+ instanceId = unusedId(current.scripts.instances);
230
+ if (objectId === 0 || current.node.kind !== "union") {
231
+ objectId = draft.createNode({
232
+ kind: "union",
233
+ parentId: objectId,
234
+ name: "Area",
235
+ }).id;
236
+ }
237
+ draft.updateNode(objectId, { scriptInstanceId: instanceId });
238
+ nextInstances.set(String(instanceId), {
239
+ graph_id: graphId,
240
+ data: {},
241
+ });
242
+ }
243
+ writeGraphStorage(draft, graphId, compiled.graph, nextInstances);
244
+ const ext = draft.getSceneExt();
245
+ if (!ext.graphsExt)
246
+ draft.patchSceneExt([
247
+ { op: "add", path: "/graphsExt", value: {} },
248
+ ]);
249
+ draft.patchSceneExt([
250
+ {
251
+ op: "add",
252
+ path: `/graphsExt/${graphId}`,
253
+ value: nextExt,
254
+ },
255
+ ]);
256
+ const affectedObjectIds = Object.entries(scriptStorage(draft).instances)
257
+ .filter(([, instance]) => instance.graph_id === graphId)
258
+ .flatMap(([id]) => objectIdsFor(draft, Number(id)));
259
+ Object.assign(receiptTarget, { objectId, graphId, instanceId });
260
+ return { objectId, graphId, instanceId, affectedObjectIds };
261
+ }, input.expectedRevision, invocation, async (_operation, api) => {
262
+ const committed = resolveTarget(api, receiptTarget.objectId);
263
+ if (committed.graphId === undefined)
264
+ return;
265
+ const affectedObjectIds = Object.entries(committed.scripts.instances)
266
+ .filter(([, instance]) => instance.graph_id === committed.graphId)
267
+ .flatMap(([id]) => objectIdsFor(api, Number(id)));
268
+ const areaIds = [
269
+ ...new Set(affectedObjectIds.map((id) => getSdkSceneAreaId(api, id))),
270
+ ];
271
+ const sceneHealth = await readStableSdkSceneHealth(api, areaIds, invocation.signal);
272
+ options.onHealth?.(sceneHealth);
273
+ const recorded = await repairs.record(String(committed.graphId), _operation.id, sceneHealth);
274
+ return {
275
+ sceneHealth,
276
+ geometryRepairAttempts: recorded.repairAttempts,
277
+ geometryRepairLimit: recorded.repairLimit,
278
+ };
279
+ });
280
+ }
281
+ catch (error) {
282
+ if (operationId !== undefined && target.graphId !== undefined) {
283
+ const operation = await editor.getOperation(operationId);
284
+ if (operation?.status === "rolled_back")
285
+ await repairs.refund(String(target.graphId), operationId);
286
+ }
287
+ throw error;
288
+ }
289
+ invocation.signal.throwIfAborted();
290
+ try {
291
+ await options.onSelect?.(applied.value.objectId);
292
+ }
293
+ catch { }
294
+ return {
295
+ status: "applied",
296
+ ...applied.value,
297
+ revision: applied.operation.resultRevision ?? input.expectedRevision,
298
+ diagnostics,
299
+ };
300
+ }
301
+ finally {
302
+ pendingTargets.delete(pendingKey);
303
+ }
304
+ },
305
+ };
306
+ }
@@ -0,0 +1,14 @@
1
+ import type { OpenScadHost } from "./capabilities.js";
2
+ import { type SdkSceneEditor } from "./sdk-scene-host.js";
3
+ import { type OpenScadPrintabilityRequest, type OpenScadPrintabilityResult } from "./openscad.js";
4
+ import { type RepairStateStore } from "./repair-state.js";
5
+ import { type SceneHealth } from "./scene-health.js";
6
+ export type SdkOpenScadHostOptions = {
7
+ editor: SdkSceneEditor;
8
+ repairs: RepairStateStore;
9
+ canGrow?: () => boolean;
10
+ onHealth?: (health: SceneHealth) => void;
11
+ onSelect?: (objectId: number) => void | Promise<void>;
12
+ requestPrintability?: (request: OpenScadPrintabilityRequest) => Promise<OpenScadPrintabilityResult>;
13
+ };
14
+ export declare function createSdkOpenScadHost(options: SdkOpenScadHostOptions): OpenScadHost;
@@ -0,0 +1,296 @@
1
+ import { z } from "zod";
2
+ import { getOpenScadGroundedPosition, MAX_PRINTABILITY_REPAIR_ATTEMPTS, requestStableOpenScadPrintability, toOpenScadCompileResponse, } from "./openscad.js";
3
+ import { waitForOpenScadRenderer } from "./sdk-openscad-renderer.js";
4
+ import { createGeometryRepairTracker, createRepairTracker, } from "./repair-state.js";
5
+ import { getSdkSceneAreaId, hasGeometryOverflow, readStableSdkSceneHealth, unverifiedSceneHealth, } from "./scene-health.js";
6
+ const compileMetadata = z.object({
7
+ error: z.string(),
8
+ params: z.array(z.object({ name: z.string() })),
9
+ });
10
+ function linkedObjectIds(api, scriptId) {
11
+ return api
12
+ .listNodes({ kind: "openScad" })
13
+ .filter((node) => node.kind === "openScad" && node.scriptId === scriptId)
14
+ .map((node) => node.id);
15
+ }
16
+ export function createSdkOpenScadHost(options) {
17
+ const editor = options.editor;
18
+ const geometryRepairs = createGeometryRepairTracker(options.repairs, "openscad.geometry");
19
+ const printabilityRepairs = createRepairTracker(options.repairs, "openscad.printability", MAX_PRINTABILITY_REPAIR_ATTEMPTS, (status) => status === "unavailable" ? undefined : status === "failed");
20
+ const pendingTargets = new Set();
21
+ const resolveTarget = async (api, objectId) => {
22
+ const revision = await api.getSceneRevision();
23
+ const node = objectId === 0 ? undefined : api.getNode(objectId);
24
+ if (objectId === 0 || node?.kind === "union" || node?.kind === "group") {
25
+ return {
26
+ target: {
27
+ kind: "container",
28
+ objectId,
29
+ parentId: node?.parentId ?? 0,
30
+ title: node?.name ?? "",
31
+ source: null,
32
+ params: {},
33
+ revision,
34
+ },
35
+ };
36
+ }
37
+ if (node?.kind !== "openScad")
38
+ throw new Error("The target must be an OpenSCAD part or an Area/Group.");
39
+ const script = api.getOpenScadScript(node.scriptId);
40
+ let rendererBounds;
41
+ try {
42
+ rendererBounds = await api.getNodeBoundingBox(objectId);
43
+ }
44
+ catch { }
45
+ return {
46
+ target: {
47
+ kind: "part",
48
+ objectId,
49
+ parentId: node.parentId ?? 0,
50
+ source: script.source,
51
+ title: script.name || node.name || "OpenSCAD part",
52
+ params: structuredClone(node.params ?? {}),
53
+ revision,
54
+ },
55
+ repairKey: `script:${node.scriptId}`,
56
+ rendererBounds,
57
+ };
58
+ };
59
+ const write = async (source, targetId, creating, invocation) => {
60
+ invocation.signal.throwIfAborted();
61
+ const resolved = await editor.read(invocation, (api) => resolveTarget(api, targetId));
62
+ const { target } = resolved;
63
+ const pendingKey = resolved.repairKey ?? `container:${targetId}`;
64
+ if (pendingTargets.has(pendingKey))
65
+ throw new Error("This part is still being compiled or checked. Await its current update first.");
66
+ pendingTargets.add(pendingKey);
67
+ let objectId = creating ? undefined : targetId;
68
+ let operationId = "";
69
+ let operationRepairKey = resolved.repairKey;
70
+ try {
71
+ if (target.revision !== source.expectedRevision)
72
+ throw new Error("The scene changed. Read it again before editing.");
73
+ if (target.kind !== (creating ? "container" : "part"))
74
+ throw new Error(creating
75
+ ? "Creation requires a parent container ID."
76
+ : "Update requires an existing OpenSCAD object ID.");
77
+ let repairingGeometry = false;
78
+ if (creating === false) {
79
+ if (resolved.repairKey === undefined)
80
+ throw new Error("The OpenSCAD repair target is unavailable.");
81
+ repairingGeometry = await geometryRepairs.isPending(resolved.repairKey);
82
+ await geometryRepairs.assertCanWrite(resolved.repairKey);
83
+ if (repairingGeometry === false)
84
+ await printabilityRepairs.assertCanWrite(resolved.repairKey);
85
+ }
86
+ if (creating && options.canGrow?.() === false)
87
+ throw new Error("OpenSCAD creation is disabled because scene memory is low.");
88
+ const params = z
89
+ .record(z.string(), z.json())
90
+ .parse({ ...target.params, ...source.params });
91
+ invocation.reportStatus("running", "Compiling the parametric part...");
92
+ let rawValidation;
93
+ try {
94
+ rawValidation = await editor.read(invocation, (api) => api.validateOpenScad(source.source, params));
95
+ }
96
+ catch {
97
+ invocation.signal.throwIfAborted();
98
+ }
99
+ const response = toOpenScadCompileResponse(rawValidation);
100
+ const metadataAvailable = compileMetadata.safeParse(rawValidation).success;
101
+ const validation = response && (response.error || metadataAvailable)
102
+ ? {
103
+ status: response.error ? "invalid" : "valid",
104
+ error: response.error || undefined,
105
+ warnings: response.warnings,
106
+ }
107
+ : {
108
+ status: "unavailable",
109
+ warnings: [
110
+ "OpenSCAD validation is unavailable; compilation and parameter validity could not be confirmed.",
111
+ ],
112
+ };
113
+ if (validation.status === "invalid" ||
114
+ (creating &&
115
+ (validation.status !== "valid" ||
116
+ response?.boundingBox === undefined))) {
117
+ if (creating && response?.boundingBox === undefined)
118
+ validation.warnings.push("The part was not added because validated placement bounds are unavailable.");
119
+ return {
120
+ status: "rejected",
121
+ objectId,
122
+ revision: target.revision,
123
+ validation,
124
+ repairAttempts: 0,
125
+ repairLimit: MAX_PRINTABILITY_REPAIR_ATTEMPTS,
126
+ };
127
+ }
128
+ const validNames = new Set(response && metadataAvailable
129
+ ? response.params.map((param) => param.name)
130
+ : Object.keys(params));
131
+ const nextParams = Object.fromEntries(Object.entries(params).filter(([name]) => validNames.has(name)));
132
+ const receiptTarget = {
133
+ parentId: target.parentId,
134
+ };
135
+ if (objectId !== undefined)
136
+ receiptTarget.objectId = objectId;
137
+ let affectedObjectIds = [];
138
+ let sceneHealth;
139
+ const applied = await editor.edit({
140
+ capability: "openscad",
141
+ operation: creating ? "create" : "update",
142
+ target: () => receiptTarget,
143
+ }, async (_api, draft, id) => {
144
+ operationId = id;
145
+ if (creating === false) {
146
+ if (resolved.repairKey === undefined)
147
+ throw new Error("The OpenSCAD repair target is unavailable.");
148
+ await geometryRepairs.reserve(resolved.repairKey, id);
149
+ if (repairingGeometry === false)
150
+ await printabilityRepairs.reserve(resolved.repairKey, id);
151
+ const node = draft.getNode(targetId);
152
+ if (node.kind !== "openScad")
153
+ throw new Error("The OpenSCAD target no longer exists.");
154
+ affectedObjectIds = linkedObjectIds(draft, node.scriptId);
155
+ draft.updateOpenScadScript(node.scriptId, {
156
+ name: source.title,
157
+ source: source.source,
158
+ });
159
+ draft.setNodeName(targetId, source.title);
160
+ draft.setOpenScadScript(targetId, node.scriptId, nextParams);
161
+ return { objectId: targetId, repairKey: resolved.repairKey };
162
+ }
163
+ if (options.canGrow?.() === false)
164
+ throw new Error("OpenSCAD creation is disabled because scene memory is low.");
165
+ let parentId = targetId;
166
+ if (targetId === 0 || draft.getNode(targetId).kind === "group")
167
+ parentId = draft.createNode({
168
+ kind: "union",
169
+ parentId: targetId,
170
+ name: "Area",
171
+ }).id;
172
+ const script = draft.createOpenScadScript(source.title, source.source);
173
+ operationRepairKey = `script:${script.id}`;
174
+ const node = draft.createNode({
175
+ kind: "openScad",
176
+ parentId,
177
+ name: source.title,
178
+ properties: {
179
+ scriptId: script.id,
180
+ params: nextParams,
181
+ transform: {
182
+ position: getOpenScadGroundedPosition(response?.boundingBox),
183
+ },
184
+ },
185
+ });
186
+ objectId = node.id;
187
+ affectedObjectIds = [node.id];
188
+ Object.assign(receiptTarget, { objectId: node.id, parentId });
189
+ return { objectId: node.id, repairKey: operationRepairKey };
190
+ }, source.expectedRevision, invocation, async (operation, api) => {
191
+ if (objectId === undefined)
192
+ return;
193
+ const areaIds = [
194
+ ...new Set(affectedObjectIds.map((id) => getSdkSceneAreaId(api, id))),
195
+ ];
196
+ try {
197
+ const rendererReady = response?.boundingBox === undefined ||
198
+ (creating === false && resolved.rendererBounds === undefined)
199
+ ? false
200
+ : await waitForOpenScadRenderer({
201
+ api,
202
+ objectId,
203
+ expectedBounds: response.boundingBox,
204
+ baselineBounds: resolved.rendererBounds,
205
+ signal: invocation.signal,
206
+ });
207
+ sceneHealth = rendererReady
208
+ ? await readStableSdkSceneHealth(api, areaIds, invocation.signal)
209
+ : unverifiedSceneHealth(areaIds, "The renderer did not confirm the committed OpenSCAD geometry before health checks.");
210
+ }
211
+ catch (error) {
212
+ sceneHealth = unverifiedSceneHealth(areaIds, `OpenSCAD renderer checks stopped after the edit committed: ${String(error)}`);
213
+ }
214
+ options.onHealth?.(sceneHealth);
215
+ if (operationRepairKey === undefined)
216
+ return;
217
+ const recorded = await geometryRepairs.record(operationRepairKey, operation.id, sceneHealth);
218
+ return {
219
+ sceneHealth,
220
+ affectedObjectIds,
221
+ geometryRepairAttempts: recorded.repairAttempts,
222
+ geometryRepairLimit: recorded.repairLimit,
223
+ };
224
+ });
225
+ objectId = applied.value.objectId;
226
+ try {
227
+ await options.onSelect?.(objectId);
228
+ }
229
+ catch { }
230
+ const revision = applied.operation.resultRevision ?? source.expectedRevision;
231
+ if (sceneHealth?.status === "unverified" ||
232
+ (sceneHealth !== undefined && hasGeometryOverflow(sceneHealth))) {
233
+ await printabilityRepairs.refund(applied.value.repairKey, operationId);
234
+ return {
235
+ status: "applied",
236
+ objectId,
237
+ revision,
238
+ validation,
239
+ repairAttempts: 0,
240
+ repairLimit: MAX_PRINTABILITY_REPAIR_ATTEMPTS,
241
+ };
242
+ }
243
+ invocation.reportStatus("running", "Checking wall thickness...");
244
+ const printability = await editor.read(invocation, (api, beginSettlement) => (options.requestPrintability ?? requestStableOpenScadPrintability)({
245
+ api,
246
+ expectedRevision: revision,
247
+ signal: invocation.signal,
248
+ onSubmissionStarted: beginSettlement,
249
+ objectIds: [
250
+ ...new Set(affectedObjectIds.map((id) => Number(getSdkSceneAreaId(api, id)))),
251
+ ],
252
+ }));
253
+ invocation.signal.throwIfAborted();
254
+ if (printability.reason === "context_busy") {
255
+ const refunded = await printabilityRepairs.refund(applied.value.repairKey, operationId);
256
+ return {
257
+ status: "applied",
258
+ objectId,
259
+ revision,
260
+ validation,
261
+ printability,
262
+ repairAttempts: refunded.repairAttempts,
263
+ repairLimit: refunded.repairLimit,
264
+ };
265
+ }
266
+ const recorded = await printabilityRepairs.record(applied.value.repairKey, operationId, printability.status);
267
+ return {
268
+ status: "applied",
269
+ objectId,
270
+ revision,
271
+ validation,
272
+ printability,
273
+ repairAttempts: recorded.repairAttempts,
274
+ repairLimit: recorded.repairLimit,
275
+ };
276
+ }
277
+ catch (error) {
278
+ if (creating === false && operationId !== "") {
279
+ const operation = await editor.getOperation(operationId);
280
+ if (operation?.status === "rolled_back") {
281
+ await geometryRepairs.refund(resolved.repairKey, operationId);
282
+ await printabilityRepairs.refund(resolved.repairKey, operationId);
283
+ }
284
+ }
285
+ throw error;
286
+ }
287
+ finally {
288
+ pendingTargets.delete(pendingKey);
289
+ }
290
+ };
291
+ return {
292
+ read: (objectId, invocation) => editor.read(invocation, async (api) => (await resolveTarget(api, objectId)).target),
293
+ create: (source, invocation) => write(source, source.parentId, true, invocation),
294
+ update: (source, invocation) => write(source, source.objectId, false, invocation),
295
+ };
296
+ }
@@ -0,0 +1,11 @@
1
+ import type { KakapoAPI } from "@womp/kakapo-sdk";
2
+ import type { OpenScadBoundingBox } from "./openscad.js";
3
+ export declare function waitForOpenScadRenderer(options: {
4
+ api: KakapoAPI;
5
+ objectId: number;
6
+ expectedBounds: OpenScadBoundingBox;
7
+ baselineBounds?: OpenScadBoundingBox;
8
+ signal: AbortSignal;
9
+ timeoutMs?: number;
10
+ pollIntervalMs?: number;
11
+ }): Promise<boolean>;