@womp/spark-agent 4.4.1 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +23 -2
  2. package/dist/capabilities/geometry.d.ts +0 -3
  3. package/dist/capabilities/geometry.js +7 -8
  4. package/dist/capabilities/openscad-instructions.d.ts +1 -1
  5. package/dist/capabilities/openscad-instructions.js +80 -81
  6. package/dist/capabilities/openscad.d.ts +0 -3
  7. package/dist/capabilities/openscad.js +1 -2
  8. package/dist/capabilities/scene.d.ts +2 -6
  9. package/dist/capabilities/scene.js +44 -45
  10. package/dist/generated/geometry-declarations.d.ts +1 -1
  11. package/dist/generated/geometry-declarations.js +1 -1
  12. package/dist/generated/openscad-declarations.d.ts +1 -1
  13. package/dist/generated/openscad-declarations.js +1 -1
  14. package/dist/generated/scene-declarations.d.ts +1 -1
  15. package/dist/generated/scene-declarations.js +1 -1
  16. package/dist/native-executor.js +2 -2
  17. package/dist/openscad.d.ts +1 -2
  18. package/dist/openscad.js +1 -19
  19. package/dist/quickjs-executor.js +1 -1
  20. package/dist/repair-state.d.ts +2 -0
  21. package/dist/repair-state.js +15 -0
  22. package/dist/runtime.d.ts +1 -5
  23. package/dist/runtime.js +8 -14
  24. package/dist/scene-environment.js +1 -1
  25. package/dist/scene-health.d.ts +1 -2
  26. package/dist/scene-health.js +0 -17
  27. package/dist/scene-operations.d.ts +5 -5
  28. package/dist/scene-operations.js +24 -43
  29. package/dist/sdk-geometry-host.d.ts +2 -2
  30. package/dist/sdk-geometry-host.js +44 -61
  31. package/dist/sdk-openscad-host.js +63 -102
  32. package/dist/sdk-scene-health-host.d.ts +2 -1
  33. package/dist/sdk-scene-health-host.js +54 -4
  34. package/dist/sdk-scene-host.d.ts +20 -5
  35. package/dist/sdk-scene-host.js +34 -31
  36. package/dist/sdk-scene-screenshot.d.ts +1 -1
  37. package/dist/sdk-scene-screenshot.js +4 -3
  38. package/dist/server/scene-access.d.ts +4 -0
  39. package/dist/server/scene-access.js +40 -0
  40. package/dist/server/standalone.js +24 -19
  41. package/dist/womp-scene-api.d.ts +15 -0
  42. package/dist/womp-scene-api.js +18 -1
  43. package/package.json +139 -139
  44. package/dist/server/scene-initialization.d.ts +0 -3
  45. package/dist/server/scene-initialization.js +0 -44
package/README.md CHANGED
@@ -6,7 +6,25 @@ Spark Agent uses AI SDK 7 `UIMessage` and `UIMessageChunk` as its public chat pr
6
6
  JavaScript uses the host's executor and capabilities. Native browser execution and isolated QuickJS
7
7
  execution use the same model loop. The host owns conversations, artifacts, authorization, and connections.
8
8
 
9
- ## Requirements
9
+ ## Requirements
10
+
11
+ ### Migrating to 5.0
12
+
13
+ - Replace scene capability `read`/`edit` with `access(callback)`. Inspect the current draft
14
+ through `scene.nodes({ ids, name, type, parentId, offset, limit })`, not a `nodes` array.
15
+ Results default to 100, with a maximum page size of 1,000.
16
+ - Update custom scene hosts to `SceneHost.access` and SDK adapters to `acquireAccess`.
17
+ `onCommitted` receives the acknowledged scene; keep host access suspended until synchronization succeeds.
18
+ - Remove scene revision arguments from Geometry/OpenSCAD writes. Current parameters and overrides
19
+ are prepared inside protected access. Hosts must still enforce connection/project ownership.
20
+ - Screenshot calls without options capture the current native viewport. Explicit `camera`
21
+ position/target, projection, `horizontalFovDegrees` and `orthographicWidth` are supported;
22
+ remove `targetId` and `view` presets. Camera distances use current project units.
23
+ - Scene health is explicitly requested through `scene.health()`, not automatically after each edit.
24
+ - This release requires Kakapo SDK 0.7.0. Native and QuickJS executors now allow 100,000 host calls
25
+ per execution. Receipts, cancellation, timeout limits and uncertain-outcome handling remain enforced.
26
+
27
+ ### Runtime
10
28
 
11
29
  - Node.js 22.13 or newer
12
30
  - AI SDK 7
@@ -339,7 +357,10 @@ The standalone host uses a fresh QuickJS runtime for each JavaScript execution.
339
357
  or browser globals and receives only the composed capability APIs. Imports, filesystem access,
340
358
  network APIs, and host environment variables are not exposed. QuickJS limits memory, stack size,
341
359
  execution time, source size, host calls, and data crossing the host bridge. Browser hosts can instead
342
- choose native page execution, with the page-global access and interruption limitations described above.
360
+ choose native page execution, with the page-global access and interruption limitations described above.
361
+ Both executors allow 100,000 host calls per execution by default; the counter resets for each
362
+ execution. QuickJS supports overriding this through `maxHostCalls`. Cancellation, timeouts,
363
+ and the other execution limits still apply.
343
364
 
344
365
  QuickJS isolates generated code from the JavaScript host API; it is not an operating-system security
345
366
  boundary. Multi-tenant deployments must additionally isolate workers, authorize every Kakapo
@@ -17,13 +17,11 @@ export type GeometryTarget = {
17
17
  instanceId?: number;
18
18
  source: string | null;
19
19
  instances: GeometryInstance[];
20
- revision: string;
21
20
  diagnostics: string[];
22
21
  };
23
22
  export type GeometryWrite = {
24
23
  objectId: number;
25
24
  source: string;
26
- expectedRevision: string;
27
25
  };
