Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add bounded agent scene authoring sessions

Nguyen Xuan An23a871de7f64
diff --git a/.gitignore b/.gitignore
index cff3b1be..90f2f100 100644
--- a/.gitignore
+++ b/.gitignore
@@ -35,3 +35,4 @@ public/lighting.md
public/volumetric.md
public/film-physics.md
public/surface-attachment.md
+public/agent-scene.md
diff --git a/CHANGELOG.md b/CHANGELOG.md
index feaf63e4..f335b89a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,10 @@
# Changelog
+## Unreleased
+
+- Add optional agent scene sessions with stable IDs, shared geometry, revision checks, atomic edits and bounded checkpoints.
+- Prioritize agent authoring, visual feedback and MCP integration in the implementation roadmap.
+
## 0.4.1
- Put installation on the homepage with npm, pnpm, Yarn and Bun controls.
diff --git a/README.md b/README.md
index db9b3a9a..41cd5b71 100644
--- a/README.md
+++ b/README.md
@@ -1,10 +1,11 @@
# 67.js
-**Your 3D scene, from browser to film.**
+**3D scenes agents can inspect, edit and render.**
Explore the [showcase](https://67js.codepawl.com), read the [documentation](https://67js.codepawl.com/docs.html), or give an agent the [plain-text guide](https://67js.codepawl.com/llms.txt).
-67.js is a JavaScript graphics engine for interactive worlds, animated models and cinematic media in the browser.
+67.js develops JavaScript tools for agent-driven 3D authoring, browser previews and image/video rendering.
+The published engine supplies interactive worlds, animated models and cinematic media. The current source adds bounded scene authoring sessions.
Meshes, materials and cameras give Three.js users a familiar foundation. Scene studios, assembly inspection and image/video export extend that foundation into a production workflow.
The renderer is designed around shared geometry, predictable frame allocation and explicit CPU/GPU render budgets.
@@ -121,6 +122,13 @@ The repository includes two reusable Codex skills.
- [build-67js-scene](skills/build-67js-scene/SKILL.md) covers geometry, materials, cameras, interaction and anti-aliasing.
- [render-67js-media](skills/render-67js-media/SKILL.md) covers CPU/GPU presets, streaming exports and memory measurements.
+## Agent authoring
+
+The current source includes [agent scene sessions](docs/agent-scene.md), newer than npm `0.4.1`.
+Agents can author JSON recipes, inspect object bounds, submit atomic edits and restore bounded checkpoints.
+The optional addon retains renderer-facing parts and geometry across supported edits.
+An MCP server and persistent render jobs remain implementation work.
+
## Checks and performance
1. Run `npm test` to validate geometry, scene budgets, the timeline and independent GLB loading.
diff --git a/ROADMAP.md b/ROADMAP.md
index 1a9b9818..7b7c41bf 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -1,6 +1,6 @@
# 67.js implementation roadmap
-67.js develops a browser graphics engine with a shared workflow for interactive scenes, animation and exported media.
+67.js develops 3D authoring and rendering tools for agents, with browser previews, deterministic animation and exported media.
This document separates shipping capabilities from work in progress. Performance claims require measurements on matching scenes and hardware.
## Available
@@ -22,11 +22,14 @@ This document separates shipping capabilities from work in progress. Performance
## Next
-1. Adaptive quality with a target frame time, explicit minimum resolution and stable changes to avoid visible oscillation.
-2. GPU timing and scene diagnostics that distinguish CPU submission, GPU work and estimated memory.
-3. Picking and reusable interaction controls for object selection, annotations and assembly inspection.
-4. Asset budgets and loading diagnostics for AI-generated models, including texture sizes, unsupported materials and geometry complexity.
-5. Declarative scene recipes for product viewers, interactive worlds and short films, with reusable camera and lighting presets.
+The current source, after npm `0.4.1`, includes fixed-topology agent scenes with stable IDs, atomic revisioned edits and checkpoints.
+
+1. Extend agent sessions with dynamic node and resource creation while preserving bounded allocation, replay and undo.
+2. An MCP adapter with capability discovery, compact scene inspection and visual feedback from multiple angles and animation frames.
+3. Persistent render jobs with progress, cancellation, explicit CPU/GPU budgets and deterministic image and video export.
+4. Geometry, rig and asset diagnostics that help agents correct intersections, invalid transforms and unsupported materials.
+5. Agent workflows for imported assets, sculpting, surface fitting, lighting and animation, verified against rendered reference scenes.
+6. GPU timing and adaptive quality based on measured frame time, with stable resolution changes and explicit minimum quality.
## Longer term
diff --git a/docs/agent-scene.md b/docs/agent-scene.md
new file mode 100644
index 00000000..5f769fb9
--- /dev/null
+++ b/docs/agent-scene.md
@@ -0,0 +1,202 @@
+# Agent scene authoring
+
+This addon is available in the current source checkout, after npm release `0.4.1`.
+It is not included in the published `0.4.1` package.
+
+The optional `agent-scene` addon creates bounded CPU scenes from JSON recipes and applies atomic editing commands.
+It returns retained renderer parts with shared geometry and material resources.
+It does not execute JavaScript, access the DOM, or provide an MCP transport.
+
+```js
+import { Renderer67 } from '67js';
+import { createAgentScene, AGENT_SCENE_CAPABILITIES } from '67js/addons/agent-scene';
+
+const scene = createAgentScene({
+ format: '67js.scene',
+ schemaVersion: 1,
+ geometries: [{ id: 'cube', type: 'box', bevel: 0 }],
+ materials: [{ id: 'blue', color: [0.1, 0.3, 0.8] }],
+ nodes: [
+ { id: 'group', label: 'Assembly' },
+ { id: 'mesh', parent: 'group', geometry: 'cube', material: 'blue' },
+ ],
+});
+
+const renderer = new Renderer67(canvas, scene.parts, { ground: false });
+const checkpoint = scene.checkpoint();
+scene.apply([
+ { type: 'set-node', id: 'group', translation: [1, 0, 0] },
+ { type: 'set-material', id: 'blue', roughness: 0.3 },
+], { expectedRevision: scene.revision });
+renderer.updateParts(scene.parts);
+renderer.render(scene.camera);
+scene.restore(checkpoint, { expectedRevision: scene.revision });
+renderer.updateParts(scene.parts);
+renderer.render(scene.camera);
+scene.releaseCheckpoint(checkpoint);
+```
+
+`AGENT_SCENE_CAPABILITIES` and `scene.capabilities` describe the same frozen capability object.
+The renderer owns GPU allocation and disposal.
+The authoring session does not allocate GPU resources.
+The normal frame loop can render retained parts without calling inspection or exporting the recipe.
+
+## Recipe contract
+
+The recipe must contain `format`, `schemaVersion`, `geometries`, `materials`, and `nodes`.
+The optional `camera` object supplies a perspective camera.
+All objects reject unknown keys.
+Inputs must contain plain, finite, acyclic JSON data without accessors, sparse arrays, or executable values.
+JSON nesting has a fixed maximum of 64 levels.
+
+Each resource and node has a unique `id` within its collection.
+IDs contain 1 to 128 characters and must contain a non-space character.
+Node labels contain at most 256 characters.
+Labels can repeat and change without changing identity.
+Renderer `part.name` contains the stable node ID.
+
+Geometry records contain `id`, `type`, and the flat fields below.
+Omitted parameters use the existing generator defaults.
+The generators also enforce their existing numeric and modeling constraints.
+
+| Type | Fields | Defaults |
+| --- | --- | --- |
+| `box` | `bevel`, `subdivisions` | `0.08`, `6` |
+| `cylinder` | `segments`, `bevel`, `bevelSegments` | `80`, `0.025`, `6` |
+| `sphere` | `segments`, `rings` | `64`, `40` |
+| `torus` | `tubeRadius`, `segments`, `sides`, `arc`, `start` | `0.08`, `96`, `24`, `2π`, `0` |
+| `lathe` | `profile`, `segments`, `startAngle`, `sweep` | Required XY profile, `64`, `0`, `2π` |
+| `extrude` | `contour`, `holes`, `depth`, `steps`, `bevel`, `bevelThickness`, `bevelSegments` | Required XY contour, `[]`, `1`, `1`, `0`, bevel, `3` |
+| `tube` | `path`, `radius`, `segments`, `radialSegments`, `closed` | Required XYZ path, `0.1`, `64`, `12`, `false` |
+
+Modeling point inputs have a maximum of 4096 points.
+An extrusion has at most 128 holes and 4096 total contour points.
+Shared resource IDs generate geometry once, regardless of the number of mesh nodes.
+
+Materials contain `id`, `tag`, `color`, `metallic`, `roughness`, `emission`, and optional `emissiveColor`.
+The defaults are `surface`, `[0.5, 0.5, 0.5]`, `0`, `0.5`, and `0`.
+The tag can be `surface` or `unlit` and remains fixed during editing.
+Colors use linear RGB.
+
+Base color, metallic, and roughness range from zero to one.
+Emission and independent emissive color must be nonnegative finite Float32 numbers.
+Their component products must also remain finite at Float32 precision.
+Unlit emissive radiance is capped at 65500 per component to fit the half-float HDR target.
+Textures and procedural material tags are outside this version.
+
+Nodes contain `id`, optional `label`, `parent`, `translation`, `rotation`, and `scale`.
+Mesh nodes also require both `geometry` and `material` resource IDs.
+Group nodes have neither resource reference.
+The default parent is `null`.
+The default transform is `[0, 0, 0]`, `[0, 0, 0, 1]`, and `[1, 1, 1]`.
+Rotation uses an XYZW quaternion that the session normalizes.
+
+Quaternions must be finite and nonzero.
+Scales must remain positive at Float32 precision.
+The scene graph rejects missing parents, cycles, excessive depth, singular transforms, and world transforms that overflow Float32.
+Normal transforms must also remain finite.
+Cached local geometry bounds provide a conservative world Float32 check from eight corners per mesh.
+The check bounds the sum of absolute matrix products, so intermediate shader arithmetic cannot overflow before cancellation.
+
+The camera contains `eye`, `target`, `up`, `fov`, `near`, and `far`.
+Its defaults are `[4, 3, 5]`, `[0, 0, 0]`, `[0, 1, 0]`, `45`, `0.1`, and `1000`.
+FOV uses degrees and ranges between zero and 180.
+The clipping range must satisfy `0 < near < far` at Float32 precision.
+Eye and target must differ at Float32 precision.
+The session normalizes the nonzero up vector and rejects collinear view directions.
+
+View and projection matrices must remain finite and nonsingular at Float32 precision.
+Projection validation uses aspect one because the renderer owns the actual target aspect.
+An explicit top view can use `eye: [0, 3, 0]`, `target: [0, 0, 0]`, and `up: [0, 0, -1]`.
+
+## Transactions and ownership
+
+`apply(operations, { expectedRevision })` requires the current revision and returns the new revision.
+It rejects an empty command list.
+Each successful application increments the revision once, including a command that retains existing values.
+Stale revisions and invalid commands leave canonical state, published matrices, materials, and the revision unchanged.
+Every command in a batch stages before any command publishes.
+
+| Operation | Fields |
+| --- | --- |
+| `set-node` | `id`, optional `translation`, `rotation`, `scale`, `parent`, `label` |
+| `set-material` | `id`, optional `color`, `metallic`, `roughness`, `emission`, `emissiveColor` |
+| `set-camera` | Optional `eye`, `target`, `up`, `fov`, `near`, `far` directly on the command |
+
+Node membership and resource definitions remain fixed.
+Reparenting changes hierarchy while preserving each node's local transform.
+Adding or removing nodes, changing geometry, and changing material tags require a new session.
+
+The session copies input recipes and commands.
+`exportRecipe()` and `camera` return detached JSON snapshots.
+Published material objects are frozen and expose immutable arrays through retained getters.
+Renderer parts, matrices, geometries, and material objects retain their identities across successful edits and restores.
+Material reads do not allocate arrays or scan resource collections.
+
+`parts` is a privileged renderer adapter surface.
+Its geometry typed arrays follow the engine's immutable geometry contract and must never change or detach.
+The session does not duplicate geometry buffers or regenerate geometry during transactions.
+Writes to retained matrices cannot poison the private recipe or inspection transforms.
+
+A successful transaction overwrites those matrices from canonical state.
+Detached matrices reject publication before canonical state changes.
+An agent adapter must expose JSON commands and snapshots rather than renderer typed arrays.
+
+`checkpoint()` returns an opaque, frozen handle that belongs to its session.
+Checkpoint snapshots are private and cannot change through the handle.
+`restore(handle, { expectedRevision })` applies the same atomic validation and increments the revision.
+Released and foreign handles fail.
+`releaseCheckpoint(handle)` frees its slot and does not change the scene revision.
+
+## Budgets and inspection
+
+The optional second constructor argument overrides the following positive integer limits.
+`scene.limits` reports the resolved, frozen values.
+
+| Limit | Default |
+| --- | --- |
+| `maxNodes` | `4096`, also the hard maximum |
+| `maxDepth` | `256`, counting a root as depth one |
+| `maxGeometries` | `256` |
+| `maxMaterials` | `256` |
+| `maxVertices` | `250000`, summed across unique geometries |
+| `maxGeometryBytes` | `33554432` |
+| `maxOperations` | `256`, per application |
+| `maxCheckpoints` | `8` |
+| `maxRecipeBytes` | `1048576`, also used for each command batch |
+
+Preflight sums conservative vertex counts before any geometry generation.
+Its byte bound uses 56 bytes per vertex for eight floats and at most six Uint32 indices.
+Actual generated geometry bytes must also fit the budget.
+
+Byte counts include position, normal, UV, and index typed arrays across unique geometries.
+They exclude JavaScript object overhead, temporary generator allocations, transaction matrices, checkpoints, and renderer GPU memory.
+The JSON budget uses conservative UTF-8 traversal accounting and also checks serialized JSON size.
+Normalization can increase serialized size, so normalized recipes also pass the JSON budget.
+Each checkpoint stores at most one normalized recipe within that limit.
+
+`inspect({ ids, limit, includeBounds })` returns compact JSON with the current revision, global counts, and selected node records.
+Its default limit is 64, capped by `maxNodes`.
+Requested IDs must exist.
+
+`truncated` reports whether the result omitted selected nodes.
+Global counts include nodes, render parts, unique geometries, materials, and unique geometry vertices.
+`geometryBytes` reports actual unique typed array bytes.
+`estimatedGeometryBytes` reports the conservative preflight bound.
+Inspection does not report GPU timing or renderer allocation.
+
+With `includeBounds: true`, each mesh record includes `{ min, max }` from every transformed geometry vertex.
+Group bounds are `null`.
+Bounds use published canonical world matrices, not externally modified renderer matrices.
+They describe the authored mesh surface without shader effects or displacement.
+
+## Design choice
+
+| Design | Benefit | Cost |
+| --- | --- | --- |
+| Evaluate arbitrary JavaScript scene functions | Full access to existing engine functions | Execution authority, mutable ownership, and replay depend on external isolation |
+| Validate JSON recipes and typed commands | Bounded inputs, private ownership, atomic batches, and reproducible snapshots | A deliberately limited geometry and editing vocabulary |
+
+The addon uses validated JSON because ownership and atomic editing form its public contract.
+A future MCP adapter can translate tool calls into this API without placing transport logic inside the scene session.
+This version does not claim Blender feature parity.
diff --git a/docs/guide.md b/docs/guide.md
index dc7e967f..f5a790c3 100644
--- a/docs/guide.md
+++ b/docs/guide.md
@@ -400,6 +400,12 @@ Disconnect observers, cancel animation frames, release pointer state and call `d
## Models and AI agents
+The current source includes [agent scene sessions](/agent-scene.md), newer than npm `0.4.1`.
+The addon accepts JSON recipes with stable object IDs, shared geometry and material resources, hierarchy and a camera.
+Edits use an expected revision and commit as one batch. Checkpoints restore the supported scene state.
+The session keeps existing renderer-facing parts and matrices for transform, material and camera edits.
+This CPU authoring API does not yet provide an MCP server or background render jobs.
+
Give the agent this guide and the matching repository skill. Start with a scene brief: focal subject, visual references, camera, output size, required interaction, GPU/CPU backend and memory budget. Read the matching scene recipe and run the smallest trial first.
Suggested prompt: “Use 67.js to build an interactive mechanical study. Reuse meshes, use a 256MiB render budget, provide orbit and keyboard controls, pause hidden playback, and capture a real wide and mobile preview. List unsupported features. Do not claim speed superiority without a comparable benchmark.”
diff --git a/package.json b/package.json
index fd63a969..97179c4e 100644
--- a/package.json
+++ b/package.json
@@ -3,7 +3,7 @@
"version": "0.4.1",
"private": false,
"type": "module",
- "description": "A browser graphics engine for interactive worlds, animation and cinematic media, with memory-aware CPU/GPU export",
+ "description": "JavaScript tools for agent-driven 3D authoring, browser previews and memory-aware CPU/GPU rendering",
"license": "MIT",
"homepage": "https://67js.codepawl.com",
"repository": {
@@ -41,7 +41,8 @@
"docs/mesh-query.md",
"docs/primitives.md",
"docs/shrinkwrap.md",
- "docs/surface-attachment.md"
+ "docs/surface-attachment.md",
+ "docs/agent-scene.md"
],
"main": "./build/67.module.js",
"module": "./build/67.module.js",
@@ -60,6 +61,7 @@
"./addons/shrinkwrap": "./build/shrinkwrap.js",
"./addons/surface-attachment": "./build/surface-attachment.js",
"./addons/physics": "./build/physics.js",
+ "./addons/agent-scene": "./build/agent-scene.js",
"./package.json": "./package.json"
},
"scripts": {
diff --git a/public/llms.txt b/public/llms.txt
index c10256c7..68a5f4ab 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -7,6 +7,12 @@ The installed package determines available APIs. Release metadata describes the
## Read only what your task needs
+The current source adds `67js/addons/agent-scene`, newer than npm `0.4.1`.
+Read `/agent-scene.md` for versioned JSON recipes, stable IDs, expected revisions, atomic edits and bounded checkpoints.
+Use `session.inspect()` for compact object facts and `session.exportRecipe()` for detached JSON.
+Keep renderer-facing geometry immutable. Call `renderer.updateParts(session.parts)` after a successful edit or restore.
+This addon does not expose an MCP server or a render job queue.
+
- [Release metadata](https://67js.codepawl.com/release.json): package name, version, publication status, install command, module URL and commit.
- [Complete plain-text guide](https://67js.codepawl.com/guide.md): renderer, parts, materials, cameras, animation, lifecycle, export and troubleshooting.
- [GLB contract](https://67js.codepawl.com/gltf.md): supported assets and conversion limits. Read before selecting or importing a model.
@@ -92,12 +98,14 @@ Surface clearance prevents overlapping layers in this workflow. It does not dete
`addons/mesh-query` owns copied static geometry in disposable BVH indices. Read `docs/mesh-query.md` before querying.
Use `solid: true` indices and `mode: 'closed-solids'` to distinguish boundary contact, containment and separation.
Surface contact does not prove volume penetration or identify z-fighting. Never substitute surface-only results for containment.
+
Pass current affine matrices explicitly, rebuild after geometry edits, and preserve budget/precision errors instead of treating them as misses.
Read `docs/primitives.md` for subdivision bounds and exact seam closure. Skin, morph and shader-deformed surfaces require geometry matching the visible pose.
`addons/shrinkwrap` returns {geometry,stats} in target-local coordinates. Read `docs/shrinkwrap.md` before choosing nearest/project modes.
Supply sourceToTarget explicitly for different local frames. Share the target matrix with the output part and keep the total callback budget.
-Nearest projection can collapse vertices on coarse meshes; preserve the error and refine the target or choose a suitable projection direction.
+Nearest projection can collapse vertices on coarse meshes. Preserve the error and refine the target or choose a suitable projection direction.
+
Vertex clearance does not certify whole-triangle clearance. Compatible static output can become a GPU morph target without repeating queries per frame.
GLB support excludes transparent and double-sided materials and compressed geometry. Unsupported features require visible errors.
@@ -105,6 +113,7 @@ GLB support excludes transparent and double-sided materials and compressed geome
Version `0.4.1` adds `addons/surface-attachment`. Read `docs/surface-attachment.md` before binding.
Bind a triangle and barycentric coordinates once. Assign the retained attachment.matrix to the accessory.
Update the target morph/skin/world pose, call attachment.update(), then upload target and accessory through renderer.updateParts().
+
Clearance uses world units and the geometric face normal. This rigid point attachment does not guarantee clearance over the entire accessory footprint.
The optional GLB decoder uses Three.js GLTFLoader. The renderer remains 67.js.
diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjs
index 6d66d57a..ab270cf1 100644
--- a/scripts/prepare-release.mjs
+++ b/scripts/prepare-release.mjs
@@ -40,7 +40,7 @@ const sourceDocuments = [
'gltf-morph.md', 'morph-targets.md', 'skinning.md', 'physics.md',
'export-glb.md', 'sculpt.md', 'surface.md', 'mesh-query.md', 'primitives.md', 'shrinkwrap.md',
'camera-path.md', 'lighting.md', 'volumetric.md', 'film-physics.md',
- 'surface-attachment.md',
+ 'surface-attachment.md', 'agent-scene.md',
];
for (const name of sourceDocuments) {
await copyFile(resolve(root, 'docs', name), resolve(root, 'public', name));
diff --git a/scripts/smoke-agent-scene.mjs b/scripts/smoke-agent-scene.mjs
new file mode 100644
index 00000000..f689d757
--- /dev/null
+++ b/scripts/smoke-agent-scene.mjs
@@ -0,0 +1,147 @@
+import assert from 'node:assert/strict';
+import { mkdir, writeFile } from 'node:fs/promises';
+import { constants, setPriority } from 'node:os';
+import { chromium } from 'playwright';
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+const width = Number(process.argv[2] ?? 960);
+const height = Number(process.argv[3] ?? 540);
+const origin = process.argv[4] ?? 'http://127.0.0.1:5173';
+await mkdir('artifacts', { recursive: true });
+const recipe = {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [
+ { id: 'pedestal', type: 'lathe', profile: [[0,0],[0.8,0],[0.9,0.07],[0.9,0.16],[0.74,0.22],[0.48,0.28],[0.42,0.34],[0,0.34]], segments: 64 },
+ { id: 'bulb', type: 'sphere', segments: 48, rings: 32 },
+ { id: 'ring', type: 'torus', tubeRadius: 0.025, segments: 80, sides: 12 },
+ { id: 'post', type: 'cylinder', segments: 40, bevel: 0.02, bevelSegments: 4 },
+ { id: 'rail', type: 'tube', path: [[-0.65,-0.35,0],[-0.68,0.3,0],[-0.5,1.05,0],[0,1.38,0],[0.5,1.05,0],[0.68,0.3,0],[0.65,-0.35,0]], radius: 0.026, segments: 80, radialSegments: 12 },
+ { id: 'fin', type: 'extrude', contour: [[0,0],[0.28,0],[0.38,0.2],[0.18,0.4],[0,0.32]], depth: 0.035, bevel: 0.008, bevelSegments: 2 },
+ { id: 'panel', type: 'box', bevel: 0.06, subdivisions: 4 },
+ ],
+ materials: [
+ { id: 'porcelain', color: [0.7,0.8,0.77], metallic: 0.15, roughness: 0.27 },
+ { id: 'brass', color: [0.58,0.3,0.06], metallic: 0.85, roughness: 0.25 },
+ { id: 'teal', color: [0.015,0.12,0.14], metallic: 0.72, roughness: 0.3 },
+ { id: 'light', color: [0.23,0.8,0.65], metallic: 0.1, roughness: 0.21, emission: 2, emissiveColor: [0.23,0.8,0.65] },
+ ],
+ nodes: [
+ { id: 'lamp', label: 'Aster lamp', translation: [0,0.82,0] },
+ { id: 'foot', parent: 'lamp', geometry: 'pedestal', material: 'porcelain', translation: [0,-0.8,0] },
+ { id: 'stem', parent: 'lamp', geometry: 'post', material: 'teal', translation: [0,-0.15,0], scale: [0.12,0.72,0.12] },
+ { id: 'glow', parent: 'lamp', geometry: 'bulb', material: 'light', translation: [0,0.55,0], scale: [0.3,0.48,0.3] },
+ { id: 'switch', parent: 'lamp', geometry: 'panel', material: 'teal', translation: [0,-0.65,0.82], scale: [0.16,0.06,0.04] },
+ ],
+ camera: { eye: [3.7,2.82,4.6], target: [0,1.06,0], fov: 36, near: 0.1, far: 40 },
+};
+for (let index = 0; index < 4; index++) {
+ const angle = index * Math.PI / 4;
+ recipe.nodes.push({ id: `rail-${index}`, parent: 'lamp', geometry: 'rail', material: 'brass', rotation: [0,Math.sin(angle/2),0,Math.cos(angle/2)] });
+}
+for (let index = 0; index < 3; index++) {
+ recipe.nodes.push({ id: `ring-${index}`, parent: 'lamp', geometry: 'ring', material: index === 1 ? 'teal' : 'brass', translation: [0,-0.38 + index * 0.34,0], scale: [0.65,0.65,0.65], rotation: [Math.SQRT1_2,0,0,Math.SQRT1_2] });
+}
+for (let index = 0; index < 8; index++) {
+ const angle = index * Math.PI / 4;
+ recipe.nodes.push({ id: `fin-${index}`, parent: 'lamp', geometry: 'fin', material: 'brass', translation: [Math.sin(angle)*0.43,-0.46,Math.cos(angle)*0.43], rotation: [0,Math.sin(angle/2),0,Math.cos(angle/2)], scale: [0.4,0.4,0.4] });
+}
+const harness = `<!doctype html><html><head><style>html,body{margin:0;height:100%;background:#152126}canvas{width:100vw;height:100vh;display:block}</style></head><body><canvas id="scene"></canvas><script type="module">
+import {createAgentScene} from '/src/agent-scene.js';
+import {Renderer67} from '/src/renderer.js';
+import {exportGlb} from '/src/export.js';
+const session=createAgentScene(${JSON.stringify(recipe)});
+const renderer=new Renderer67(document.querySelector('canvas'),session.parts,{ground:true,hdr:true,samples:4,pixelRatio:1,memoryBudgetMiB:192});
+const effects={bloom:{strength:0.12,threshold:1,radius:1},saturation:1,contrast:1,temperature:0,vignette:0,grain:0};
+function draw() {
+ renderer.updateParts(session.parts);
+ renderer.render({...session.camera,effects});
+}
+function pixels() {
+ const context = renderer.context;
+ const buffer = new Uint8Array(context.drawingBufferWidth * context.drawingBufferHeight * 4);
+ context.readPixels(0,0,context.drawingBufferWidth,context.drawingBufferHeight,context.RGBA,context.UNSIGNED_BYTE,buffer);
+ return buffer;
+}
+draw();
+window.__agentFixture = {
+ session, renderer, draw, pixels,
+ exportSnapshot: () => Array.from(new Uint8Array(exportGlb(session.parts))),
+};
+</script></body></html>`;
+await writeFile('artifacts/agent-scene-harness.html', harness);
+const browser = await chromium.launch({executablePath:'C:/Program Files/Google/Chrome/Application/chrome.exe',headless:true,args:['--enable-webgl','--ignore-gpu-blocklist']});
+try {
+ const page = await browser.newPage({viewport:{width,height},reducedMotion:'reduce'});
+ const errors=[];
+ page.on('pageerror',error=>errors.push(error.message));
+ await page.goto(`${origin}/artifacts/agent-scene-harness.html`);
+ await page.waitForFunction(()=>window.__agentFixture);
+ await page.screenshot({path:`artifacts/agent-scene-${width}x${height}-before.png`});
+ const result=await page.evaluate(()=>{
+ const {session,renderer,draw,pixels}=window.__agentFixture;
+ const parts=[...session.parts];
+ const matrices=parts.map(part=>part.matrix);
+ const geometries=parts.map(part=>part.geometry);
+ const checkpoint=session.checkpoint();
+ // Read the freshly rendered buffer before browser compositing may clear it.
+ draw();
+ const before=pixels();
+ const creation={buffer:0,texture:0,framebuffer:0,renderbuffer:0};
+ for(const [name,key] of [['createBuffer','buffer'],['createTexture','texture'],['createFramebuffer','framebuffer'],['createRenderbuffer','renderbuffer']]){
+ const original=renderer.context[name].bind(renderer.context);
+ renderer.context[name]=(...args)=>{
+ creation[key]++;
+ return original(...args);
+ };
+ }
+ session.apply([{type:'set-node',id:'lamp',translation:[0.18,0.82,0]},{type:'set-node',id:'glow',translation:[0,0.75,0],scale:[0.34,0.3,0.34]},{type:'set-material',id:'light',color:[0.9,0.28,0.04],emissiveColor:[0.9,0.28,0.04]}],{expectedRevision:session.revision});
+ draw();
+ const after=pixels();
+ let changed=0;
+ for(let index=0;index<before.length;index++) {
+ if(before[index]!==after[index]) {
+ changed++;
+ }
+ }
+ window.__agentFixture.restore=()=>{
+ session.restore(checkpoint,{expectedRevision:session.revision});
+ draw();
+ session.releaseCheckpoint(checkpoint);
+ };
+ window.__agentFixture.before=before;
+ return {changed,creation,identities:parts.every((part,index)=>part===session.parts[index]&&matrices[index]===part.matrix&&geometries[index]===part.geometry),inspection:session.inspect(),revision:session.revision,estimatedBytes:renderer.memoryPlan.estimatedBytes,glError:renderer.context.getError(),backend:renderer.context.getParameter(renderer.context.getExtension('WEBGL_debug_renderer_info').UNMASKED_RENDERER_WEBGL)};
+ });
+ await page.screenshot({path:`artifacts/agent-scene-${width}x${height}-after.png`});
+ const restored=await page.evaluate(()=>{
+ const fixture=window.__agentFixture;
+ fixture.restore();
+ const pixels=fixture.pixels();
+ return {equal:pixels.every((value,index)=>value===fixture.before[index]),revision:fixture.session.revision,glError:fixture.renderer.context.getError()};
+ });
+ assert.deepEqual(errors,[]);
+ assert.ok(result.changed>1000);
+ assert.ok(result.identities);
+ assert.deepEqual(result.creation,{buffer:0,texture:0,framebuffer:0,renderbuffer:0});
+ assert.ok(restored.equal,'Checkpoint restore must reproduce the original rendered frame');
+ assert.equal(result.glError,0);
+ assert.equal(restored.glError,0);
+ assert.ok(result.estimatedBytes<=192*1048576);
+ await page.screenshot({path:`artifacts/agent-scene-${width}x${height}-restored.png`});
+ const topView = await page.evaluate(() => {
+ const { session, renderer, draw } = window.__agentFixture;
+ session.apply([{ type: 'set-camera', eye: [0, 5.5, 0], target: [0, 1.06, 0], up: [0, 0, -1] }], { expectedRevision: session.revision });
+ draw();
+ return { revision: session.revision, glError: renderer.context.getError() };
+ });
+ assert.equal(topView.glError, 0);
+ await page.screenshot({path:`artifacts/agent-scene-${width}x${height}-top.png`});
+ const snapshot = Buffer.from(await page.evaluate(() => window.__agentFixture.exportSnapshot()));
+ assert.equal(snapshot.readUInt32LE(0), 0x46546c67);
+ assert.equal(snapshot.readUInt32LE(4), 2);
+ assert.equal(snapshot.readUInt32LE(8), snapshot.byteLength);
+ await writeFile(`artifacts/agent-scene-${width}x${height}.glb`, snapshot);
+ await writeFile(`artifacts/agent-scene-${width}x${height}.json`,JSON.stringify({result,restored},null,2));
+ console.log(JSON.stringify({width,height,changed:result.changed,allocations:result.creation,retained:result.identities,restore:restored.equal,backend:result.backend,estimatedBytes:result.estimatedBytes}));
+} finally {
+ await browser.close();
+}
diff --git a/scripts/smoke-package.mjs b/scripts/smoke-package.mjs
index f03d74f4..d15e4096 100644
--- a/scripts/smoke-package.mjs
+++ b/scripts/smoke-package.mjs
@@ -129,6 +129,23 @@ if (${!published || metadata.version !== '0.4.0'}) {
assert.ok(Math.abs(retainedMatrix[14] - 0.202) < 1e-6);
}
solidIndex.dispose();
+if (${!published}) {
+ const { createAgentScene } = await import('67js/addons/agent-scene');
+ const agentScene = createAgentScene({
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'cube', type: 'box', bevel: 0 }],
+ materials: [{ id: 'paint', color: [0.2, 0.4, 0.5] }],
+ nodes: [{ id: 'object', geometry: 'cube', material: 'paint' }],
+ });
+ const agentPart = agentScene.parts[0];
+ const agentCheckpoint = agentScene.checkpoint();
+ agentScene.apply([{ type: 'set-node', id: 'object', translation: [2, 0, 0] }], { expectedRevision: agentScene.revision });
+ assert.equal(agentPart, agentScene.parts[0]);
+ assert.equal(agentPart.matrix[12], 2);
+ agentScene.restore(agentCheckpoint, { expectedRevision: agentScene.revision });
+ assert.equal(agentPart.matrix[12], 0);
+ agentScene.releaseCheckpoint(agentCheckpoint);
+}
const parts = createModel();
assert.equal(parts.length, 574);
assert.ok(parts.every(part => assemblyOffset(part, 1).some(value => value !== 0)));
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index a73aeed2..02fcb347 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -29,6 +29,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- Static contact, ray hits or closed-solid containment use optional `src/mesh-query.js` and the checkout's `docs/mesh-query.md`.
- Static vertex wrapping uses optional `src/shrinkwrap.js` and the checkout's `docs/shrinkwrap.md`.
- A rigid accessory on a morphing or skinned surface uses optional `src/surface-attachment.js` and `docs/surface-attachment.md`.
+- Agent scene recipes use optional `src/agent-scene.js` and `docs/agent-scene.md`; verify source versus published availability before importing.
- An image or video export uses `render-67js-media`.
Read [scene-contract.md](references/scene-contract.md) before creating parts or changing materials.
diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.md
index bd0344c4..e7032f1a 100644
--- a/skills/build-67js-scene/references/scene-contract.md
+++ b/skills/build-67js-scene/references/scene-contract.md
@@ -130,7 +130,17 @@ Use `createSurfaceAttachment(target, { triangle, barycentric, clearance })` for
Read `docs/surface-attachment.md`. Share its retained `matrix` with the accessory, update the target pose, then update the attachment before renderer upload.
The frame follows relative morphs before four-influence skinning. Clearance uses world units and the geometric triangle normal.
Bind immutable geometry once. This sparse point attachment does not deform the accessory or certify clearance over its footprint.
-This addon follows the current source and is newer than npm `0.4.0`.
+The surface-attachment addon is included in npm `0.4.1`.
+
+Agent authoring uses `createAgentScene(recipe, limits)` from `67js/addons/agent-scene`.
+This addon is available in source after npm `0.4.1`; it is not included in that published package.
+Read `docs/agent-scene.md` for schema version one and its fixed resource topology.
+Start with capabilities and bounded inspection. Edit stable IDs through one `apply` batch with the current `expectedRevision`.
+Checkpoint before uncertain changes, inspect and render the result, then restore or release the checkpoint.
+Call `renderer.updateParts(session.parts)` after successful edits, then render the detached `session.camera` snapshot.
+Keep JSON commands and snapshots exposed to agents; retained matrices and immutable geometry belong to the renderer adapter.
+Do not inspect all vertex bounds in a frame loop. Memory estimates cover unique geometry arrays, not total RAM or VRAM.
+The scene addon does not implement MCP transport, dynamic node creation, asset search, or render jobs.
`cameraView('front' | 'right' | 'top')` returns an orthographic camera with the correct up vector.
`fitOrthographicHeight(bounds, view, aspect)` frames both model width and height.
diff --git a/src/agent-scene.js b/src/agent-scene.js
new file mode 100644
index 00000000..2d0f9f81
--- /dev/null
+++ b/src/agent-scene.js
@@ -0,0 +1,560 @@
+import { mat4, mat3 } from 'gl-matrix';
+import { box, cylinder, sphere, torus } from './geometry.js';
+import { lathe, extrude, tube } from './modeling.js';
+import { createSceneGraph } from './scene-graph.js';
+import { applyProjection } from './camera.js';
+
+const DEFAULT_LIMITS = Object.freeze({
+ maxNodes: 4096, maxDepth: 256, maxGeometries: 256, maxMaterials: 256,
+ maxVertices: 250_000, maxGeometryBytes: 32 * 1024 * 1024,
+ maxOperations: 256, maxCheckpoints: 8, maxRecipeBytes: 1024 * 1024,
+});
+const CAMERA_DEFAULTS = Object.freeze({ eye: [4, 3, 5], target: [0, 0, 0], up: [0, 1, 0], fov: 45, near: 0.1, far: 1000 });
+const NODE_FIELDS = ['translation', 'rotation', 'scale', 'parent', 'label'];
+const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor'];
+const CAMERA_FIELDS = Object.keys(CAMERA_DEFAULTS);
+
+export const AGENT_SCENE_CAPABILITIES = Object.freeze({
+ format: '67js.scene', schemaVersion: 1,
+ geometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube']),
+ operations: Object.freeze(['set-node', 'set-material', 'set-camera']),
+ materialTags: Object.freeze(['surface', 'unlit']),
+ fixedResources: true, checkpoints: true, positiveScaleOnly: true,
+});
+
+function knownKeys(value, allowed, label) {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ throw new TypeError(`${label} must be an object.`);
+ }
+ for (const key of Object.keys(value)) {
+ if (!allowed.includes(key)) {
+ throw new TypeError(`Unknown ${label} field: ${key}.`);
+ }
+ }
+}
+
+function resolveLimits(input) {
+ knownKeys(input, Object.keys(DEFAULT_LIMITS), 'limits');
+ const result = { ...DEFAULT_LIMITS, ...input };
+ for (const [key, value] of Object.entries(result)) {
+ if (!Number.isSafeInteger(value) || value <= 0) {
+ throw new RangeError(`${key} must be a positive safe integer.`);
+ }
+ }
+ if (result.maxNodes > 4096) {
+ throw new RangeError('maxNodes cannot exceed 4096.');
+ }
+ return Object.freeze(result);
+}
+
+// Copy only JSON data. Reject accessors before reading them and bound traversal before serialization.
+function copiedJson(input, maximum) {
+ let bytes = 0;
+ const ancestors = new Set();
+ const encoder = new TextEncoder();
+ function charge(count) {
+ bytes += count;
+ if (bytes > maximum) {
+ throw new RangeError('JSON exceeds maxRecipeBytes. Reduce the input.');
+ }
+ }
+ function copy(value, depth) {
+ if (depth > 64) {
+ throw new RangeError('JSON nesting exceeds 64 levels.');
+ }
+ if (value === null || typeof value === 'boolean') {
+ charge(value === null ? 4 : String(value).length);
+ return value;
+ }
+ if (typeof value === 'number' && Number.isFinite(value)) {
+ charge(String(value).length);
+ return value;
+ }
+ if (typeof value === 'string') {
+ if (value.length > maximum) {
+ throw new RangeError('JSON exceeds maxRecipeBytes.');
+ }
+ charge(encoder.encode(JSON.stringify(value)).length);
+ return value;
+ }
+ if (!value || typeof value !== 'object' || ancestors.has(value)) {
+ throw new TypeError('Recipe must contain finite, acyclic JSON data.');
+ }
+ const array = Array.isArray(value);
+ if (array && value.length > maximum) {
+ throw new RangeError('JSON exceeds maxRecipeBytes.');
+ }
+ if (!array && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {
+ throw new TypeError('Recipe objects must be plain JSON objects.');
+ }
+ ancestors.add(value);
+ charge(2);
+ const result = array ? [] : {};
+ const keys = Reflect.ownKeys(value);
+ for (const key of keys) {
+ if (array && key === 'length') continue;
+ if (typeof key !== 'string' || key === '__proto__') {
+ throw new TypeError('Invalid JSON key.');
+ }
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
+ if (!descriptor.enumerable || !Object.hasOwn(descriptor, 'value')) {
+ throw new TypeError('JSON accessors and hidden fields are unsupported.');
+ }
+ if (array && key !== String(result.length)) {
+ throw new TypeError('JSON arrays must be dense without extra fields.');
+ }
+ charge(array ? 1 : encoder.encode(JSON.stringify(key)).length + 2);
+ result[key] = copy(descriptor.value, depth + 1);
+ }
+ if (array && result.length !== value.length) {
+ throw new TypeError('JSON arrays must be dense without trailing holes.');
+ }
+ ancestors.delete(value);
+ return result;
+ }
+ const result = copy(input, 0);
+ if (encoder.encode(JSON.stringify(result)).length > maximum) {
+ throw new RangeError('JSON exceeds maxRecipeBytes.');
+ }
+ return result;
+}
+
+function finite(value, label) {
+ if (!Number.isFinite(value) || !Number.isFinite(Math.fround(value))) {
+ throw new TypeError(`${label} must be a finite Float32 number.`);
+ }
+ return value;
+}
+
+function vector(value, length, label) {
+ if (!Array.isArray(value) || value.length !== length) {
+ throw new TypeError(`${label} needs ${length} numbers.`);
+ }
+ return value.map(component => finite(component, label));
+}
+
+function defaultValue(value, fallback) {
+ return value === undefined ? fallback : value;
+}
+
+function integer(value, minimum, maximum, label) {
+ if (!Number.isInteger(value) || value < minimum || value > maximum) {
+ throw new RangeError(`${label} must be within ${minimum} and ${maximum}.`);
+ }
+ return value;
+}
+
+function identifier(value) {
+ if (typeof value !== 'string' || !value.trim() || value.length > 128) {
+ throw new TypeError('IDs must contain 1 to 128 characters.');
+ }
+ return value;
+}
+
+function resources(values, maximum, label, validate) {
+ if (!Array.isArray(values) || values.length > maximum) {
+ throw new RangeError(`${label} exceeds its resource limit or is not an array.`);
+ }
+ const seen = new Set();
+ return values.map(value => {
+ identifier(value?.id);
+ if (seen.has(value.id)) {
+ throw new RangeError(`Duplicate ${label} ID: ${value.id}.`);
+ }
+ seen.add(value.id);
+ return validate(value);
+ });
+}
+
+function materialFrom(value) {
+ knownKeys(value, ['id', 'tag', ...MATERIAL_FIELDS], 'material');
+ const result = { id: value.id, tag: defaultValue(value.tag, 'surface'), color: vector(defaultValue(value.color, [0.5, 0.5, 0.5]), 3, 'color'),
+ metallic: defaultValue(value.metallic, 0), roughness: defaultValue(value.roughness, 0.5), emission: defaultValue(value.emission, 0) };
+ if (!AGENT_SCENE_CAPABILITIES.materialTags.includes(result.tag)) {
+ throw new RangeError('Material tag must be surface or unlit.');
+ }
+ for (const field of ['metallic', 'roughness']) {
+ finite(result[field], field);
+ if (result[field] < 0 || result[field] > 1) {
+ throw new RangeError(`${field} must be within zero and one.`);
+ }
+ }
+ finite(result.emission, 'emission');
+ if (result.emission < 0 || result.color.some(component => component < 0 || component > 1)) {
+ throw new RangeError('Emission must be nonnegative and color must be within zero and one.');
+ }
+ if (value.emissiveColor !== undefined) {
+ result.emissiveColor = vector(value.emissiveColor, 3, 'emissiveColor');
+ if (result.emissiveColor.some(component => component < 0)) {
+ throw new RangeError('emissiveColor must be nonnegative.');
+ }
+ }
+ const emissiveColor = result.emissiveColor ?? result.color;
+ for (const component of emissiveColor) {
+ const radiance = Math.fround(component) * Math.fround(result.emission);
+ if (!Number.isFinite(Math.fround(radiance))) {
+ throw new RangeError('Emissive radiance exceeds Float32 range.');
+ }
+ if (result.tag === 'unlit' && radiance > 65500) {
+ throw new RangeError('Unlit emissive radiance exceeds the half-float HDR target range.');
+ }
+ }
+ return result;
+}
+
+function nodeFrom(value) {
+ knownKeys(value, ['id', 'geometry', 'material', ...NODE_FIELDS], 'node');
+ const result = { ...value, parent: value.parent ?? null,
+ translation: vector(defaultValue(value.translation, [0, 0, 0]), 3, 'translation'),
+ rotation: vector(defaultValue(value.rotation, [0, 0, 0, 1]), 4, 'rotation'),
+ scale: vector(defaultValue(value.scale, [1, 1, 1]), 3, 'scale') };
+ if (result.parent !== null) identifier(result.parent);
+ if (result.label !== undefined && (typeof result.label !== 'string' || result.label.length > 256)) {
+ throw new TypeError('label must be a string of at most 256 characters.');
+ }
+ if (result.scale.some(component => component <= 0 || Math.fround(component) <= 0)) {
+ throw new RangeError('scale must remain positive at Float32 precision.');
+ }
+ const length = Math.hypot(...result.rotation);
+ if (length === 0) {
+ throw new RangeError('rotation quaternion must be nonzero.');
+ }
+ result.rotation = result.rotation.map(component => component / length);
+ if ((value.geometry !== undefined) !== (value.material !== undefined)) {
+ throw new TypeError('Mesh nodes need both geometry and material IDs.');
+ }
+ if (value.geometry !== undefined) {
+ identifier(value.geometry);
+ identifier(value.material);
+ }
+ return result;
+}
+
+function cameraFrom(value = {}) {
+ knownKeys(value, CAMERA_FIELDS, 'camera');
+ const result = { ...CAMERA_DEFAULTS, ...value };
+ result.eye = vector(result.eye, 3, 'eye');
+ result.target = vector(result.target, 3, 'target');
+ result.up = vector(result.up, 3, 'up');
+ const upLength = Math.hypot(...result.up);
+ if (upLength === 0) {
+ throw new RangeError('Camera up must be nonzero.');
+ }
+ result.up = result.up.map(component => component / upLength);
+ for (const field of ['fov', 'near', 'far']) finite(result[field], field);
+ if (Math.fround(result.fov) <= 0 || Math.fround(result.fov) >= 180 || Math.fround(result.near) <= 0 || Math.fround(result.far) <= Math.fround(result.near)) {
+ throw new RangeError('Camera needs 0 < fov < 180 and 0 < near < far at Float32 precision.');
+ }
+ if (result.eye.every((component, axis) => Math.fround(component) === Math.fround(result.target[axis]))) {
+ throw new RangeError('Camera eye and target must differ at Float32 precision.');
+ }
+ const direction = result.target.map((component, axis) => component - result.eye[axis]);
+ const directionLength = Math.hypot(...direction);
+ const unit = direction.map(component => component / directionLength);
+ const crossLength = Math.hypot(unit[1] * result.up[2] - unit[2] * result.up[1],
+ unit[2] * result.up[0] - unit[0] * result.up[2], unit[0] * result.up[1] - unit[1] * result.up[0]);
+ if (Math.fround(crossLength) === 0) {
+ throw new RangeError('Camera up must not be collinear with the view direction.');
+ }
+ const view = mat4.lookAt(mat4.create(), result.eye, result.target, result.up);
+ const projection = applyProjection(mat4.create(), result, 1);
+ for (const matrix of [view, projection]) {
+ const determinant = mat4.determinant(matrix);
+ if (!matrix.every(Number.isFinite) || !Number.isFinite(determinant) || determinant === 0) {
+ throw new RangeError('Camera matrices must remain finite and nonsingular at Float32 precision.');
+ }
+ }
+ return result;
+}
+
+const GEOMETRY_FIELDS = {
+ box: ['bevel', 'subdivisions'], cylinder: ['segments', 'bevel', 'bevelSegments'],
+ sphere: ['segments', 'rings'], torus: ['tubeRadius', 'segments', 'sides', 'arc', 'start'],
+ lathe: ['profile', 'segments', 'startAngle', 'sweep'],
+ extrude: ['contour', 'holes', 'depth', 'steps', 'bevel', 'bevelThickness', 'bevelSegments'],
+ tube: ['path', 'radius', 'segments', 'radialSegments', 'closed'],
+};
+
+function geometryEstimate(value) {
+ if (!Object.hasOwn(GEOMETRY_FIELDS, value.type)) {
+ throw new TypeError('Unsupported geometry type.');
+ }
+ knownKeys(value, ['id', 'type', ...GEOMETRY_FIELDS[value.type]], 'geometry');
+ function detail(field, fallback, minimum, maximum) {
+ return integer(value[field] ?? fallback, minimum, maximum, field);
+ }
+ function points(input, size, minimum) {
+ if (!Array.isArray(input) || input.length < minimum || input.length > 4096) {
+ throw new RangeError('Geometry point count exceeds its limit.');
+ }
+ for (const point of input) vector(point, size, 'geometry point');
+ return input.length;
+ }
+ for (const field of GEOMETRY_FIELDS[value.type]) {
+ if (value[field] !== undefined && !['profile', 'contour', 'holes', 'path', 'closed'].includes(field)) finite(value[field], field);
+ }
+ switch (value.type) {
+ case 'box': return value.bevel === 0 ? 24 : 6 * (2 * detail('subdivisions', 6, 1, 128) + 2) ** 2;
+ case 'cylinder': return (detail('segments', 80, 3, 2048) + 1) * 2 * (detail('bevelSegments', 6, 1, 128) + 1) + 2 * ((value.segments ?? 80) + 2);
+ case 'sphere': return (detail('segments', 64, 3, 2048) + 1) * (detail('rings', 40, 2, 2048) + 1);
+ case 'torus': return (detail('segments', 96, 3, 2048) + 1) * (detail('sides', 24, 3, 128) + 1) + 2 * ((value.sides ?? 24) + 2);
+ case 'lathe': return (detail('segments', 64, 3, 2048) + 1) * points(value.profile, 2, 2);
+ case 'tube':
+ points(value.path, 3, value.closed ? 3 : 2);
+ if (value.closed !== undefined && typeof value.closed !== 'boolean') {
+ throw new TypeError('closed must be boolean.');
+ }
+ return (detail('segments', 64, 3, 2048) + 1) * (detail('radialSegments', 12, 3, 128) + 1);
+ case 'extrude': {
+ const holes = value.holes ?? [];
+ if (!Array.isArray(holes) || holes.length > 128) {
+ throw new RangeError('holes must contain at most 128 rings.');
+ }
+ const count = points(value.contour, 2, 3) + holes.reduce((total, hole) => total + points(hole, 2, 3), 0);
+ if (count > 4096) {
+ throw new RangeError('Extrude exceeds 4096 input points.');
+ }
+ const beveled = (value.bevel ?? 0) > 0 || (value.bevelThickness ?? value.bevel ?? 0) > 0;
+ return 6 * (count + holes.length * 2 - 2) + 6 * count * (detail('steps', 1, 1, 256) + (beveled ? detail('bevelSegments', 3, 1, 32) * 2 : 0));
+ }
+ }
+}
+
+function generateGeometry(value, maxVertices) {
+ switch (value.type) {
+ case 'box': return box(value.bevel, value.subdivisions);
+ case 'cylinder': return cylinder(value.segments, value.bevel, value.bevelSegments);
+ case 'sphere': return sphere(value.segments, value.rings);
+ case 'torus': return torus(value.tubeRadius, value.segments, value.sides, value.arc, value.start);
+ case 'lathe': return lathe(value.profile, { ...value, maxVertices });
+ case 'extrude': return extrude(value.contour, { ...value, maxVertices });
+ case 'tube': return tube(value.path, { ...value, maxVertices });
+ }
+}
+
+function compile(recipe, geometries, localBounds, limits) {
+ const materials = new Map(recipe.materials.map(material => [material.id, material]));
+ const graph = createSceneGraph(recipe.nodes.map(node => {
+ if (node.geometry !== undefined && (!geometries.has(node.geometry) || !materials.has(node.material))) {
+ throw new RangeError(`Node ${node.id} references an unknown resource.`);
+ }
+ return { name: node.id, parent: node.parent,
+ matrix: mat4.fromRotationTranslationScale(mat4.create(), node.rotation, node.translation, node.scale),
+ geometry: geometries.get(node.geometry), material: materials.get(node.material) };
+ }), limits);
+ const normal = mat3.create();
+ for (const node of graph.nodes) {
+ if (!mat3.normalFromMat4(normal, node.worldMatrix) || !normal.every(Number.isFinite)) {
+ throw new RangeError(`Node ${node.name} normal transform exceeds Float32 range.`);
+ }
+ if (node.geometry) {
+ const bounds = localBounds.get(node.geometry);
+ for (let corner = 0; corner < 8; corner++) {
+ const point = [0, 1, 2].map(axis => corner & (1 << axis) ? bounds.max[axis] : bounds.min[axis]);
+ for (let axis = 0; axis < 3; axis++) {
+ const matrix = node.worldMatrix;
+ // Bound every multiplication and possible addition order, before cancellation.
+ const absoluteSum = Math.abs(matrix[axis] * point[0]) + Math.abs(matrix[4 + axis] * point[1]) +
+ Math.abs(matrix[8 + axis] * point[2]) + Math.abs(matrix[12 + axis]);
+ if (!Number.isFinite(Math.fround(absoluteSum))) {
+ throw new RangeError(`Node ${node.name} world geometry bounds exceed Float32 range.`);
+ }
+ }
+ }
+ }
+ }
+ return graph;
+}
+
+function boundsFor(geometry, matrix) {
+ const minimum = [Infinity, Infinity, Infinity];
+ const maximum = [-Infinity, -Infinity, -Infinity];
+ const positions = geometry.positions;
+ for (let offset = 0; offset < positions.length; offset += 3) {
+ for (let axis = 0; axis < 3; axis++) {
+ const value = matrix[axis] * positions[offset] + matrix[4 + axis] * positions[offset + 1] + matrix[8 + axis] * positions[offset + 2] + matrix[12 + axis];
+ minimum[axis] = Math.min(minimum[axis], value);
+ maximum[axis] = Math.max(maximum[axis], value);
+ }
+ }
+ return { min: minimum, max: maximum };
+}
+
+/** A bounded CPU authoring session. Render adapters must treat geometry as immutable. */
+export function createAgentScene(input, inputLimits = {}) {
+ const limits = resolveLimits(inputLimits);
+ let recipe = copiedJson(input, limits.maxRecipeBytes);
+ knownKeys(recipe, ['format', 'schemaVersion', 'geometries', 'materials', 'nodes', 'camera'], 'recipe');
+ if (recipe.format !== '67js.scene' || recipe.schemaVersion !== 1) {
+ throw new RangeError('Expected 67js.scene schemaVersion 1.');
+ }
+ recipe.geometries = resources(recipe.geometries, limits.maxGeometries, 'geometries', value => value);
+ recipe.materials = resources(recipe.materials, limits.maxMaterials, 'materials', materialFrom);
+ recipe.nodes = resources(recipe.nodes, limits.maxNodes, 'nodes', nodeFrom);
+ recipe.camera = cameraFrom(recipe.camera);
+ const estimatedVertices = recipe.geometries.reduce((total, value) => total + geometryEstimate(value), 0);
+ // Every supported generator uses at most six Uint32 indices per vertex and eight floats per vertex.
+ const estimatedGeometryBytes = estimatedVertices * 56;
+ if (estimatedVertices > limits.maxVertices || estimatedGeometryBytes > limits.maxGeometryBytes) {
+ throw new RangeError('Geometry preflight exceeds maxVertices or maxGeometryBytes. Reduce detail.');
+ }
+ recipe = copiedJson(recipe, limits.maxRecipeBytes);
+ const geometries = new Map(recipe.geometries.map(value => [value.id, Object.freeze(generateGeometry(value, Math.min(limits.maxVertices, 1_000_000)))]));
+ const localBounds = new Map([...geometries.values()].map(geometry => [geometry, boundsFor(geometry, mat4.create())]));
+ let graph = compile(recipe, geometries, localBounds, limits);
+ const geometryBytes = [...geometries.values()].reduce((total, geometry) => total + Object.values(geometry).reduce((sum, array) => sum + array.byteLength, 0), 0);
+ const vertices = [...geometries.values()].reduce((total, geometry) => total + geometry.positions.length / 3, 0);
+ if (vertices > limits.maxVertices || geometryBytes > limits.maxGeometryBytes) {
+ throw new RangeError('Generated geometry exceeds its budget.');
+ }
+ let revision = 0;
+ const checkpoints = new Map();
+ let currentMaterials = new Map();
+ function snapshotsFor(materials) {
+ return new Map(materials.map(material => {
+ for (const field of ['color', 'emissiveColor']) {
+ if (material[field]) {
+ Object.freeze(material[field]);
+ }
+ }
+ return [material.id, material];
+ }));
+ }
+ currentMaterials = snapshotsFor(recipe.materials);
+ const materialOutputs = new Map(recipe.materials.map(material => {
+ const output = {};
+ for (const field of ['tag', ...MATERIAL_FIELDS]) {
+ Object.defineProperty(output, field, { enumerable: true, get() {
+ return currentMaterials.get(material.id)[field];
+ } });
+ }
+ return [material.id, Object.freeze(output)];
+ }));
+ const parts = Object.freeze(recipe.nodes.filter(node => node.geometry !== undefined).map(node => Object.freeze({
+ name: node.id, geometry: geometries.get(node.geometry), material: materialOutputs.get(node.material),
+ matrix: new Float32Array(graph.getNode(node.id).worldMatrix),
+ })));
+
+ function expected(options) {
+ knownKeys(options, ['expectedRevision'], 'transaction options');
+ if (!Number.isSafeInteger(options.expectedRevision) || options.expectedRevision !== revision) {
+ throw new RangeError('expectedRevision must match the current revision.');
+ }
+ }
+ function publish(candidate) {
+ candidate = copiedJson(candidate, limits.maxRecipeBytes);
+ candidate.nodes = candidate.nodes.map(nodeFrom);
+ candidate.materials = candidate.materials.map(materialFrom);
+ candidate.camera = cameraFrom(candidate.camera);
+ candidate = copiedJson(candidate, limits.maxRecipeBytes);
+ const staged = compile(candidate, geometries, localBounds, limits);
+ const stagedMaterials = snapshotsFor(candidate.materials);
+ for (const part of parts) {
+ if (part.matrix.length !== 16 || part.matrix.byteLength !== 64) {
+ throw new RangeError('Retained render matrices must not be detached.');
+ }
+ }
+ recipe = candidate;
+ currentMaterials = stagedMaterials;
+ graph = staged;
+ for (const part of parts) {
+ part.matrix.set(graph.getNode(part.name).worldMatrix);
+ }
+ revision++;
+ return revision;
+ }
+ return Object.freeze({
+ parts, capabilities: AGENT_SCENE_CAPABILITIES, limits,
+ get revision() {
+ return revision;
+ },
+ get camera() {
+ return structuredClone(recipe.camera);
+ },
+ exportRecipe() {
+ return structuredClone(recipe);
+ },
+ apply(inputOperations, options = {}) {
+ expected(options);
+ if (!Array.isArray(inputOperations) || inputOperations.length === 0 || inputOperations.length > limits.maxOperations) {
+ throw new RangeError('operations must contain 1 to maxOperations commands.');
+ }
+ const operations = copiedJson(inputOperations, limits.maxRecipeBytes);
+ const candidate = structuredClone(recipe);
+ for (const operation of operations) {
+ let target;
+ let fields;
+ if (operation.type === 'set-node') {
+ fields = NODE_FIELDS;
+ target = candidate.nodes.find(node => node.id === operation.id);
+ } else if (operation.type === 'set-material') {
+ fields = MATERIAL_FIELDS;
+ target = candidate.materials.find(material => material.id === operation.id);
+ } else if (operation.type === 'set-camera') {
+ fields = CAMERA_FIELDS;
+ target = candidate.camera;
+ } else {
+ throw new TypeError('Unsupported operation type.');
+ }
+ knownKeys(operation, ['type', ...(operation.type === 'set-camera' ? [] : ['id']), ...fields], 'operation');
+ if (!target) {
+ throw new RangeError(`Operation ID was not found: ${operation.id}.`);
+ }
+ for (const field of fields) {
+ if (Object.hasOwn(operation, field)) {
+ target[field] = operation[field];
+ }
+ }
+ }
+ return publish(candidate);
+ },
+ inspect(options = {}) {
+ knownKeys(options, ['ids', 'limit', 'includeBounds'], 'inspection');
+ const maximum = integer(options.limit ?? Math.min(64, limits.maxNodes), 1, limits.maxNodes, 'inspection limit');
+ if (options.includeBounds !== undefined && typeof options.includeBounds !== 'boolean') {
+ throw new TypeError('includeBounds must be boolean.');
+ }
+ if (options.ids !== undefined && (!Array.isArray(options.ids) || options.ids.length > limits.maxNodes)) {
+ throw new RangeError('Inspection IDs exceed maxNodes.');
+ }
+ const selected = options.ids === undefined ? recipe.nodes : options.ids.map(id => {
+ identifier(id);
+ const node = recipe.nodes.find(value => value.id === id);
+ if (!node) {
+ throw new RangeError(`Inspection ID was not found: ${id}.`);
+ }
+ return node;
+ });
+ const nodes = selected.slice(0, maximum).map(node => {
+ const geometry = geometries.get(node.geometry);
+ const result = { id: node.id, label: node.label ?? node.id, parent: node.parent,
+ geometry: node.geometry ?? null, material: node.material ?? null,
+ vertices: geometry ? geometry.positions.length / 3 : 0, triangles: geometry ? geometry.indices.length / 3 : 0 };
+ if (options.includeBounds) result.bounds = geometry ? boundsFor(geometry, graph.getNode(node.id).worldMatrix) : null;
+ return result;
+ });
+ return { revision, counts: { nodes: recipe.nodes.length, parts: parts.length, geometries: geometries.size, materials: recipe.materials.length, vertices },
+ geometryBytes, estimatedGeometryBytes, nodes, truncated: selected.length > nodes.length };
+ },
+ checkpoint() {
+ if (checkpoints.size >= limits.maxCheckpoints) {
+ throw new RangeError('Checkpoint budget exhausted. Release a checkpoint.');
+ }
+ const handle = Object.freeze({});
+ checkpoints.set(handle, structuredClone(recipe));
+ return handle;
+ },
+ restore(handle, options = {}) {
+ expected(options);
+ if (!checkpoints.has(handle)) {
+ throw new RangeError('Unknown or released checkpoint.');
+ }
+ return publish(checkpoints.get(handle));
+ },
+ releaseCheckpoint(handle) {
+ if (!checkpoints.delete(handle)) {
+ throw new RangeError('Unknown or released checkpoint.');
+ }
+ },
+ });
+}
diff --git a/tests/agent-scene.test.js b/tests/agent-scene.test.js
new file mode 100644
index 00000000..fd650347
--- /dev/null
+++ b/tests/agent-scene.test.js
@@ -0,0 +1,270 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { Matrix4, Quaternion, Vector3 } from 'three';
+import { createAgentScene, AGENT_SCENE_CAPABILITIES } from '../src/agent-scene.js';
+
+function recipe() {
+ return { format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'box', type: 'box', bevel: 0 }],
+ materials: [{ id: 'finish', color: [0.2, 0.4, 0.6] }],
+ nodes: [{ id: 'child', parent: 'root', geometry: 'box', material: 'finish', translation: [1, 2, 0] },
+ { id: 'root', label: 'Same label', translation: [3, 0, 0] },
+ { id: 'other', label: 'Same label', geometry: 'box', material: 'finish' }] };
+}
+
+test('shader arithmetic rejects cancelling product overflow and nonfinite emission atomically', () => {
+ const input = recipe();
+ const coordinate = Math.fround(1e20);
+ const nextCoordinate = Math.fround(coordinate + 1e14);
+ input.geometries = [{ id: 'box', type: 'extrude', depth: 1,
+ contour: [[coordinate, coordinate], [nextCoordinate, coordinate], [nextCoordinate, nextCoordinate], [coordinate, nextCoordinate]] }];
+ input.nodes = [
+ { id: 'root' },
+ { id: 'child', parent: 'root', geometry: 'box', material: 'finish', rotation: [0, 0, Math.sin(Math.PI / 8), Math.cos(Math.PI / 8)] },
+ ];
+ const session = createAgentScene(input);
+ const before = session.exportRecipe();
+ const matrix = Array.from(session.parts[0].matrix);
+ assert.throws(() => session.apply([{ type: 'set-node', id: 'root', scale: [1e20, 1e-20, 1] }], { expectedRevision: 0 }), /world geometry bounds/);
+ assert.throws(() => session.apply([{ type: 'set-material', id: 'finish', emission: 1e30, emissiveColor: [1e30, 0, 0] }], { expectedRevision: 0 }), /Emissive radiance/);
+ assert.deepEqual(session.exportRecipe(), before);
+ assert.deepEqual(Array.from(session.parts[0].matrix), matrix);
+ assert.equal(session.revision, 0);
+ input.materials[0].tag = 'unlit';
+ input.materials[0].emission = 70000;
+ input.materials[0].emissiveColor = [1, 0, 0];
+ assert.throws(() => createAgentScene(input), /half-float HDR/);
+});
+
+test('trailing sparse array holes reject recipes and command batches without commit', () => {
+ const input = recipe();
+ input.nodes.length++;
+ assert.throws(() => createAgentScene(input), /trailing holes/);
+ const session = createAgentScene(recipe());
+ const before = session.exportRecipe();
+ const operations = [{ type: 'set-node', id: 'root', translation: [2, 0, 0] }];
+ operations.length++;
+ assert.throws(() => session.apply(operations, { expectedRevision: 0 }), /trailing holes/);
+ assert.deepEqual(session.exportRecipe(), before);
+ assert.equal(session.revision, 0);
+});
+
+test('shared resources and retained renderer identities survive apply and restore', () => {
+ const input = recipe();
+ const session = createAgentScene(input);
+ input.nodes[1].translation[0] = 100;
+ const parts = session.parts;
+ const identities = parts.map(part => [part, part.matrix, part.geometry, part.material]);
+ assert.equal(parts[0].geometry, parts[1].geometry);
+ assert.equal(parts[0].material, parts[1].material);
+ assert.equal(parts[0].matrix[12], 4);
+ assert.equal(session.capabilities, AGENT_SCENE_CAPABILITIES);
+ const checkpoint = session.checkpoint();
+ assert.equal(session.apply([{ type: 'set-node', id: 'root', translation: [7, 0, 0] },
+ { type: 'set-material', id: 'finish', color: [1, 0, 0], emission: 2 }], { expectedRevision: 0 }), 1);
+ assert.equal(parts[0].matrix[12], 8);
+ assert.deepEqual(parts[1].material.color, [1, 0, 0]);
+ session.restore(checkpoint, { expectedRevision: 1 });
+ assert.equal(session.revision, 2);
+ assert.equal(parts[0].matrix[12], 4);
+ assert.deepEqual(parts[0].material.color, [0.2, 0.4, 0.6]);
+ parts.forEach((part, index) => {
+ [part, part.matrix, part.geometry, part.material].forEach((value, component) => assert.equal(value, identities[index][component]));
+ });
+ assert.equal(parts[0].material.color, parts[0].material.color);
+ assert.equal(session.parts, parts);
+ const inspection = session.inspect();
+ assert.equal(inspection.counts.vertices, 24);
+ assert.equal(inspection.geometryBytes, 720);
+});
+
+test('transactions reject conflicts and invalid late commands without publishing any changes', () => {
+ const session = createAgentScene(recipe());
+ const before = session.exportRecipe();
+ const matrix = Array.from(session.parts[0].matrix);
+ const invalidCommands = [
+ { type: 'set-node', id: 'root', parent: 'child' },
+ { type: 'set-node', id: 'child', parent: 'missing' },
+ { type: 'set-node', id: 'child', scale: [0, 1, 1] },
+ { type: 'set-node', id: 'child', rotation: [0, 0, 0, 0] },
+ { type: 'set-material', id: 'finish', roughness: 2 },
+ { type: 'set-camera', eye: [0, 0, 0], target: [0, 0, 0] },
+ { type: 'set-camera', near: 10, far: 1 },
+ { type: 'set-node', id: 'child', surprise: true },
+ { type: 'set-node', id: 'child', translation: null },
+ ];
+ for (const command of invalidCommands) {
+ assert.throws(() => session.apply([{ type: 'set-node', id: 'root', translation: [9, 0, 0] }, command], { expectedRevision: 0 }));
+ assert.deepEqual(session.exportRecipe(), before);
+ assert.deepEqual(Array.from(session.parts[0].matrix), matrix);
+ assert.equal(session.revision, 0);
+ }
+ assert.throws(() => session.apply([{ type: 'set-camera', fov: 60 }]));
+ assert.throws(() => session.apply([{ type: 'set-camera', fov: 60 }], { expectedRevision: 1 }));
+ session.apply([{ type: 'set-camera', fov: 60 }], { expectedRevision: 0 });
+ assert.equal(session.camera.fov, 60);
+});
+
+test('hierarchy and actual vertex bounds agree with an independent double precision transform', () => {
+ const input = recipe();
+ const rotation = [0, 0, Math.sin(Math.PI / 8) * 2, Math.cos(Math.PI / 8) * 2];
+ input.nodes[1].rotation = rotation;
+ input.nodes[1].scale = [2, 3, 4];
+ input.nodes[0].scale = [0.5, 1.5, 0.75];
+ const session = createAgentScene(input);
+ const root = new Matrix4().compose(new Vector3(3, 0, 0), new Quaternion(...rotation).normalize(), new Vector3(2, 3, 4));
+ const child = new Matrix4().compose(new Vector3(1, 2, 0), new Quaternion(), new Vector3(0.5, 1.5, 0.75));
+ const world = root.multiply(child);
+ const minimum = [Infinity, Infinity, Infinity];
+ const maximum = [-Infinity, -Infinity, -Infinity];
+ for (const x of [-0.5, 0.5]) for (const y of [-0.5, 0.5]) for (const z of [-0.5, 0.5]) {
+ const point = new Vector3(x, y, z).applyMatrix4(world).toArray();
+ for (let axis = 0; axis < 3; axis++) {
+ minimum[axis] = Math.min(minimum[axis], point[axis]);
+ maximum[axis] = Math.max(maximum[axis], point[axis]);
+ }
+ }
+ const actual = session.inspect({ ids: ['child'], includeBounds: true }).nodes[0].bounds;
+ for (let axis = 0; axis < 3; axis++) {
+ assert.ok(Math.abs(actual.min[axis] - minimum[axis]) < 1e-5);
+ assert.ok(Math.abs(actual.max[axis] - maximum[axis]) < 1e-5);
+ }
+ session.parts[0].matrix.fill(NaN);
+ assert.deepEqual(session.inspect({ ids: ['child'], includeBounds: true }).nodes[0].bounds, actual);
+ const exported = session.exportRecipe();
+ exported.nodes[0].translation[0] = 999;
+ const camera = session.camera;
+ camera.eye[0] = 999;
+ session.apply([{ type: 'set-node', id: 'child', label: 'Renamed' }], { expectedRevision: 0 });
+ assert.ok(session.parts[0].matrix.every(Number.isFinite));
+ assert.equal(session.inspect({ ids: ['child'] }).nodes[0].label, 'Renamed');
+ assert.equal(session.parts[0].name, 'child');
+});
+
+test('depth and world overflow checks reject an entire candidate and allow recovery', () => {
+ const session = createAgentScene(recipe(), { maxDepth: 2 });
+ assert.throws(() => session.apply([{ type: 'set-node', id: 'other', parent: 'child' }], { expectedRevision: 0 }), /maxDepth/);
+ assert.throws(() => session.apply([{ type: 'set-node', id: 'root', scale: [1e30, 1e30, 1e30] },
+ { type: 'set-node', id: 'child', scale: [1e30, 1e30, 1e30] }], { expectedRevision: 0 }), /finite Float32/);
+ assert.equal(session.revision, 0);
+ session.apply([{ type: 'set-node', id: 'other', parent: 'root' }], { expectedRevision: 0 });
+ assert.equal(session.inspect({ ids: ['other'] }).nodes[0].parent, 'root');
+});
+
+test('checkpoints are private, bounded, session-specific and releaseable', () => {
+ const session = createAgentScene(recipe(), { maxCheckpoints: 1 });
+ const checkpoint = session.checkpoint();
+ assert.ok(Object.isFrozen(checkpoint));
+ assert.throws(() => session.checkpoint(), /budget/);
+ const foreign = createAgentScene(recipe()).checkpoint();
+ assert.throws(() => session.restore(foreign, { expectedRevision: 0 }), /Unknown/);
+ assert.throws(() => session.releaseCheckpoint(foreign), /Unknown/);
+ session.apply([{ type: 'set-node', id: 'root', translation: [8, 0, 0] }], { expectedRevision: 0 });
+ assert.throws(() => session.restore(checkpoint, { expectedRevision: 0 }), /expectedRevision/);
+ session.restore(checkpoint, { expectedRevision: 1 });
+ session.releaseCheckpoint(checkpoint);
+ assert.throws(() => session.restore(checkpoint, { expectedRevision: 2 }), /released/);
+ assert.throws(() => session.releaseCheckpoint(checkpoint), /released/);
+ assert.ok(session.checkpoint());
+});
+
+test('camera supports explicit top views and rejects degenerate or collapsed projection ranges', () => {
+ const session = createAgentScene(recipe());
+ for (const camera of [{ eye: [0, 3, 0], target: [0, 0, 0] }, { up: [0, 0, 0] },
+ { near: 1e-100 }, { near: 1, far: 1 + 1e-10 }, { fov: 1e-40 }]) {
+ assert.throws(() => session.apply([{ type: 'set-camera', ...camera }], { expectedRevision: 0 }));
+ assert.equal(session.revision, 0);
+ }
+ session.apply([{ type: 'set-camera', eye: [0, 3, 0], target: [0, 0, 0], up: [0, 0, -2] }], { expectedRevision: 0 });
+ assert.deepEqual(session.camera.up, [0, 0, -1]);
+});
+
+test('finite matrices still reject world geometry overflow using cached local bounds', () => {
+ const input = recipe();
+ input.geometries = [{ id: 'box', type: 'lathe', profile: [[1e30, -1], [1e30, 1]], segments: 8 }];
+ const session = createAgentScene(input);
+ const before = session.exportRecipe();
+ assert.throws(() => session.apply([{ type: 'set-node', id: 'child', scale: [1e30, 1, 1] }], { expectedRevision: 0 }), /world geometry/);
+ assert.deepEqual(session.exportRecipe(), before);
+ assert.equal(session.revision, 0);
+});
+
+test('recipe boundary rejects malformed JSON, unknown keys and oversized geometry before generation', () => {
+ assert.throws(() => createAgentScene({ ...recipe(), eval: 'code' }), /Unknown/);
+ assert.throws(() => createAgentScene(recipe(), { maxNodes: 4097 }), /4096/);
+ assert.throws(() => createAgentScene(recipe(), { maxRecipeBytes: 100 }), /maxRecipeBytes/);
+ assert.throws(() => createAgentScene(recipe(), { maxGeometryBytes: 100 }), /preflight/);
+ const huge = recipe();
+ huge.geometries = [{ id: 'box', type: 'sphere', segments: 2048, rings: 2048 }];
+ assert.throws(() => createAgentScene(huge), /preflight/);
+ const cyclic = recipe();
+ cyclic.camera = cyclic;
+ assert.throws(() => createAgentScene(cyclic), /acyclic/);
+ const accessor = recipe();
+ Object.defineProperty(accessor, 'camera', {
+ enumerable: true,
+ get() {
+ throw new Error('must not execute');
+ },
+ });
+ assert.throws(() => createAgentScene(accessor), /accessors/);
+ const bad = recipe();
+ bad.nodes[0].rotation = [0, 0, NaN, 1];
+ assert.throws(() => createAgentScene(bad), /JSON/);
+});
+
+test('command and resource budgets, bounded inspection and missing IDs report failures', () => {
+ assert.throws(() => createAgentScene(recipe(), { maxNodes: 2 }), /resource limit/);
+ const extra = recipe();
+ extra.geometries.push({ id: 'sphere', type: 'sphere', segments: 8, rings: 4 });
+ assert.throws(() => createAgentScene(extra, { maxGeometries: 1 }), /resource limit/);
+ const duplicate = recipe();
+ duplicate.nodes[2].id = 'root';
+ assert.throws(() => createAgentScene(duplicate), /Duplicate/);
+ const session = createAgentScene(recipe(), { maxOperations: 1 });
+ assert.throws(() => session.apply([{ type: 'set-camera', fov: 60 }, { type: 'set-camera', fov: 70 }], { expectedRevision: 0 }), /maxOperations/);
+ assert.throws(() => session.apply([], { expectedRevision: 0 }), /commands/);
+ const inspection = session.inspect({ limit: 1 });
+ assert.equal(inspection.nodes.length, 1);
+ assert.equal(inspection.truncated, true);
+ assert.equal(inspection.counts.nodes, 3);
+ assert.throws(() => session.inspect({ ids: ['missing'] }), /not found/);
+ assert.throws(() => session.inspect({ includeBounds: 'yes' }), /boolean/);
+ assert.equal(session.revision, 0);
+});
+
+test('detached privileged adapter matrices cannot partially publish a transaction', () => {
+ const session = createAgentScene(recipe());
+ const before = session.exportRecipe();
+ const checkpoint = session.checkpoint();
+ structuredClone(session.parts[1].matrix.buffer, { transfer: [session.parts[1].matrix.buffer] });
+ assert.throws(() => session.apply([{ type: 'set-node', id: 'root', translation: [10, 0, 0] },
+ { type: 'set-material', id: 'finish', color: [1, 0, 0] }], { expectedRevision: 0 }), /detached/);
+ assert.equal(session.revision, 0);
+ assert.deepEqual(session.exportRecipe(), before);
+ assert.deepEqual(session.parts[0].material.color, [0.2, 0.4, 0.6]);
+ assert.equal(session.parts[0].matrix[12], 4);
+ assert.throws(() => session.restore(checkpoint, { expectedRevision: 0 }), /detached/);
+ assert.equal(session.revision, 0);
+});
+
+test('all seven generators remain within conservative aggregate vertex and byte estimates', () => {
+ const input = { format: '67js.scene', schemaVersion: 1, materials: [{ id: 'material' }], nodes: [], geometries: [
+ { id: 'box', type: 'box', subdivisions: 2 },
+ { id: 'cylinder', type: 'cylinder', segments: 8, bevelSegments: 2 },
+ { id: 'sphere', type: 'sphere', segments: 8, rings: 4 },
+ { id: 'torus', type: 'torus', segments: 8, sides: 4, arc: Math.PI },
+ { id: 'lathe', type: 'lathe', profile: [[0.5, -1], [1, 0], [0.5, 1]], segments: 8 },
+ { id: 'extrude', type: 'extrude', contour: [[0, 0], [1, 0], [1, 1], [0, 1]], depth: 0.5 },
+ { id: 'tube', type: 'tube', path: [[0, 0, 0], [0, 1, 0], [1, 2, 0]], segments: 8, radialSegments: 4 },
+ ] };
+ input.nodes = input.geometries.map(geometry => ({ id: geometry.id, geometry: geometry.id, material: 'material' }));
+ const session = createAgentScene(input);
+ const inspection = session.inspect({ includeBounds: true });
+ assert.equal(inspection.counts.geometries, 7);
+ assert.ok(inspection.geometryBytes <= inspection.estimatedGeometryBytes);
+ assert.ok(inspection.nodes.every(node => node.bounds.min.every(Number.isFinite)));
+ assert.deepEqual(createAgentScene(session.exportRecipe()).inspect(), session.inspect());
+ assert.throws(() => session.apply([{ type: 'set-node', id: 'box', geometry: 'sphere' }], { expectedRevision: 0 }), /Unknown/);
+ assert.throws(() => session.apply([{ type: 'set-material', id: 'material', tag: 'unlit' }], { expectedRevision: 0 }), /Unknown/);
+});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index d16d8a13..26078c01 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -25,6 +25,7 @@ export default defineConfig({
shrinkwrap: 'src/shrinkwrap.js',
'surface-attachment': 'src/surface-attachment.js',
physics: 'src/physics.js',
+ 'agent-scene': 'src/agent-scene.js',
},
formats: ['es'],
fileName: (_, entry) => entry === 'core' ? '67.module.js' : `${entry}.js`,