28
26
  export type GeometryWriteResult = {
29
27
  status: "applied" | "rejected";
@@ -31,7 +29,6 @@ export type GeometryWriteResult = {
31
29
  graphId?: number;
32
30
  instanceId?: number;
33
31
  affectedObjectIds: number[];
34
- revision: string;
35
32
  diagnostics: string[];
36
33
  };
37
34
  export type WompGeometryApi = {
@@ -5,7 +5,6 @@ const write = z
5
5
  .object({
6
6
  objectId,
7
7
  source: z.string().trim().min(1),
8
- expectedRevision: z.string().min(1),
9
8
  })
10
9
  .strict();
11
10
  export function createGeometryCapability(host, reference) {
@@ -15,26 +14,26 @@ export function createGeometryCapability(host, reference) {
15
14
  name: "geometry-nodes",
16
15
  version: "5",
17
16
  description: "Create and edit visual Geometry Nodes graphs with adjustable parameters and animation.",
18
- instructions: `Use womp.geometry for requested Geometry Nodes, parametric organic/procedural geometry, or animation.
17
+ instructions: `Use womp.geometry for requested Geometry Nodes, parametric organic/procedural geometry, or animation.
19
18
  Keep follow-up edits to an existing Geometry Nodes object in its graph, preserving its adjustable parameters and instances.
20
19
  Read the target after any scene edit this build needs. read(0) reads the scene root as a creation container.
21
20
  write updates an existing shared graph, attaches a new graph to an Area without one, or creates a new Area beneath the root/Group target. Use the returned objectId for follow-up edits.
22
- Read geometry-nodes-reference before writing source. Supply the complete FlowIR text and the exact revision returned by the latest read. JavaScript calls execute JavaScript; source is a FlowIR string, not JavaScript or JSON.
23
- After a stale revision rejection, read the latest graph and adapt the edit while preserving intervening user changes. Ask only when the edits conflict or remain ambiguous; never retry the old replacement with a refreshed revision token.
21
+ Read geometry-nodes-reference before writing source. Supply the complete FlowIR text after inspecting the target. JavaScript calls execute JavaScript; source is a FlowIR string, not JavaScript or JSON.
22
+ Inspect the current target before replacing its graph; preserve unrelated geometry and parameter overrides.
24
23
  If source is null and diagnostics are present, the existing graph cannot be edited without loss. Explain the limitation; never treat it as empty or create a replacement to bypass the refusal.
25
24
  Preserve unrelated statements, parameter names, and FlowIR node IDs from the read. Shared graph edits affect all listed instances; report the affected objects. Valid overrides migrate by parameter name and type. Removed or type-changed parameters return to graph defaults and are reported.
26
25
  Use min/max/step for naturally bounded parameters and omit ranges for free-form positions/rotations. Meaningful parameter names become editor labels. Do not invent label fields.
27
26
  SetMaterial assigns one scene material to every primitive it receives. Its Material input is a scene material ID, not a color; 0 selects the scene default material.
28
- Obtain that ID from the scene-editing skill inside one scene.edit, where those lookups live: materialList with materialGetName and materialGetColor to reuse an existing material, materialCreate with materialSetColor and materialSetName for a new one, or listSuperMaterials with materialImport for a library material. Prefer reusing a material that already matches the request over creating another, and do not recolor a shared material unless every object using it should change.
29
- A scene edit changes the scene revision, so create or import the material before reading the geometry target, then write, all within one JavaScript call. Each call has a fresh scope and cannot read an earlier call's variables.
27
+ Obtain that ID from the scene-editing skill inside one scene.access, where those lookups live: materialList with materialGetName and materialGetColor to reuse an existing material, materialCreate with materialSetColor and materialSetName for a new one, or listSuperMaterials with materialImport for a library material. Prefer reusing a material that already matches the request over creating another, and do not recolor a shared material unless every object using it should change.
28
+ Create or import the material inside scene.access before writing the geometry target, all within one JavaScript call. Each call has a fresh scope and cannot read an earlier call's variables.
30
29
  Positions and sizes are millimetres; Boolean Blend uses the conversion in geometry-nodes-reference. Coordinates are right-handed, +X right, +Y up, +Z forward. Rotations are degrees, intrinsic X-Z-Y.
31
30
  On compiler errors, repair the source in this same conversation and retry with a fresh read. A rejected write made no change. Committed/unknown effects remain in execution receipts even if a later call fails; inspect before retrying.
32
31
  After applying, read the returned object and use the scene screenshot API with emitImage to inspect the applied result.`,
33
32
  declarations: WOMP_GEOMETRY_DECLARATIONS,
34
33
  examples: [
35
34
  "const target = await womp.geometry.read(objectId); print(target);",
36
- "const target = await womp.geometry.read(objectId); print(await womp.geometry.write({ objectId: target.objectId, source: editedFlowIR, expectedRevision: target.revision }));",
37
- "const materialId = await womp.scene.edit(scene => { const id = scene.materialCreate(); scene.materialSetName(id, 'Red'); scene.materialSetColor(id, { r: 255, g: 0, b: 0 }); return id; }, (await womp.scene.read()).revision); const target = await womp.geometry.read(0); const source = ['param Float size = 20.0 min=1 max=100 step=1', 'node box Primitive Type=Cube Position=Vec3(0.0,0.0,0.0) Rotation=Vec3(0.0,0.0,0.0) Size=size Roundness=0.0', `node painted SetMaterial Material=${materialId} Geometry=box.Geometry`, 'out Geometry=painted.Geometry'].join('\\n'); print(await womp.geometry.write({ objectId: target.objectId, source, expectedRevision: target.revision }));",
35
+ "const target = await womp.geometry.read(objectId); print(await womp.geometry.write({ objectId: target.objectId, source: editedFlowIR }));",
36
+ "const materialId = await womp.scene.access(scene => { const id = scene.materialCreate(); scene.materialSetName(id, 'Red'); scene.materialSetColor(id, { r: 255, g: 0, b: 0 }); return id; }); const target = await womp.geometry.read(0); const source = ['param Float size = 20.0 min=1 max=100 step=1', 'node box Primitive Type=Cube Position=Vec3(0.0,0.0,0.0) Rotation=Vec3(0.0,0.0,0.0) Size=size Roundness=0.0', `node painted SetMaterial Material=${materialId} Geometry=box.Geometry`, 'out Geometry=painted.Geometry'].join('\\n'); print(await womp.geometry.write({ objectId: target.objectId, source }));",
38
37
  ],
39
38
  },
40
39
  {
@@ -1 +1 @@
1
- export declare const OPENSCAD_INSTRUCTIONS = "Use womp.openscad to create or update one adjustable CAD part. Read an existing part before editing it.\nKeep follow-up edits to an existing CAD part in that part unless the user asks to change representation.\nread(0) returns the root container and a scene revision for creation. read(id) returns an existing\npart or container. Use the scene-editing skill when available to discover other scene objects.\ncreate requires a parentId (0 means the scene root); update requires the existing objectId.\nBoth methods compile the effective source and parameters, apply one undoable change, and check wall thickness.\nA stale revision requires reading again and adapting the edit while preserving intervening user changes.\nAsk the user only when the intended edits conflict or remain ambiguous; never reuse the old replacement\nwith a refreshed revision token. Existing overrides are preserved for parameters still present;\nparams supplies overrides to merge into the current values. Keep top-level parameter names stable.\nReturn complete source on every update and preserve unrelated geometry. Never create a replacement to repair a part.\nCompile errors return status rejected without applying. Creation requires validated placement bounds.\nAn update may apply with validation unavailable; that is a diagnostic, not proof that it compiles.\nAn applied part remains in the scene even if thickness fails or is unavailable. Use the returned objectId for repairs.\nWhen thickness fails, increase thin walls and fragile connections while preserving requested dimensions and openings.\nAt most four applied printability repairs are allowed per logical build/edit in this run. Respect the returned limit;\ndo not bypass it by recreating the part. Unavailable thickness is not a pass. Report unresolved issues honestly.\nBuild connected geometry and avoid features below 1.4 mm. OpenSCAD source dimensions use millimetres,\nindependently of the scene display unit. New parts are centered and grounded from compiled bounds.\nOpenSCAD is Z-up; the scene-editing API is Y-up. For an unrotated part at its creation-time scale and an identity parent transform,\na source point [x,y,z] mm maps to scene {x:y, y:z, z:-x} times the unitMultiplier returned by scene.read(), plus nodeGetPos(partId).\nAccount for the part and parent transforms when they are not identity; source coordinates are not scene coordinates.\nAfter a major change, use the scene screenshot API and emitImage to inspect the applied result.\nA committed effect can survive later failure. Inspect receipts and the existing part before retrying.\nDo not print source in the final answer unless requested; describe the result and any unresolved diagnostics.\n\nRUNTIME\n- Produce a single OpenSCAD file.\n- Do not use imports, includes, external libraries, text, hull, minkowski, polyhedron, or extrudes.\n- Prefer cube, sphere, cylinder, translate, rotate, color, union, difference, and intersection.\n- Do not use $fn, $fa, or $fs; tessellation controls are ignored.\n- Build faceted geometry by combining supported primitives with CSG operations and transforms.\n- Do not use scale(); size primitives directly instead.\n- Use color(\"#rrggbb\") around distinct visible parts.\n- Keep the model centered near the origin and use millimeter-like units consistently.\n- For organic blending, use goop(radius_mm) { ... }. The radius is in millimetres before parent scaling, matching scene-editing; do not multiply by project unitMultiplier. It is ordered: the first child seeds with blend 0, and each later child uses radius_mm.\n- Put core primitives first. Avoid wrapping goop children in union() when they should blend individually.\n\nSCREWS AND THREADS\n- Copy helical_ridge below for rounded screw threads, necks, caps, and coils. It joins spheres with cylinders; never use stacked rings or disconnected spheres.\n- Dimensions are mm: radius = ridge centerline radius; pitch = axial travel/turn; tube_radius = half ridge thickness; handedness = 1 (right) or -1 (left).\n- For a hand control use thread_hand = 1; // [-1:Left, 1:Right] and pass it directly. Ternary expressions (?:) are unsupported.\n- Embed the ridge in the shaft/neck (e.g. radius = shaft_radius). Hollow fittings: subtract the bore from body + thread. Internal threads: subtract the helix from the socket wall with mating clearance. Mating parts need matching pitch and handedness.\n- Expose diameter, pitch, thread length, and thickness in Customizer; derive sampling. Keep 2 * tube_radius < pitch and allow tube_radius beyond both path endpoints for rounded ends. This is a rounded profile, not ISO/metric V-thread; never claim standards compliance.\n- Build heads/grips separately using cylinders, tapered cylinders, and radial ribs/cutters, not thread samples.\n\nmodule helical_ridge(radius, pitch, turns, tube_radius, handedness) {\n if (radius > 0 && pitch > 0 && turns > 0 && tube_radius > 0) {\n // Limit chord error to 0.03 mm or 3% of the ridge radius.\n chord_error = min(0.03, tube_radius * 0.03);\n steps_per_turn = max(48, ceil(180 / acos(1 - min(1, chord_error / radius))));\n steps = ceil(turns * steps_per_turn);\n for (i = [0:steps]) {\n angle = handedness * 360 * turns * i / steps;\n p = [radius * cos(angle), radius * sin(angle), pitch * turns * i / steps];\n translate(p) sphere(r = tube_radius);\n if (i < steps) {\n next_angle = handedness * 360 * turns * (i + 1) / steps;\n dx = radius * cos(next_angle) - p[0];\n dy = radius * sin(next_angle) - p[1];\n dz = pitch * turns / steps;\n segment_length = sqrt(dx * dx + dy * dy + dz * dz);\n translate(p)\n rotate([0, acos(dz / segment_length), atan2(dy, dx)])\n cylinder(h = segment_length, r = tube_radius);\n }\n }\n }\n}\n\nPARAMETERS\n- Make important top-level constants user-adjustable with OpenSCAD Customizer comments:\n - Numbers with ranges: body_radius = 12; // [4:0.5:40]\n - Counts: leg_count = 4; // [2:8]\n - Booleans: show_base = true;\n - Options: style = \"round\"; // [round, sharp, chunky]\n- Prefer stable size/count/ratio/style controls; keep fragile dependent dimensions as local expressions.\n\nSUPPORTED SUBSET\n- Export is best-effort from a supported CSG subset: cube, sphere, cylinder, translate, rotate, color, union, difference, intersection, and goop.\n- difference() cutters become subtractive primitives, so use clean cutters that fully pass through the target solid.\n- Unsupported OpenSCAD may validate but can warn or skip during export; prefer the supported subset above.";
1
+ export declare const OPENSCAD_INSTRUCTIONS = "Use womp.openscad to create or update one adjustable CAD part. Read an existing part before editing it.\nKeep follow-up edits to an existing CAD part in that part unless the user asks to change representation.\nread(0) returns the root container for creation. read(id) returns an existing\npart or container. Use the scene-editing skill when available to discover other scene objects.\ncreate requires a parentId (0 means the scene root); update requires the existing objectId.\nBoth methods compile the effective source and parameters, apply one undoable change, and check wall thickness.\nPreserve intervening user changes. Ask the user when the intended edits conflict or remain ambiguous.\nExisting overrides are preserved for parameters still present;\nparams supplies overrides to merge into the current values. Keep top-level parameter names stable.\nReturn complete source on every update and preserve unrelated geometry. Never create a replacement to repair a part.\nCompile errors return status rejected without applying. Creation requires validated placement bounds.\nAn update may apply with validation unavailable; that is a diagnostic, not proof that it compiles.\nAn applied part remains in the scene even if thickness fails or is unavailable. Use the returned objectId for repairs.\nWhen thickness fails, increase thin walls and fragile connections while preserving requested dimensions and openings.\nAt most four applied printability repairs are allowed per logical build/edit in this run. Respect the returned limit;\ndo not bypass it by recreating the part. Unavailable thickness is not a pass. Report unresolved issues honestly.\nBuild connected geometry and avoid features below 1.4 mm. OpenSCAD source dimensions use millimetres,\nindependently of the scene display unit. New parts are centered and grounded from compiled bounds.\nOpenSCAD is Z-up; the scene-editing API is Y-up. For an unrotated part at its creation-time scale and an identity parent transform,\na source point [x,y,z] mm maps to scene {x:y, y:z, z:-x} times the scene.unitMultiplier inside the access callback, plus nodeGetPos(partId).\nAccount for the part and parent transforms when they are not identity; source coordinates are not scene coordinates.\nAfter a major change, use the scene screenshot API and emitImage to inspect the applied result.\nA committed effect can survive later failure. Inspect receipts and the existing part before retrying.\nDo not print source in the final answer unless requested; describe the result and any unresolved diagnostics.\n\nRUNTIME\n- Produce a single OpenSCAD file.\n- Do not use imports, includes, external libraries, text, hull, minkowski, polyhedron, or extrudes.\n- Prefer cube, sphere, cylinder, translate, rotate, color, union, difference, and intersection.\n- Do not use $fn, $fa, or $fs; tessellation controls are ignored.\n- Build faceted geometry by combining supported primitives with CSG operations and transforms.\n- Do not use scale(); size primitives directly instead.\n- Use color(\"#rrggbb\") around distinct visible parts.\n- Keep the model centered near the origin and use millimeter-like units consistently.\n- For organic blending, use goop(radius_mm) { ... }. The radius is in millimetres before parent scaling, matching scene-editing; do not multiply by project unitMultiplier. It is ordered: the first child seeds with blend 0, and each later child uses radius_mm.\n- Put core primitives first. Avoid wrapping goop children in union() when they should blend individually.\n\nSCREWS AND THREADS\n- Copy helical_ridge below for rounded screw threads, necks, caps, and coils. It joins spheres with cylinders; never use stacked rings or disconnected spheres.\n- Dimensions are mm: radius = ridge centerline radius; pitch = axial travel/turn; tube_radius = half ridge thickness; handedness = 1 (right) or -1 (left).\n- For a hand control use thread_hand = 1; // [-1:Left, 1:Right] and pass it directly. Ternary expressions (?:) are unsupported.\n- Embed the ridge in the shaft/neck (e.g. radius = shaft_radius). Hollow fittings: subtract the bore from body + thread. Internal threads: subtract the helix from the socket wall with mating clearance. Mating parts need matching pitch and handedness.\n- Expose diameter, pitch, thread length, and thickness in Customizer; derive sampling. Keep 2 * tube_radius < pitch and allow tube_radius beyond both path endpoints for rounded ends. This is a rounded profile, not ISO/metric V-thread; never claim standards compliance.\n- Build heads/grips separately using cylinders, tapered cylinders, and radial ribs/cutters, not thread samples.\n\nmodule helical_ridge(radius, pitch, turns, tube_radius, handedness) {\n if (radius > 0 && pitch > 0 && turns > 0 && tube_radius > 0) {\n // Limit chord error to 0.03 mm or 3% of the ridge radius.\n chord_error = min(0.03, tube_radius * 0.03);\n steps_per_turn = max(48, ceil(180 / acos(1 - min(1, chord_error / radius))));\n steps = ceil(turns * steps_per_turn);\n for (i = [0:steps]) {\n angle = handedness * 360 * turns * i / steps;\n p = [radius * cos(angle), radius * sin(angle), pitch * turns * i / steps];\n translate(p) sphere(r = tube_radius);\n if (i < steps) {\n next_angle = handedness * 360 * turns * (i + 1) / steps;\n dx = radius * cos(next_angle) - p[0];\n dy = radius * sin(next_angle) - p[1];\n dz = pitch * turns / steps;\n segment_length = sqrt(dx * dx + dy * dy + dz * dz);\n translate(p)\n rotate([0, acos(dz / segment_length), atan2(dy, dx)])\n cylinder(h = segment_length, r = tube_radius);\n }\n }\n }\n}\n\nPARAMETERS\n- Make important top-level constants user-adjustable with OpenSCAD Customizer comments:\n - Numbers with ranges: body_radius = 12; // [4:0.5:40]\n - Counts: leg_count = 4; // [2:8]\n - Booleans: show_base = true;\n - Options: style = \"round\"; // [round, sharp, chunky]\n- Prefer stable size/count/ratio/style controls; keep fragile dependent dimensions as local expressions.\n\nSUPPORTED SUBSET\n- Export is best-effort from a supported CSG subset: cube, sphere, cylinder, translate, rotate, color, union, difference, intersection, and goop.\n- difference() cutters become subtractive primitives, so use clean cutters that fully pass through the target solid.\n- Unsupported OpenSCAD may validate but can warn or skip during export; prefer the supported subset above.";
@@ -1,82 +1,81 @@
1
- export const OPENSCAD_INSTRUCTIONS = `Use womp.openscad to create or update one adjustable CAD part. Read an existing part before editing it.
2
- Keep follow-up edits to an existing CAD part in that part unless the user asks to change representation.
3
- read(0) returns the root container and a scene revision for creation. read(id) returns an existing
4
- part or container. Use the scene-editing skill when available to discover other scene objects.
5
- create requires a parentId (0 means the scene root); update requires the existing objectId.
6
- Both methods compile the effective source and parameters, apply one undoable change, and check wall thickness.
7
- A stale revision requires reading again and adapting the edit while preserving intervening user changes.
8
- Ask the user only when the intended edits conflict or remain ambiguous; never reuse the old replacement
9
- with a refreshed revision token. Existing overrides are preserved for parameters still present;
10
- params supplies overrides to merge into the current values. Keep top-level parameter names stable.
11
- Return complete source on every update and preserve unrelated geometry. Never create a replacement to repair a part.
12
- Compile errors return status rejected without applying. Creation requires validated placement bounds.
13
- An update may apply with validation unavailable; that is a diagnostic, not proof that it compiles.
14
- An applied part remains in the scene even if thickness fails or is unavailable. Use the returned objectId for repairs.
15
- When thickness fails, increase thin walls and fragile connections while preserving requested dimensions and openings.
16
- At most four applied printability repairs are allowed per logical build/edit in this run. Respect the returned limit;
17
- do not bypass it by recreating the part. Unavailable thickness is not a pass. Report unresolved issues honestly.
18
- Build connected geometry and avoid features below 1.4 mm. OpenSCAD source dimensions use millimetres,
19
- independently of the scene display unit. New parts are centered and grounded from compiled bounds.
20
- OpenSCAD is Z-up; the scene-editing API is Y-up. For an unrotated part at its creation-time scale and an identity parent transform,
21
- a source point [x,y,z] mm maps to scene {x:y, y:z, z:-x} times the unitMultiplier returned by scene.read(), plus nodeGetPos(partId).
22
- Account for the part and parent transforms when they are not identity; source coordinates are not scene coordinates.
23
- After a major change, use the scene screenshot API and emitImage to inspect the applied result.
24
- A committed effect can survive later failure. Inspect receipts and the existing part before retrying.
25
- Do not print source in the final answer unless requested; describe the result and any unresolved diagnostics.
26
-
27
- RUNTIME
28
- - Produce a single OpenSCAD file.
29
- - Do not use imports, includes, external libraries, text, hull, minkowski, polyhedron, or extrudes.
30
- - Prefer cube, sphere, cylinder, translate, rotate, color, union, difference, and intersection.
31
- - Do not use $fn, $fa, or $fs; tessellation controls are ignored.
32
- - Build faceted geometry by combining supported primitives with CSG operations and transforms.
33
- - Do not use scale(); size primitives directly instead.
34
- - Use color("#rrggbb") around distinct visible parts.
35
- - Keep the model centered near the origin and use millimeter-like units consistently.
36
- - For organic blending, use goop(radius_mm) { ... }. The radius is in millimetres before parent scaling, matching scene-editing; do not multiply by project unitMultiplier. It is ordered: the first child seeds with blend 0, and each later child uses radius_mm.
37
- - Put core primitives first. Avoid wrapping goop children in union() when they should blend individually.
38
-
39
- SCREWS AND THREADS
40
- - Copy helical_ridge below for rounded screw threads, necks, caps, and coils. It joins spheres with cylinders; never use stacked rings or disconnected spheres.
41
- - Dimensions are mm: radius = ridge centerline radius; pitch = axial travel/turn; tube_radius = half ridge thickness; handedness = 1 (right) or -1 (left).
42
- - For a hand control use thread_hand = 1; // [-1:Left, 1:Right] and pass it directly. Ternary expressions (?:) are unsupported.
43
- - Embed the ridge in the shaft/neck (e.g. radius = shaft_radius). Hollow fittings: subtract the bore from body + thread. Internal threads: subtract the helix from the socket wall with mating clearance. Mating parts need matching pitch and handedness.
44
- - Expose diameter, pitch, thread length, and thickness in Customizer; derive sampling. Keep 2 * tube_radius < pitch and allow tube_radius beyond both path endpoints for rounded ends. This is a rounded profile, not ISO/metric V-thread; never claim standards compliance.
45
- - Build heads/grips separately using cylinders, tapered cylinders, and radial ribs/cutters, not thread samples.
46
-
47
- module helical_ridge(radius, pitch, turns, tube_radius, handedness) {
48
- if (radius > 0 && pitch > 0 && turns > 0 && tube_radius > 0) {
49
- // Limit chord error to 0.03 mm or 3% of the ridge radius.
50
- chord_error = min(0.03, tube_radius * 0.03);
51
- steps_per_turn = max(48, ceil(180 / acos(1 - min(1, chord_error / radius))));
52
- steps = ceil(turns * steps_per_turn);
53
- for (i = [0:steps]) {
54
- angle = handedness * 360 * turns * i / steps;
55
- p = [radius * cos(angle), radius * sin(angle), pitch * turns * i / steps];
56
- translate(p) sphere(r = tube_radius);
57
- if (i < steps) {
58
- next_angle = handedness * 360 * turns * (i + 1) / steps;
59
- dx = radius * cos(next_angle) - p[0];
60
- dy = radius * sin(next_angle) - p[1];
61
- dz = pitch * turns / steps;
62
- segment_length = sqrt(dx * dx + dy * dy + dz * dz);
63
- translate(p)
64
- rotate([0, acos(dz / segment_length), atan2(dy, dx)])
65
- cylinder(h = segment_length, r = tube_radius);
66
- }
67
- }
68
- }
69
- }
70
-
71
- PARAMETERS
72
- - Make important top-level constants user-adjustable with OpenSCAD Customizer comments:
73
- - Numbers with ranges: body_radius = 12; // [4:0.5:40]
74
- - Counts: leg_count = 4; // [2:8]
75
- - Booleans: show_base = true;
76
- - Options: style = "round"; // [round, sharp, chunky]
77
- - Prefer stable size/count/ratio/style controls; keep fragile dependent dimensions as local expressions.
78
-
79
- SUPPORTED SUBSET
80
- - Export is best-effort from a supported CSG subset: cube, sphere, cylinder, translate, rotate, color, union, difference, intersection, and goop.
81
- - difference() cutters become subtractive primitives, so use clean cutters that fully pass through the target solid.
1
+ export const OPENSCAD_INSTRUCTIONS = `Use womp.openscad to create or update one adjustable CAD part. Read an existing part before editing it.
2
+ Keep follow-up edits to an existing CAD part in that part unless the user asks to change representation.
3
+ read(0) returns the root container for creation. read(id) returns an existing
4
+ part or container. Use the scene-editing skill when available to discover other scene objects.
5
+ create requires a parentId (0 means the scene root); update requires the existing objectId.
6
+ Both methods compile the effective source and parameters, apply one undoable change, and check wall thickness.
7
+ Preserve intervening user changes. Ask the user when the intended edits conflict or remain ambiguous.
8
+ Existing overrides are preserved for parameters still present;
9
+ params supplies overrides to merge into the current values. Keep top-level parameter names stable.
10
+ Return complete source on every update and preserve unrelated geometry. Never create a replacement to repair a part.
11
+ Compile errors return status rejected without applying. Creation requires validated placement bounds.
12
+ An update may apply with validation unavailable; that is a diagnostic, not proof that it compiles.
13
+ An applied part remains in the scene even if thickness fails or is unavailable. Use the returned objectId for repairs.
14
+ When thickness fails, increase thin walls and fragile connections while preserving requested dimensions and openings.
15
+ At most four applied printability repairs are allowed per logical build/edit in this run. Respect the returned limit;
16
+ do not bypass it by recreating the part. Unavailable thickness is not a pass. Report unresolved issues honestly.
17
+ Build connected geometry and avoid features below 1.4 mm. OpenSCAD source dimensions use millimetres,
18
+ independently of the scene display unit. New parts are centered and grounded from compiled bounds.
19
+ OpenSCAD is Z-up; the scene-editing API is Y-up. For an unrotated part at its creation-time scale and an identity parent transform,
20
+ a source point [x,y,z] mm maps to scene {x:y, y:z, z:-x} times the scene.unitMultiplier inside the access callback, plus nodeGetPos(partId).
21
+ Account for the part and parent transforms when they are not identity; source coordinates are not scene coordinates.
22
+ After a major change, use the scene screenshot API and emitImage to inspect the applied result.
23
+ A committed effect can survive later failure. Inspect receipts and the existing part before retrying.
24
+ Do not print source in the final answer unless requested; describe the result and any unresolved diagnostics.
25
+
26
+ RUNTIME
27
+ - Produce a single OpenSCAD file.
28
+ - Do not use imports, includes, external libraries, text, hull, minkowski, polyhedron, or extrudes.
29
+ - Prefer cube, sphere, cylinder, translate, rotate, color, union, difference, and intersection.
30
+ - Do not use $fn, $fa, or $fs; tessellation controls are ignored.
31
+ - Build faceted geometry by combining supported primitives with CSG operations and transforms.
32
+ - Do not use scale(); size primitives directly instead.
33
+ - Use color("#rrggbb") around distinct visible parts.
34
+ - Keep the model centered near the origin and use millimeter-like units consistently.
35
+ - For organic blending, use goop(radius_mm) { ... }. The radius is in millimetres before parent scaling, matching scene-editing; do not multiply by project unitMultiplier. It is ordered: the first child seeds with blend 0, and each later child uses radius_mm.
36
+ - Put core primitives first. Avoid wrapping goop children in union() when they should blend individually.
37
+
38
+ SCREWS AND THREADS
39
+ - Copy helical_ridge below for rounded screw threads, necks, caps, and coils. It joins spheres with cylinders; never use stacked rings or disconnected spheres.
40
+ - Dimensions are mm: radius = ridge centerline radius; pitch = axial travel/turn; tube_radius = half ridge thickness; handedness = 1 (right) or -1 (left).
41
+ - For a hand control use thread_hand = 1; // [-1:Left, 1:Right] and pass it directly. Ternary expressions (?:) are unsupported.
42
+ - Embed the ridge in the shaft/neck (e.g. radius = shaft_radius). Hollow fittings: subtract the bore from body + thread. Internal threads: subtract the helix from the socket wall with mating clearance. Mating parts need matching pitch and handedness.
43
+ - Expose diameter, pitch, thread length, and thickness in Customizer; derive sampling. Keep 2 * tube_radius < pitch and allow tube_radius beyond both path endpoints for rounded ends. This is a rounded profile, not ISO/metric V-thread; never claim standards compliance.
44
+ - Build heads/grips separately using cylinders, tapered cylinders, and radial ribs/cutters, not thread samples.
45
+
46
+ module helical_ridge(radius, pitch, turns, tube_radius, handedness) {
47
+ if (radius > 0 && pitch > 0 && turns > 0 && tube_radius > 0) {
48
+ // Limit chord error to 0.03 mm or 3% of the ridge radius.
49
+ chord_error = min(0.03, tube_radius * 0.03);
50
+ steps_per_turn = max(48, ceil(180 / acos(1 - min(1, chord_error / radius))));
51
+ steps = ceil(turns * steps_per_turn);
52
+ for (i = [0:steps]) {
53
+ angle = handedness * 360 * turns * i / steps;
54
+ p = [radius * cos(angle), radius * sin(angle), pitch * turns * i / steps];
55
+ translate(p) sphere(r = tube_radius);
56
+ if (i < steps) {
57
+ next_angle = handedness * 360 * turns * (i + 1) / steps;
58
+ dx = radius * cos(next_angle) - p[0];
59
+ dy = radius * sin(next_angle) - p[1];
60
+ dz = pitch * turns / steps;
61
+ segment_length = sqrt(dx * dx + dy * dy + dz * dz);
62
+ translate(p)
63
+ rotate([0, acos(dz / segment_length), atan2(dy, dx)])
64
+ cylinder(h = segment_length, r = tube_radius);
65
+ }
66
+ }
67
+ }
68
+ }
69
+
70
+ PARAMETERS
71
+ - Make important top-level constants user-adjustable with OpenSCAD Customizer comments:
72
+ - Numbers with ranges: body_radius = 12; // [4:0.5:40]
73
+ - Counts: leg_count = 4; // [2:8]
74
+ - Booleans: show_base = true;
75
+ - Options: style = "round"; // [round, sharp, chunky]
76
+ - Prefer stable size/count/ratio/style controls; keep fragile dependent dimensions as local expressions.
77
+
78
+ SUPPORTED SUBSET
79
+ - Export is best-effort from a supported CSG subset: cube, sphere, cylinder, translate, rotate, color, union, difference, intersection, and goop.
80
+ - difference() cutters become subtractive primitives, so use clean cutters that fully pass through the target solid.
82
81
  - Unsupported OpenSCAD may validate but can warn or skip during export; prefer the supported subset above.`;
@@ -6,13 +6,11 @@ export type OpenScadTarget = {
6
6
  title: string;
7
7
  source: string | null;
8
8
  params: Record<string, unknown>;
9
- revision: string;
10
9
  };
11
10
  export type OpenScadSource = {
12
11
  source: string;
13
12
  title: string;
14
13
  params?: Record<string, unknown>;
15
- expectedRevision: string;
16
14
  };
17
15
  export type OpenScadCreate = OpenScadSource & {
18
16
  parentId: number;
@@ -35,7 +33,6 @@ export type OpenScadPrintability = {
35
33
  export type OpenScadWriteResult = {
36
34
  status: "applied" | "rejected";
37
35
  objectId?: number;
38
- revision: string;
39
36
  validation: OpenScadValidation;
40
37
  printability?: OpenScadPrintability;
41
38
  repairAttempts: number;
@@ -6,7 +6,6 @@ const source = z.object({
6
6
  source: z.string().trim().min(1),
7
7
  title: z.string().trim().min(1),
8
8
  params: z.record(z.string(), z.json()).optional(),
9
- expectedRevision: z.string().min(1),
10
9
  });
11
10
  const create = source.extend({ parentId: nodeId }).strict();
12
11
  const update = source.extend({ objectId: nodeId.positive() }).strict();
@@ -21,7 +20,7 @@ export function createOpenScadCapability(host) {
21
20
  declarations: WOMP_OPENSCAD_DECLARATIONS,
22
21
  examples: [
23
22
  "const part = await womp.openscad.read(objectId); print(part);",
24
- "const part = await womp.openscad.read(objectId); print(await womp.openscad.update({ objectId: part.objectId, source: part.source, title: part.title, params: { width: 30 }, expectedRevision: part.revision }));",
23
+ "const part = await womp.openscad.read(objectId); print(await womp.openscad.update({ objectId: part.objectId, source: part.source, title: part.title, params: { width: 30 } }));",
25
24
  ],
26
25
  },
27
26
  ],
@@ -3,8 +3,6 @@ import type { ArtifactRef, SparkCapability, SparkInvocationContext } from "../ca
3
3
  import type { WompSceneDraft } from "./scene-draft.js";
4
4
  import { type SceneHealth } from "../scene-health.js";
5
5
  export type SceneSnapshot = {
6
- health: SceneHealth;
7
- revision: string;
8
6
  projectId?: number;
9
7
  unitMultiplier: number;
10
8
  nodes: {
@@ -19,18 +17,16 @@ export type SceneScreenshotOptions = {
19
17
  camera?: CameraConfiguration;
20
18
  };
21
19
  export type WompSceneApi = {
22
- read(): Promise<SceneSnapshot>;
23
20
  health(objectIds?: number[]): Promise<SceneHealth>;
24
- edit<T>(callback: (draft: WompSceneDraft) => T | Promise<T>, expectedRevision: string): Promise<T>;
21
+ access<T>(callback: (draft: WompSceneDraft) => T | Promise<T>): Promise<T>;
25
22
  screenshot(options?: SceneScreenshotOptions): Promise<ArtifactRef>;
26
23
  };
27
24
  export interface SceneHealthHost {
28
25
  read(objectIds: number[], context: SparkInvocationContext): Promise<SceneHealth>;
29
26
  }
30
27
  export interface SceneHost {
31
- read(context: SparkInvocationContext): Promise<Omit<SceneSnapshot, "health">>;
32
28
  health?: SceneHealthHost["read"];
33
- edit<T>(callback: (draft: WompSceneDraft) => T | Promise<T>, expectedRevision: string, context: SparkInvocationContext): Promise<T>;
29
+ access<T>(callback: (draft: WompSceneDraft) => T | Promise<T>, context: SparkInvocationContext): Promise<T>;
34
30
  screenshot(options: SceneScreenshotOptions, context: SparkInvocationContext): Promise<ArtifactRef>;
35
31
  }
36
32
  export declare function createSceneCapability(host: SceneHost): SparkCapability<WompSceneApi>;
@@ -2,7 +2,7 @@ import { z } from "zod";
2
2
  import { maxLightIntensity } from "@womp/kakapo-sdk";
3
3
  import { WOMP_SCENE_DECLARATIONS } from "../generated/scene-declarations.js";
4
4
  import { unverifiedSceneHealth } from "../scene-health.js";
5
- // A node id, as `scene.read()` publishes them: the scene root is 0, so a health
5
+ // A node id, as `scene.access()` publishes them: the scene root is 0, so a health
6
6
  // read has to accept it. `openscad.ts` and `geometry.ts` spell an object id the
7
7
  // same way; `positive()` here refused an id this capability had just handed out.
8
8
  const objectId = z.number().int().nonnegative();
@@ -21,7 +21,7 @@ function readHealthObjectIds(objectIds) {
21
21
  ? objectIds.filter((value) => objectId.safeParse(value).success === false)
22
22
  : [objectIds];
23
23
  const named = invalid.slice(0, 3).map(display).join(", ");
24
- throw new Error(`scene.health takes object ids from scene.read(): whole numbers from 0 up, in an array. ${named} ${invalid.length === 1 ? "is not one" : "are not ids"}.`);
24
+ throw new Error(`scene.health takes object ids from scene.access(): whole numbers from 0 up, in an array. ${named} ${invalid.length === 1 ? "is not one" : "are not ids"}.`);
25
25
  }
26
26
  const cameraVector = z.object({ x: z.number().finite(), y: z.number().finite(), z: z.number().finite() }).strict();
27
27
  const screenshotOptions = z.object({
@@ -38,35 +38,34 @@ export function createSceneCapability(host) {
38
38
  skills: [
39
39
  {
40
40
  name: "scene-editing",
41
- version: "42",
41
+ version: "45",
42
42
  description: "Inspect the open scene and edit its objects, materials, curves, and environment.",
43
- instructions: `Read the scene first and keep its revision and object IDs. read() includes health.
43
+ instructions: `Use womp.scene.access(callback) for both inspection and edits. Inspect targets inside each callback using scene.nodes({ name, type, parentId, ids, offset, limit }) and detailed getters; filters are optional, name is a case-insensitive substring, and results default to 100 (maximum 1000). Page with offset as needed. Inspection reflects changes made in the callback. scene.unitMultiplier gives project units. Do not reuse an earlier inspection as current state.
44
44
  Use womp.scene.health() to refresh whole-scene health or womp.scene.health(objectIds) to check specific objects (mapped to their owning Areas).
45
- Health is a separate snapshot, not proof of consistency with read().revision or that the latest edit finished evaluating. Inspect post-edit health in receipts before claiming success; refresh only when needed.
45
+ Health is requested only through scene.health(); access does not request it automatically. It is renderer feedback, not proof that the latest edit finished evaluating. Request it when needed to verify the result.
46
46
  Unavailable, stale, or unverified feedback must not trigger blind regeneration or a claim that the model passed. Hosts without health services return unverified health with a reason.
47
47
  For confirmed primitive or depth overflow, repair the same target while preserving design, dimensions, active parameter overrides, and unrelated objects. At most two geometry repairs are allowed per target in one logical run.
48
48
  Empty Areas may be pending, intentionally empty, mesh-only, or failed. Overflow flags take precedence over possibly stale counts.
49
49
  max_total_depth reports the engine's tier-dependent nesting allowance, not measured depth. Compiled Boolean depth includes generated grouping; organizational Groups do not add a level. Use flag_depth_overflow to detect evaluator rejection.
50
- Call scene.edit(callback, expectedRevision)
51
- for one coherent undoable change. The callback receives a draft; all node/material/curve functions and enums
50
+ Call scene.access(callback) for one coherent change or read-only inspection. The callback receives a draft; all node/material/curve functions and enums
52
51
  are properties of that draft. The draft expires when the callback ends. Await asynchronous methods.
53
- Do not start unrelated operations from inside an edit. A stale revision requires reading again.
52
+ Do not start unrelated operations from inside an access. Draft handles expire when its callback returns. An unchanged draft does not submit or save anything.
54
53
  Preserve the existing scene unless asked to remove or replace content. Use semantic object names and reuse
55
54
  known IDs when editing rather than creating duplicates. Distances follow the current project's units
56
- (read().unitMultiplier is 1 for millimetres, 0.1 for centimetres, approximately 0.0393701 for inches).
57
- Convert a dimension in millimetres to project units by multiplying it by read().unitMultiplier.
55
+ (scene.unitMultiplier is 1 for millimetres, 0.1 for centimetres, approximately 0.0393701 for inches).
56
+ Convert a dimension in millimetres to project units by multiplying it by scene.unitMultiplier.
58
57
  The SDK-backed draft clamps dimension writes to 0.01–1000 mm per component before converting to native units; this is an adapter limit, not a scene-wide size limit. Read back dimensions when physical size matters.
59
58
  Area size is a dimensionless scale; Group size stays fixed at one. Lights must be created at root (parentId 0); their size has x/y dimensions.
60
- Light power is linear emitted intensity before collimation, not a percentage or physical unit: doubling it doubles emission, not tone-mapped pixel brightness. Valid ranges are 0–${maxLightIntensity("rect")} for Rect/Sphere and 0–${maxLightIntensity("distant")} for Distant; these limits are not brightness targets. A light-type change preserves intensity and rejects values outside the new type's range; lower intensity first if needed. Rect size is width/height; Sphere uses x as diameter; Distant uses direction, not position or size.
61
- Use nodeSetFacing(id, target - position) to aim light emission or the readable face of text/decals at a target in the same parent-local space. It keeps Y up (Z up for vertical directions); generic lookAt aligns a different axis and does not aim these faces.
62
- For text, nodeSetTextSize(id, {fontSize, depth}) sets font em size and extrusion in project units, not a bounding box. Layout width and additional letter spacing also use project units; spacing clamps to ±25 mm. Line height is a multiplier clamped to 0.5–3. The origin anchors the first baseline; alignment uses the layout width. Empty text clears its geometry.
63
- Decals require an existing loaded image and receiving geometry. Projection is a uniform cube: native scale.x (public size.z) controls all dimensions, not independent width/height/depth. Restriction to an Area requires that parent Area; root decals project globally. Missing image data can yield no projection even when no resource is pending.
59
+ Light power is linear emitted intensity before collimation, not a percentage or physical unit: doubling it doubles emission, not tone-mapped pixel brightness. Valid ranges are 0–${maxLightIntensity("rect")} for Rect/Sphere and 0–${maxLightIntensity("distant")} for Distant; these limits are not brightness targets. A light-type change preserves intensity and rejects values outside the new type's range; lower intensity first if needed. Rect size is width/height; Sphere uses x as diameter; Distant uses direction, not position or size.
60
+ Use nodeSetFacing(id, target - position) to aim light emission or the readable face of text/decals at a target in the same parent-local space. It keeps Y up (Z up for vertical directions); generic lookAt aligns a different axis and does not aim these faces.
61
+ For text, nodeSetTextSize(id, {fontSize, depth}) sets font em size and extrusion in project units, not a bounding box. Layout width and additional letter spacing also use project units; spacing clamps to ±25 mm. Line height is a multiplier clamped to 0.5–3. The origin anchors the first baseline; alignment uses the layout width. Empty text clears its geometry.
62
+ Decals require an existing loaded image and receiving geometry. Projection is a uniform cube: native scale.x (public size.z) controls all dimensions, not independent width/height/depth. Restriction to an Area requires that parent Area; root decals project globally. Missing image data can yield no projection even when no resource is pending.
64
63
  nodeCreate(Curve, parentId) creates an empty curve with zero blend. curvePointAdd(curveId, point, index?) returns the new index; omit index to append or supply an integer from 0 through point count to insert before that position.
65
64
  Point defaults: position/rotation/handles zero, profile size {x:1,y:1,z:1} in project units, the curve's material, fixed false, round 0. Pass {} for defaults.
66
65
  Removing all points is supported. One point renders a single profile primitive, not a path.
67
66
  Curves render sampled profiles, not a continuous sweep. For smooth curves, start with nodeSetDensity(curveId, 250) and nodeSetBlend(curveId, 3).
68
67
  Density increases sampling and primitive cost; the 3 mm blend softens joins, not sample positions. Adjust blend to preserve thin features and the intended silhouette; these settings do not guarantee continuity.
69
- nodeSetUnionResolution(unionId, resolution) sets a dimensionless detail level, clamped to 0.01–0.65: higher is finer and costs more voxels. Set the owning outermost Area, not a nested Union. Material emission ranges from 0 to 1.
68
+ nodeSetUnionResolution(unionId, resolution) sets a dimensionless detail level, clamped to 0.01–0.65: higher is finer and costs more voxels. Set the owning outermost Area, not a nested Union. Material emission ranges from 0 to 1.
70
69
  nodeSetBlend and mirror goop take radii in millimetres before parent scaling, regardless of project units, and clamp to 0–500 mm. This does not apply to the FlowIR Boolean Blend port, which takes native units; geometry-nodes-reference gives its conversion.
71
70
  V1/V2 curve transforms are read-only;
72
71
  edit their points instead. Handles and closure are available only on V3 Bezier curves.
@@ -85,50 +84,51 @@ Never replace a parametric graph with ordinary primitives to color it. Ordinary
85
84
  nodeSetColor writes the node color field (used by lights); it does not replace a geometry object's material color.
86
85
  Do not recolor a shared material unless every object using it should change. Create and assign the material in the same edit as the scene geometry that uses it; a Geometry Nodes graph instead consumes a material ID created in an earlier edit.
87
86
  Create primitives, curves, and text inside Areas/Unions. Respect tree order for subtraction and intersection.
88
- Groups are organizational only; move and rotate their child Areas individually, not the Group.
89
- An Area is an outermost Union with no Union ancestor: it has its own modeller, bounds, and volumetric resolution. Nested Unions share that Area's resolution, even through Groups.
90
- Choose Area boundaries for evaluation needs, not individual editability: parts within an Area remain independently editable. Sibling Areas under a Group can overlap without blending together, while each blends internally and has independent resolution. Keep required shared smooth joins or Boolean evaluation within one Area; overlapping independent Areas are not a watertight Boolean union.
91
- Prioritize requested visual fidelity over minimizing voxel use. If correctly placed thin features render fragmented or missing, increase their owning Area's resolution, up to 0.65 as needed, and compare the same camera; distinguish sampling loss from material/lighting contrast or authored gaps. A higher voxel count is acceptable when detail improves within engine limits. If resolution is insufficient or hits resource limits/downscaling, consider smaller independent Areas where shared blending or Booleans are unnecessary.
87
+ Groups are organizational only; move and rotate their child Areas individually, not the Group.
88
+ An Area is an outermost Union with no Union ancestor: it has its own modeller, bounds, and volumetric resolution. Nested Unions share that Area's resolution, even through Groups.
89
+ Choose Area boundaries for evaluation needs, not individual editability: parts within an Area remain independently editable. Sibling Areas under a Group can overlap without blending together, while each blends internally and has independent resolution. Keep required shared smooth joins or Boolean evaluation within one Area; overlapping independent Areas are not a watertight Boolean union.
90
+ Prioritize requested visual fidelity over minimizing voxel use. If correctly placed thin features render fragmented or missing, increase their owning Area's resolution, up to 0.65 as needed, and compare the same camera; distinguish sampling loss from material/lighting contrast or authored gaps. A higher voxel count is acceptable when detail improves within engine limits. If resolution is insufficient or hits resource limits/downscaling, consider smaller independent Areas where shared blending or Booleans are unnecessary.
92
91
  Sphere uses size.x as uniform diameter (y/z do not stretch it), including new or resized spherical curve points. Cylinder/Cone/Pyramid use x as base diameter/width and y as height;
93
- Torus lies in local XZ (axis +Y), with x as outer diameter and y as tube thickness. For these four primitives, nodeSetSize accepts {x, y}; z follows x even when supplied. Cube uses all three dimensions. Node and curve-point round are dimensionless fractions clamped to [0, 1], not radii in project units; rounding does not set size. Cube rounding reaches half its shortest dimension at 1, so a shallow Cube retains broad flat faces rather than becoming an ellipsoid.
94
- Build and verify coarse geometry and unfamiliar operations before replicating details. Check one representative result, then repeat it.
95
- Construct both sides of a joint from shared attachment points and axes. Create each mounted part together with its contact or mounting geometry, derived from the supporting surface; preserve intended clearances and separate editability. If contact is uncertain, check the authored positions, dimensions, and axes in 3D: projected overlap is not a connection.
96
- Fix unintended gaps, floating attachments, and fragmented geometry before decorative detail or presentation. Use inspection to identify a concrete defect and verify its correction, not merely to collect screenshots or healthy receipts.
97
- Reference fidelity:
92
+ Torus lies in local XZ (axis +Y), with x as outer diameter and y as tube thickness. For these four primitives, nodeSetSize accepts {x, y}; z follows x even when supplied. Cube uses all three dimensions. Node and curve-point round are dimensionless fractions clamped to [0, 1], not radii in project units; rounding does not set size. Cube rounding reaches half its shortest dimension at 1, so a shallow Cube retains broad flat faces rather than becoming an ellipsoid.
93
+ Build and verify coarse geometry and unfamiliar operations before replicating details. Check one representative result, then repeat it.
94
+ Construct both sides of a joint from shared attachment points and axes. Create each mounted part together with its contact or mounting geometry, derived from the supporting surface; preserve intended clearances and separate editability. If contact is uncertain, check the authored positions, dimensions, and axes in 3D: projected overlap is not a connection.
95
+ Fix unintended gaps, floating attachments, and fragmented geometry before decorative detail or presentation. Use inspection to identify a concrete defect and verify its correction, not merely to collect screenshots or healthy receipts.
96
+ Reference fidelity:
98
97
  When recreating an image, treat its visible geometry and level of detail as the target—not merely its subject, colors, or list of parts. Preserve the user's chosen workflow and editability requirements.
99
98
  Establish a comparison view matching the reference's angle, projection, and subject framing as closely as practical. Match silhouette, proportions, pose, and negative spaces first; then local contours, thickness, curvature, surface transitions, and defining details. Infer unseen geometry conservatively.
100
99
  Compare each rendered pass directly with the source. Identify the largest remaining visible shape mismatch, edit it, and verify that it improved before moving to smaller details. Use close-ups when the comparison view cannot resolve a feature; return to the comparison view afterward. Adjust sampling or resolution when visible faceting or segmentation requires it—not as a substitute for reshaping.
101
- Do not stop at semantic resemblance or after a fixed number of screenshots. Continue while substantial visible mismatches remain and supported edits are making progress, within the available budget. If progress stalls or the chosen representation cannot achieve the requested fidelity, explain the specific limitation and ask before changing workflows. Before finishing, compare the latest render with the reference and address the largest remaining visible mismatch; if substantial differences remain, identify the concrete stopping reason rather than treating an approximation disclaimer as completion.
100
+ Do not stop at semantic resemblance or after a fixed number of screenshots. Continue while substantial visible mismatches remain and supported edits are making progress, within the available budget. If progress stalls or the chosen representation cannot achieve the requested fidelity, explain the specific limitation and ask before changing workflows. Before finishing, compare the latest render with the reference and address the largest remaining visible mismatch; if substantial differences remain, identify the concrete stopping reason rather than treating an approximation disclaimer as completion.
102
101
 
103
102
  nodeClone is shallow (no children). await cloneSubtree(id, { parentId?, name?, index? }) copies the complete hierarchy with fresh IDs,
104
103
  preserving local transforms, order and metadata, remapping internal references and sharing external materials/assets.
105
- Cloning requires a host transport with atomic scene patches; an unsupported host rejects it without changing the draft.
104
+ Cloning stages changes in the draft and commits them with the rest of the access.
106
105
  For primitives, nodeSetBlend joins against all accumulated preceding geometry in the Area, not only the nearest part. A Union's blend affects its outer join, not joins between its children; top-level Area blend does not smooth its contents.
107
- For organic joins, overlap primitives and tune blend on the joining children while preserving intended gaps.
106
+ For organic joins, overlap primitives and tune blend on the joining children while preserving intended gaps.
108
107
  Check font, HDR, and material catalogs before selecting names. A host can explicitly report a catalog as
109
108
  unavailable. Selecting an HDR resets its intensity; apply a custom intensity after selecting it.
110
- For library materials, use listSuperMaterials(), then await materialImport(name) inside scene.edit and assign the returned numeric ID the way that object requires: nodeSetMaterialId or curvePointSetMaterialId for scene nodes, the FlowIR SetMaterial node for a Geometry Nodes graph. A failed import rolls back the draft.
109
+ For library materials, use listSuperMaterials(), then await materialImport(name) inside scene.access and assign the returned numeric ID the way that object requires: nodeSetMaterialId or curvePointSetMaterialId for scene nodes, the FlowIR SetMaterial node for a Geometry Nodes graph. A failed import rolls back the draft.
111
110
  Filter large read results with JavaScript and print only useful details.
112
111
  After a major edit, capture a screenshot outside the transaction and emitImage its reference.
113
- screenshot({ camera: { position: {x,y,z}, target: {x,y,z}, projection: 'perspective', horizontalFovDegrees: 60 } })
114
- sets a world-space camera in the same Womp coordinates and project units as scene positions (Y-up).
115
- For orthographic framing use projection: 'orthographic' and orthographicWidth in project units instead of FOV.
116
- Direction is derived from position/target; do not use coincident points or an exactly vertical viewing direction.
117
- Omitted projection/lens settings come from the active camera. Pass the camera again for repeatable captures.
118
- For object-focused screenshots, identify the requested object and frame it with an explicit camera position and target using its bounds; reuse established framing when appropriate. Choose a view that reveals the requested features without clipping the subject.
119
- Omitting camera captures the active viewport without auto-fit. Use it when the user asks about the current viewport or clearly refers to what is visible on screen, not on the assumption that it shows the requested object.
120
- Respect the host's camera-lock restrictions. Verify silhouette,
121
- connections, openings, proportions, and materials before claiming completion. Use the owning top-level Area for scene-space bounds;
112
+ screenshot() captures the current Kakapo viewport without moving or fitting the camera.
113
+ screenshot({ camera: { position: {x,y,z}, target: {x,y,z}, projection: 'perspective', horizontalFovDegrees: 60 } })
114
+ sets a world-space camera in Womp scene coordinates and current project units (Y-up), and leaves it active.
115
+ Use horizontalFovDegrees for perspective zoom, or projection: 'orthographic' with orthographicWidth in project units.
116
+ Omitted projection/lens settings are preserved. Position and target are required together; avoid coincident points or an exactly vertical direction.
117
+ Pass an explicit camera again for repeatable captures; targetId and view presets are not supported.
118
+ Respect the host's camera-lock restrictions. Only claim visual verification for features visible in the captured view. Verify silhouette,
119
+ connections, openings, proportions, and materials before claiming completion. Use the owning top-level Area for scene-space bounds;
122
120
  OpenSCAD part bounds are local to the part; individual primitive and curve bounds are unsupported. Renderer bounds and resize calls
123
- must finish before subsequent writes. Inside scene.edit, complete renderer-backed bounds reads before the first
121
+ must finish before subsequent writes. Inside scene.access, complete renderer-backed bounds reads before the first
124
122
  draft mutation; the SDK rejects them once the draft is dirty. Inspect committed results when renderer state has not caught up.
125
123
  A failed script can retain earlier committed effects. Use receipts and inspect unknown outcomes before retrying.`,
126
124
  declarations: WOMP_SCENE_DECLARATIONS,
127
125
  examples: [
128
- "const snapshot = await womp.scene.read(); print(snapshot.health);",
126
+ "print(await womp.scene.health());",
129
127
  "print(await womp.scene.health([objectId]));",
130
- "const snapshot = await womp.scene.read(); print(snapshot.nodes.filter(node => /body/i.test(node.name)));",
131
- "const snapshot = await womp.scene.read(); const diameter = 20 * snapshot.unitMultiplier; const result = await womp.scene.edit(scene => { const areaId = scene.nodeCreate(scene.NodeType.Union, 0); const bodyId = scene.nodeCreate(scene.NodeType.Primitive, areaId); scene.nodeSetName(bodyId, '20 mm orange sphere'); scene.nodeSetPrimType(bodyId, scene.PrimitiveType.Sphere); scene.nodeSetSize(bodyId, { x: diameter, y: diameter, z: diameter }); scene.nodeSetPos(bodyId, { x: 0, y: diameter / 2, z: 0 }); const materialId = scene.materialCreate(); scene.materialSetColor(materialId, { r: 255, g: 128, b: 0 }); scene.nodeSetMaterialId(bodyId, materialId); return { areaId, bodyId }; }, snapshot.revision); print(result); await emitImage(await womp.scene.screenshot({ camera: { position: { x: diameter * 2, y: diameter * 1.5, z: diameter * 2 }, target: { x: 0, y: diameter / 2, z: 0 }, projection: 'perspective', horizontalFovDegrees: 60 } }));",
128
+ "print(await womp.scene.access(scene => scene.nodes({ name: 'body' })));",
129
+ "const unit = await womp.scene.access(scene => scene.unitMultiplier); await emitImage(await womp.scene.screenshot({ camera: { position: { x: 100 * unit, y: 75 * unit, z: 100 * unit }, target: { x: 0, y: 0, z: 0 }, projection: 'perspective', horizontalFovDegrees: 60 } }));",
130
+ "const unit = await womp.scene.access(scene => scene.unitMultiplier); await emitImage(await womp.scene.screenshot({ camera: { position: { x: 0, y: 25 * unit, z: 100 * unit }, target: { x: 0, y: 0, z: 0 }, projection: 'orthographic', orthographicWidth: 80 * unit } }));",
131
+ "const result = await womp.scene.access(scene => { const diameter = 20 * scene.unitMultiplier; const areaId = scene.nodeCreate(scene.NodeType.Union, 0); const bodyId = scene.nodeCreate(scene.NodeType.Primitive, areaId); scene.nodeSetName(bodyId, '20 mm orange sphere'); scene.nodeSetPrimType(bodyId, scene.PrimitiveType.Sphere); scene.nodeSetSize(bodyId, { x: diameter, y: diameter, z: diameter }); scene.nodeSetPos(bodyId, { x: 0, y: diameter / 2, z: 0 }); const materialId = scene.materialCreate(); scene.materialSetColor(materialId, { r: 255, g: 128, b: 0 }); scene.nodeSetMaterialId(bodyId, materialId); return { areaId, bodyId }; }); print(result); await emitImage(await womp.scene.screenshot());",
132
132
  ],
133
133
  },
134
134
  ],
@@ -149,12 +149,11 @@ A failed script can retain earlier committed effects. Use receipts and inspect u
149
149
  }
150
150
  };
151
151
  return {
152
- read: async () => ({ ...await host.read(context), health: await health() }),
153
152
  health,
154
- edit: (callback, expectedRevision) => {
153
+ access: (callback) => {
155
154
  if (typeof callback !== "function")
156
- throw new Error("scene.edit requires a callback.");
157
- return host.edit(callback, z.string().min(1).parse(expectedRevision), context);
155
+ throw new Error("scene.access requires a callback.");
156
+ return host.access(callback, context);
158
157
  },
159
158
  screenshot: (options) => host.screenshot(screenshotOptions.parse(options ?? {}), context),
160
159
  };