Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Measure tool cost and return diagnostics that name the next action (#65, #66)

Nguyen Xuan Ana4f116b6e5cc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fbfdc253..68e55a23 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,9 @@
## Unreleased
+- Measure and cut the cost of the MCP tools (issue #65). `node scripts/measure-tool-cost.mjs` reports each tool schema and each typical result in bytes and estimated tokens (3.5 characters a token). The 22 schemas came to 373,388 bytes (about 107,000 tokens) and are now 173,216 (about 49,500): recipe geometries and asset recipes point to `mesh_edit`, `mesh_stack` and `scene_create` for the mesh edit, stack and motion detail instead of repeating about 45 KB and 35 KB in each tool, and vectors, colours, quaternions and IDs are shared `$ref` definitions. The backend still validates every field. `tests/tool-cost.test.js` fails when the schema total, one tool's schema or a typical result passes `bench/tool-cost-budgets.json`. A small mesh change is 187 bytes as `mesh_edit` against 1,254 as dispose plus a whole-recipe `scene_create` on a 7-node recipe.
+- Return diagnostics that name the next action (issue #66). `mesh_inspect` lint adds `intersecting-parts`, `self-intersection`, `thin-wall`, `floating-part` and `asymmetric` warnings from the BVH, with face budgets and a `skippedChecks` list; they never turn `ok` off and the agent modeling suite does not grade them. `scene_inspect` adds `diagnostics` for material fields the renderer ignores, blended transmission and unused materials or geometries, and asset inspection adds decoder warnings (accepted but not drawn features), skinned meshes with no joints, joints with no skin and assets with no clips. Error messages now list allowed fields, known IDs and the next call: a missing session (the largest group, 21 of 68 recorded errors) names the active session or says to call `scene_create`, and page errors no longer carry the bundle stack. `tests/tool-errors.test.js` walks 27 error paths and rejects a message with no next action.
+
- Add joint limits, node constraints and drivers to motion (issue #58). Two-bone IK takes `limits` per joint and axis in degrees and `bendToward`; `scene_inspect` `motionIk` now carries `limited` (each pose a limit changed) and `warnings` (`hyperextended`, and `wrong-bend` for a knee or elbow bent the unnatural way, which a wrong pole used to hide behind `reached`). `motion.constraints` adds `copy_location`, `copy_rotation`, `copy_scale`, `limit_location`, `limit_rotation`, `track_to`, `child_of` (with an inverse and an influence blend) and `floor`, and `motion.drivers` sets a node component or material property from a bounded JSON expression over time and other nodes (never run as code). The order is tracks, IK, drivers, constraints, with no state between samples, so a seek equals playing. `copy_rotation`, `limit_rotation`, `track_to`, `child_of` and `floor` match Blender 5.2 world matrices in 8 recorded cases (`tests/fixtures/blender/constraints.json`). Joint limits are also in `67js/addons/skeleton-pose`. The `leg-plant` task joins the agent modeling suite. The expression language is a new small one in `src/motion-expression.js`: the field expressions of the mesh addon were not on `main` yet
- Reach Rapier from recipes: a `physics` section (and a `set-physics` operation) puts rigid bodies on node IDs with box, ball, capsule, convex or trimesh colliders fitted to their geometry, joints, gravity and a duration of up to 10 seconds. It is recorded once at 60 steps a second and seeks like `motion`, so a seek back repeats the same frame (checked as identical PNG bytes on SwiftShader through MCP). `scene_inspect` reports per-body final positions and resting times, contacts and sensor enter and leave events. Rapier stays an optional peer, served to the preview from `node_modules` like Manifold, so the MCP server bundle does not grow.
diff --git a/bench/agent-modeling/measure.mjs b/bench/agent-modeling/measure.mjs
index 47e6cecc..fc7166ca 100644
--- a/bench/agent-modeling/measure.mjs
+++ b/bench/agent-modeling/measure.mjs
@@ -6,6 +6,7 @@ import { readFile } from 'node:fs/promises';
import { createAgentAssetScene } from '../../src/agent-asset.js';
import { createAgentScene, loadMeshBooleans, needsMeshBooleans, loadPhysicsEngine, needsPhysics } from '../../src/agent-scene.js';
import { parseGltf } from '../../src/gltf.js';
+import { GEOMETRY_PROBLEMS } from '../../src/mesh-lint.js';
const WELD_DISTANCE = 1e-5;
@@ -269,8 +270,10 @@ export async function measureRecipe(recipe) {
parts += report.parts.count;
closedParts += report.parts.closed;
eulerCharacteristic += report.counts.vertices - report.counts.edges + report.counts.faces;
- for (const problem of report.problems) problemKinds.add(problem.kind);
- lintProblems += report.problems.length;
+ // Spatial warnings are advice, not pass or fail: a mug handle is meant to break symmetry.
+ const gradedProblems = report.problems.filter(problem => !(problem.kind in GEOMETRY_PROBLEMS));
+ for (const problem of gradedProblems) problemKinds.add(problem.kind);
+ lintProblems += gradedProblems.length;
}
const allClosed = closedParts === parts;
return {
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index 94138060..2536336a 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -15,7 +15,7 @@
"entry:sculpt": 2500,
"entry:surface": 10100,
"entry:mesh-query": 15900,
- "entry:mesh": 49400,
+ "entry:mesh": 65700,
"entry:shrinkwrap": 18300,
"entry:surface-attachment": 11800,
"entry:physics": 18000,
@@ -28,11 +28,11 @@
"entry:grass": 4400,
"entry:clutter": 5300,
"entry:texture-set": 900,
- "entry:agent-scene": 135800,
- "entry:agent-asset": 143200,
+ "entry:agent-scene": 144500,
+ "entry:agent-asset": 152300,
"entry:hdri": 3300,
"scene:lit-box": 56000,
"scene:gltf-box": 75300,
- "scene:agent-scene": 162400
+ "scene:agent-scene": 170500
}
}
diff --git a/bench/tool-cost-budgets.json b/bench/tool-cost-budgets.json
new file mode 100644
index 00000000..1c861c9d
--- /dev/null
+++ b/bench/tool-cost-budgets.json
@@ -0,0 +1,21 @@
+{
+ "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; was 373388 schema bytes before shared IDs and recipe references",
+ "schemaTotalBytes": 176000,
+ "schemaToolBytes": {
+ "scene_create": 57000,
+ "scene_apply": 43000,
+ "mesh_edit": 34000,
+ "scene_create_asset": 18000,
+ "mesh_stack": 11500
+ },
+ "schemaOtherToolBytes": 4000,
+ "resultBytes": {
+ "scene_capabilities": 3000,
+ "scene_create": 1400,
+ "scene_inspect": 1400,
+ "mesh_inspect": 1200,
+ "mesh_edit": 2400,
+ "scene_apply": 200,
+ "scene_export_recipe": 2800
+ }
+}
diff --git a/docs/mcp.md b/docs/mcp.md
index 259dd051..d26b2441 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -119,6 +119,12 @@ Inspect or export the recipe before retrying. Context loss still permits recipe
| `scene_render_result` | `jobId` | Completed output paths, hashes and metrics |
| `scene_render_release` | `jobId` | Confirmation that owned job files were removed |
+### Tool cost and diagnostics
+
+Every tool schema is read on every turn, so `node scripts/measure-tool-cost.mjs` reports the bytes and estimated tokens of each schema and of each typical result, and `tests/tool-cost.test.js` fails when one passes `bench/tool-cost-budgets.json`. The schemas total 173,216 bytes (about 49,500 tokens). To save space, a mesh geometry's `edits` and `stack` in a recipe, and `motion` in `scene_apply` and asset recipes, are advertised as plain objects: the full field list is in `mesh_edit`, `mesh_stack` and `scene_create`, and the backend still validates every field and names the valid choices when one is wrong. A small mesh change is far cheaper as `mesh_edit` (187 bytes in the measured case) than as a whole recipe rewrite (1,254 bytes with the dispose).
+
+`mesh_inspect` lint adds warnings for `intersecting-parts`, `self-intersection`, `thin-wall`, `floating-part` and `asymmetric`. They never set `ok` to false, run within face budgets, and list any check they skipped in `skippedChecks`. `scene_inspect` returns a `diagnostics` list only when there is something to say: ignored material fields, blended transmission, unused materials or geometries, and for imported assets the decoder's not-drawn features, rigs with no joints or no skin, and assets with no clips. Each item has `kind`, `severity`, `target`, `message` and `fix`.
+
The recipe uses `format: '67js.scene'` and `schemaVersion: 1`.
Supported geometry types are `box`, `cylinder`, `sphere`, `torus`, `lathe`, `extrude`, `tube`, and `mesh`.
A `mesh` geometry starts from one of the others as `base` and replays an edit log; see [mesh.md](mesh.md).
diff --git a/docs/parity.md b/docs/parity.md
index 2f59451f..9c96dd05 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -47,7 +47,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Modeling > Meshes > Editing | partial | 26 edits, including extrude, inset, bevel, loop cut, boolean, merge, bisect, bridge, fill, grid fill, dissolve, edge subdivision and a knife by projected polyline. All but the knife match Blender on fixtures; the knife is compared only with a straight plane cut. | [Blender results](../tests/fixtures/blender/golden.json) | #41 |
| Modeling > Meshes > Properties | partial | `smoothAngle` and face tags. There is no sharp edge attribute or crease. | | #39 |
| Modeling > Meshes > UVs | partial | `uv_unwrap` with LSCM, axis charts and shelf packing. Patterns can not use the result yet. | | #50 |
-| Modeling > Meshes > Mesh Analysis | partial | `lintMesh` reports topology problems. There is no check for thin walls or intersections. | | #66 |
+| Modeling > Meshes > Mesh Analysis | partial | `lintMesh` reports topology problems. With `{ geometry: true }` (always on in `mesh_inspect`) it also warns of crossing parts, a solid cutting itself, thin walls, floating parts and near-symmetry, using the BVH within face budgets. Checks are heuristics on parts, not Blender's exact Select Non-Manifold or Intersect checks. | [tests/mesh-lint-geometry.test.js](../tests/mesh-lint-geometry.test.js), [src/mesh-lint-geometry.js](../src/mesh-lint-geometry.js) | #66 |
| Modeling > Meshes > Remeshing | missing | No remesh. | | #40 |
| Modeling > Curves | partial | `tube` follows a curve and `extrude` follows a contour. There is no curve object. | | #45 |
| Modeling > Curves (New) | missing | No hair curves. | | #63 |
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index 98814e37..48010172 100644
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@ -8,13 +8,14 @@ import { parseGltf } from '../src/gltf.js';
import { exportGlb } from '../src/export.js';
import { weightTracksFromGltfAnimation } from '../src/export-skeleton.js';
import { clipFromGltfAnimation } from '../src/skeleton-pose.js';
+import { sessionProblem } from '../src/agent-errors.js';
let active = null;
let canvas = document.querySelector('canvas');
function requireSession(sessionId) {
if (!active || active.sessionId !== sessionId) {
- throw new Error('Unknown or disposed scene session.');
+ throw new Error(sessionProblem(sessionId, active?.sessionId));
}
return active;
}
diff --git a/scripts/agent-render-jobs.mjs b/scripts/agent-render-jobs.mjs
index dd57f7a0..0ea92826 100644
--- a/scripts/agent-render-jobs.mjs
+++ b/scripts/agent-render-jobs.mjs
@@ -16,7 +16,7 @@ const INTERNAL_FILES =new Set(['owner.json', 'snapshot.json', 'asset.glb', 'stat
function objectKeys(value, allowed, label) {
if (!value || Object.getPrototypeOf(value) !== Object.prototype) throw new TypeError(`${label} must be a plain object.`);
for (const key of Object.keys(value)) {
- if (!allowed.includes(key)) throw new TypeError(`Unknown ${label} field: ${key}.`);
+ if (!allowed.includes(key)) throw new TypeError(`Unknown ${label} field: ${key}. Allowed fields: ${allowed.join(", ")}.`);
}
}
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
index 5fde6e2b..9129ac93 100644
--- a/scripts/agent-runtime.mjs
+++ b/scripts/agent-runtime.mjs
@@ -11,6 +11,7 @@ import { createAgentRenderJobs, EXPORT_DIRECTORY_NAME } from './agent-render-job
import { createFrameEncoder } from './frame-encoder.mjs';
import { isPreviewHost } from './preview-host.mjs';
import { normalizeReview, REVIEW_LIMITS } from './agent-review.mjs';
+import { sessionProblem } from '../src/agent-errors.js';
const SCENE_LIMITS = AGENT_SCENE_DEFAULT_LIMITS;
const MAXIMUM_IMAGE_BYTES = 1024 * 1024;
@@ -212,7 +213,7 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo
function requireSession(sessionId) {
if (!activeSessionId || sessionId !== activeSessionId) {
- throw new Error('Unknown or disposed scene session.');
+ throw new Error(sessionProblem(sessionId, activeSessionId));
}
}
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 160af612..47437a21 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -12,10 +12,10 @@ const finite = z.number().min(-3.4028234663852886e38).max(3.4028234663852886e38)
const positive = finite.positive();
const nonnegative = finite.nonnegative();
const unit = z.number().min(0).max(1);
-const identifier = z.string().min(1).max(128).regex(/\S/).describe('Stable resource or node ID, with at least one non-space character.');
-const vector3 = z.tuple([finite, finite, finite]);
-const color = z.tuple([unit, unit, unit]);
-const quaternion = z.tuple([finite, finite, finite, finite]);
+const identifier = z.string().min(1).max(128).regex(/\S/).describe('Stable resource or node ID, with at least one non-space character.').meta({ id: 'Identifier' });
+const vector3 = z.tuple([finite, finite, finite]).meta({ id: 'Vector3' });
+const color = z.tuple([unit, unit, unit]).meta({ id: 'Color' });
+const quaternion = z.tuple([finite, finite, finite, finite]).meta({ id: 'Quaternion' });
const point2 = z.tuple([finite, finite]);
const detail = (minimum, maximum) => z.number().int().min(minimum).max(maximum).optional();
const segments = detail(3, 2048);
@@ -283,9 +283,13 @@ const stackNodes = [
];
const meshStack = z.array(z.discriminatedUnion('op', stackNodes)).max(16);
const meshEdits = z.array(z.discriminatedUnion('op', [...meshEdit.options, ...stackNodes])).max(64);
+// The full edit and stack schemas live in mesh_edit and mesh_stack. Repeating them in every recipe cost about 45 KB
+// per tool; the backend still validates each item and names the valid ops when one is wrong.
+const recipeMeshEdits = z.array(z.record(z.string(), z.unknown())).max(64);
+const recipeMeshStack = z.array(z.record(z.string(), z.unknown())).max(16);
const geometry = z.discriminatedUnion('type', [
...primitiveGeometries(true),
- z.strictObject({ id: identifier, type: z.literal('mesh'), base: z.discriminatedUnion('type', primitiveGeometries(false)).describe('Starting shape, converted to welded quads with axis face tags.'), edits: meshEdits.optional().describe('Replayable edit log, applied in order.'), stack: meshStack.optional().describe('Non-destructive modifier stack (mirror, array, solidify, bevel, uv_unwrap, subdivide) evaluated after the edits.'), smoothAngle: bounded(0, 180).optional().describe('Edges bending more than this many degrees render hard. Defaults to 30.') }),
+ z.strictObject({ id: identifier, type: z.literal('mesh'), base: z.discriminatedUnion('type', primitiveGeometries(false)).describe('Starting shape, converted to welded quads with axis face tags.'), edits: recipeMeshEdits.optional().describe('Replayable edit log, applied in order. Each item has the shape of one mesh_edit edit; read that tool for every op and field.'), stack: recipeMeshStack.optional().describe('Non-destructive modifier stack evaluated after the edits. Each item has the shape of one mesh_stack node; read that tool for the ops.'), smoothAngle: bounded(0, 180).optional().describe('Edges bending more than this many degrees render hard. Defaults to 30.') }),
]);
function motionTrack(kind, property, value, tangent) {
return z.strictObject({
@@ -413,6 +417,9 @@ const physics = z.strictObject({
bodies: z.array(physicsBody).min(1).max(64),
joints: z.array(physicsJoint).max(64).optional().describe('Joint bodies are the node IDs of physics bodies.'),
}).describe('Rigid-body physics recorded offline with Rapier at 60 steps a second, then played back by time like motion: scene_look and scene_review motionTime seek into the recording, so a seek back shows the identical frame. Bodies are recipe nodes; scene_inspect reports contacts, sensor events and resting state as numbers. Needs the optional peer dependency @dimforge/rapier3d-compat. A node cannot have a physics body and a motion translation or rotation track.');
+// The full motion schema (tracks, ik, constraints, drivers) is in scene_create's recipe. scene_apply and asset recipes
+// take the same object, validated by the backend, without repeating about 35 KB of schema in each tool.
+const recipeMotionReference = z.record(z.string(), z.unknown()).describe('The same object as recipe.motion in scene_create: duration, loop, tracks, ik, constraints, drivers. Read that tool for the fields.');
const recipe = z.strictObject({
format: z.literal('67js.scene'),
schemaVersion: z.literal(1),
@@ -441,13 +448,13 @@ const assetRecipe = z.strictObject({
animation: z.strictObject({ clip: z.number().int().min(0), time: nonnegative }).nullable().optional().describe('Absolute clip/time sample. null selects the original decoded pose.'),
materialOverrides: z.array(z.strictObject({ id: identifier, ...materialFields })).max(4096).optional(),
nodeOverrides: z.array(z.strictObject({ id: identifier, translation: vector3.optional(), rotation: quaternion.optional(), scale: z.tuple([positive, positive, positive]).optional() })).max(4096).optional(),
- motion: motion.nullable().optional(),
+ motion: recipeMotionReference.nullable().optional(),
});
const operation = z.discriminatedUnion('type', [
z.strictObject({ type: z.literal('set-node'), id: identifier, geometry: identifier.optional(), material: identifier.optional(), ...nodeFields }),
z.strictObject({ type: z.literal('set-material'), id: identifier, ...materialFields }),
z.strictObject({ type: z.literal('set-camera'), ...cameraFields }),
- z.strictObject({ type: z.literal('set-motion'), motion: motion.nullable() }),
+ z.strictObject({ type: z.literal('set-motion'), motion: recipeMotionReference.nullable() }),
z.strictObject({ type: z.literal('set-physics'), physics: physics.nullable() }),
z.strictObject({ type: z.literal('set-environment'), environment }),
z.strictObject({ type: z.literal('set-effects'), effects }),
@@ -479,6 +486,13 @@ const renderSettings = z.strictObject({
const readOnly = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
const edit = { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false };
+// Errors from the preview page arrive as "page.evaluate: RangeError: <message>\n at <bundle url>...": the stack
+// names bundle internals the agent cannot act on, so only the message is returned.
+export function readableErrorMessage(error) {
+ const message = error instanceof Error ? error.message : String(error);
+ return message.split(/\s+at (?:\S+ \()?https?:\/\//)[0].replace(/^page\.evaluate: (?:\w*Error: )?/, '').trim();
+}
+
function jsonResult(value) {
return { content: [{ type: 'text', text: JSON.stringify(value) }], structuredContent: value };
}
@@ -500,8 +514,7 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versio
try {
return await run(argumentsValue);
} catch (error) {
- const message = error instanceof Error ? error.message : String(error);
- return { isError: true, content: [{ type: 'text', text: `${name} failed: ${message}` }] };
+ return { isError: true, content: [{ type: 'text', text: `${name} failed: ${readableErrorMessage(error)}` }] };
}
});
}
diff --git a/scripts/measure-tool-cost.mjs b/scripts/measure-tool-cost.mjs
new file mode 100644
index 00000000..ce085239
--- /dev/null
+++ b/scripts/measure-tool-cost.mjs
@@ -0,0 +1,122 @@
+import { pathToFileURL } from 'node:url';
+import { resolve } from 'node:path';
+import { Client } from '@modelcontextprotocol/client';
+import { InMemoryTransport } from '@modelcontextprotocol/server';
+import { createAgentMcpServer } from './mcp-server.mjs';
+import { createAgentScene, AGENT_SCENE_CAPABILITIES } from '../src/agent-scene.js';
+
+// JSON is dense in tokens: about 3.5 characters each for schemas and recipes (an estimate, not a tokenizer count).
+const CHARACTERS_PER_TOKEN = 3.5;
+const SAMPLE_SESSION = '00000000-0000-4000-8000-000000000000';
+const SMALL_EDIT = { op: 'extrude_face_region', select: { tag: 'dish.cap' }, offset: -0.02, name: 'well' };
+
+export function estimateTokens(bytes) {
+ return Math.ceil(bytes / CHARACTERS_PER_TOKEN);
+}
+
+function sizeOf(value) {
+ const bytes = Buffer.byteLength(JSON.stringify(value));
+ return { bytes, tokens: estimateTokens(bytes) };
+}
+
+/** A small furniture recipe: one mesh geometry with an edit log and a few plain nodes. */
+export function sampleRecipe() {
+ const leg = index => ({
+ id: `leg-${index}`, geometry: 'leg', material: 'wood',
+ translation: [index % 2 ? 0.4 : -0.4, 0.25, index > 1 ? 0.4 : -0.4], scale: [0.08, 0.5, 0.08],
+ });
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [
+ {
+ id: 'seat', type: 'mesh', base: { type: 'box', bevel: 0 },
+ edits: [
+ { op: 'inset_region', select: { tag: 'top' }, thickness: 0.08, name: 'rim' },
+ { op: 'extrude_face_region', select: { tag: 'rim.cap' }, offset: -0.03, name: 'dish' },
+ ],
+ },
+ { id: 'leg', type: 'box', bevel: 0 },
+ { id: 'back', type: 'box', bevel: 0 },
+ ],
+ materials: [{ id: 'wood', color: [0.45, 0.28, 0.14], roughness: 0.7 }, { id: 'cushion', color: [0.7, 0.1, 0.1], roughness: 0.9 }],
+ nodes: [
+ { id: 'seat', geometry: 'seat', material: 'cushion', translation: [0, 0.55, 0], scale: [1, 0.1, 1] },
+ ...[0, 1, 2, 3].map(leg),
+ { id: 'back', geometry: 'back', material: 'wood', translation: [0, 0.95, -0.46], scale: [1, 0.7, 0.08] },
+ ],
+ };
+}
+
+export async function listTools() {
+ const server = createAgentMcpServer({ async close() {} });
+ const client = new Client({ name: 'tool-cost', version: '1' });
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ await server.connect(serverTransport);
+ await client.connect(clientTransport);
+ const { tools } = await client.listTools();
+ await client.close();
+ await server.close();
+ return tools;
+}
+
+function typicalResults(recipe) {
+ const scene = createAgentScene(recipe);
+ const status = { sessionId: SAMPLE_SESSION, revision: scene.revision, inspection: scene.inspect(), render: { backend: 'gpu' } };
+ scene.apply([{ type: 'edit-mesh', geometry: 'seat', edits: [SMALL_EDIT] }], { expectedRevision: scene.revision });
+ const meshReport = scene.inspectMeshes({ geometries: ['seat'] });
+ const { inspection, ...statusWithoutInspection } = status;
+ return {
+ scene_capabilities: AGENT_SCENE_CAPABILITIES,
+ scene_create: status,
+ scene_inspect: { sessionId: SAMPLE_SESSION, ...scene.inspect() },
+ mesh_inspect: { sessionId: SAMPLE_SESSION, ...meshReport },
+ mesh_edit: { ...status, mesh: meshReport.meshes[0] },
+ scene_apply: statusWithoutInspection,
+ scene_export_recipe: { sessionId: SAMPLE_SESSION, revision: scene.revision, recipe: scene.exportRecipe() },
+ };
+}
+
+/** One small mesh change sent as a mesh_edit call, against the same change sent as a whole new recipe. */
+function smallChangeComparison(recipe) {
+ const meshEditCall = { sessionId: SAMPLE_SESSION, expectedRevision: 1, geometry: 'seat', edits: [SMALL_EDIT] };
+ const changed = structuredClone(recipe);
+ changed.geometries[0].edits.push(SMALL_EDIT);
+ return {
+ meshEditCall: sizeOf(meshEditCall),
+ rewriteCall: sizeOf({ recipe: changed }),
+ rewriteNeedsDispose: sizeOf({ sessionId: SAMPLE_SESSION }),
+ };
+}
+
+export async function measureToolCost() {
+ const tools = await listTools();
+ const entries = tools.map(tool => ({ name: tool.name, description: tool.description, inputSchema: tool.inputSchema }));
+ const schemas = entries
+ .map(entry => ({ name: entry.name, descriptionBytes: Buffer.byteLength(entry.description), ...sizeOf(entry) }))
+ .sort((first, second) => second.bytes - first.bytes);
+ const recipe = sampleRecipe();
+ const results = Object.entries(typicalResults(recipe)).map(([name, value]) => ({ name, ...sizeOf(value) }));
+ return { schemas, schemaTotal: sizeOf(entries), results, comparison: smallChangeComparison(recipe) };
+}
+
+function printRow(name, row, note = '') {
+ console.log(` ${name.padEnd(26)} ${String(row.bytes).padStart(7)} B ~${String(row.tokens).padStart(6)} tokens${note}`);
+}
+
+function printReport(report) {
+ console.log('Tool schemas (description + input schema), largest first');
+ for (const row of report.schemas) printRow(row.name, row, ` (description ${row.descriptionBytes} B)`);
+ printRow('TOTAL', report.schemaTotal);
+ console.log('Typical results');
+ for (const row of report.results) printRow(row.name, row);
+ const { meshEditCall, rewriteCall, rewriteNeedsDispose } = report.comparison;
+ console.log('Small mesh change (one inset on the seat)');
+ printRow('mesh_edit call', meshEditCall);
+ printRow('scene_create rewrite', rewriteCall, ` (+ scene_dispose ${rewriteNeedsDispose.bytes} B)`);
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
+ const report = await measureToolCost();
+ if (process.argv.includes('--json')) console.log(JSON.stringify(report));
+ else printReport(report);
+}
diff --git a/src/agent-asset.js b/src/agent-asset.js
index 9bd53a18..99059fda 100644
--- a/src/agent-asset.js
+++ b/src/agent-asset.js
@@ -1,5 +1,6 @@
import { mat4, mat3 } from 'gl-matrix';
import { createAgentScene } from './agent-scene.js';
+import { assetDiagnostics } from './agent-diagnostics.js';
import { fitPerspectiveDistance } from './camera.js';
import { validateSkinGeometry, validateSkinPose } from './skinning.js';
import { validateMorphGeometry, validateMorphTransform } from './morph.js';
@@ -34,7 +35,7 @@ function knownKeys(value, fields, label) {
}
for (const key of Object.keys(value)) {
if (!fields.includes(key)) {
- throw new TypeError(`Unknown ${label} field: ${key}.`);
+ throw new TypeError(`Unknown ${label} field: ${key}. Allowed fields: ${fields.join(", ")}.`);
}
}
}
@@ -562,6 +563,17 @@ export function createAgentAssetScene(asset, inputRecipe) {
}
/** scene_inspect's motionIk: how each solver fares across the clip, from a sampler that leaves the published pose alone. */
+ function diagnosticsReport() {
+ const diagnostics = assetDiagnostics({
+ assetId: canonicalAssetId,
+ warnings: asset.warnings,
+ skinnedParts: records.filter(record => record.source.skin).length,
+ jointCount: [...sourceNodes.values()].filter(node => node.joint).length,
+ clipCount: asset.animations.length,
+ });
+ return diagnostics.length ? { diagnostics } : {};
+ }
+
function motionIkReport() {
if (!recipe.motion?.ik?.length) return {};
const sweeper = compileAgentMotion(recipe.motion, motionRecipe(recipe));
@@ -727,7 +739,7 @@ export function createAgentAssetScene(asset, inputRecipe) {
}
if (options.kind === 'hierarchy') {
if (options.includeBounds) {
- throw new TypeError('Hierarchy inspection has no deformed silhouette bounds.');
+ throw new TypeError('Hierarchy inspection has no deformed silhouette bounds. Drop includeBounds, or inspect without kind to get mesh bounds.');
}
if (options.ids !== undefined && (!Array.isArray(options.ids) || options.ids.length > sourceNodes.size)) {
throw new RangeError('Hierarchy IDs must fit the source-node count.');
@@ -739,7 +751,7 @@ export function createAgentAssetScene(asset, inputRecipe) {
return sourceNodes.get(id);
});
const nodes = structuredClone(selected.slice(offset, offset + limit));
- return { revision, topologyRevision: 0, assetId: canonicalAssetId, kind: 'hierarchy', ...motionIkReport(),
+ return { revision, topologyRevision: 0, assetId: canonicalAssetId, kind: 'hierarchy', ...motionIkReport(), ...diagnosticsReport(),
counts: { nodes: sourceNodes.size, joints: [...sourceNodes.values()].filter(node => node.joint).length },
nodes, offset, truncated: offset + nodes.length < selected.length,
motion: recipe.motion ? { duration: recipe.motion.duration, loop: recipe.motion.loop, tracks: recipe.motion.tracks.length, time: motionTime } : null };
@@ -750,7 +762,7 @@ export function createAgentAssetScene(asset, inputRecipe) {
const selected = options.ids === undefined ? records : options.ids.map(id => {
const record = records.find(value => value.id === id);
if (!record) {
- throw new RangeError(`Unknown mesh ID: ${id}.`);
+ throw new RangeError(`Unknown mesh ID: ${id}. Imported mesh IDs look like mesh-0, mesh-1; call scene_inspect without ids to list them, or with kind hierarchy for source nodes.`);
}
return record;
});
@@ -786,7 +798,7 @@ export function createAgentAssetScene(asset, inputRecipe) {
}
}
return {
- revision, topologyRevision: 0, assetId: canonicalAssetId,
+ revision, topologyRevision: 0, assetId: canonicalAssetId, ...diagnosticsReport(),
counts: { nodes: parts.length, parts: parts.length, geometries: geometries.size, materials: materials.size, vertices },
geometryBytes, animation: structuredClone(recipe.animation),
motion: recipe.motion ? { duration: recipe.motion.duration, loop: recipe.motion.loop, tracks: recipe.motion.tracks.length, time: motionTime } : null,
@@ -805,13 +817,13 @@ export function createAgentAssetScene(asset, inputRecipe) {
restore(handle, options = {}) {
expected(options);
if (!checkpoints.has(handle)) {
- throw new RangeError('Unknown or released asset checkpoint.');
+ throw new RangeError('Unknown or released asset checkpoint. Save one with scene_checkpoint, or use a checkpointId that scene_checkpoint returned and you have not released.');
}
return publish(checkpoints.get(handle));
},
releaseCheckpoint(handle) {
if (!checkpoints.delete(handle)) {
- throw new RangeError('Unknown or released asset checkpoint.');
+ throw new RangeError('Unknown or released asset checkpoint. Save one with scene_checkpoint, or use a checkpointId that scene_checkpoint returned and you have not released.');
}
},
});
diff --git a/src/agent-diagnostics.js b/src/agent-diagnostics.js
new file mode 100644
index 00000000..90664c15
--- /dev/null
+++ b/src/agent-diagnostics.js
@@ -0,0 +1,93 @@
+/**
+ * Diagnostics for things that load or validate without error but do not do what the agent probably meant: a material
+ * field the renderer ignores, an asset feature that is accepted but not drawn, a rig with nothing to move. Each has a
+ * kind, a severity, a target (the material, node or asset it concerns), a message and a fix that names the next action.
+ * Reads of an inspected scene include them only when there is something to say, to keep default results small.
+ */
+const PLAIN_SURFACE_TAGS = new Set(['surface', 'gltf']);
+const LAYER_FIELDS = ['clearcoat', 'sheenColor', 'specular', 'specularColor'];
+const TRANSMISSION_DETAIL_FIELDS = ['thickness', 'attenuationColor', 'attenuationDistance'];
+
+function diagnostic(kind, severity, target, message, fix) {
+ return { kind, severity, target, message, fix };
+}
+
+function hasValue(material, field) {
+ const value = material[field];
+ if (Array.isArray(value)) return value.some(component => component !== 0);
+ return typeof value === 'number' && value !== 0;
+}
+
+function materialProblems(material) {
+ const problems = [];
+ const tag = material.tag ?? 'surface';
+ const transmitting = hasValue(material, 'transmission');
+ if (tag !== 'surface' && tag !== 'liquid') {
+ for (const field of LAYER_FIELDS.filter(layer => hasValue(material, layer))) {
+ problems.push(diagnostic('ignored-material-field', 'warning', material.id,
+ `${field} is ignored on a material with tag ${tag}.`,
+ `Remove ${field}, or set the material tag to surface with scene_apply set-material.`));
+ }
+ }
+ if (!transmitting) {
+ for (const field of TRANSMISSION_DETAIL_FIELDS.filter(detail => hasValue(material, detail))) {
+ problems.push(diagnostic('ignored-material-field', 'warning', material.id,
+ `${field} only matters with transmission, and transmission is 0.`,
+ `Set transmission above 0 for glass or gems, or remove ${field}.`));
+ }
+ }
+ if (transmitting && (material.alphaMode === 'blend' || material.opacity < 1)) {
+ problems.push(diagnostic('transmission-blended', 'warning', material.id,
+ 'A transmitting material that is also blended does not refract what is behind it.',
+ 'Set opacity to 1 and alphaMode to opaque for refraction, or drop transmission and keep the blended look.'));
+ }
+ if (material.pattern && (tag === 'liquid' || tag === 'foam' || tag === 'unlit')) {
+ problems.push(diagnostic('ignored-material-field', 'warning', material.id,
+ `pattern is not applied to a material with tag ${tag}.`,
+ 'Move the pattern to a surface material, or remove it.'));
+ }
+ return problems;
+}
+
+/** Material and resource diagnostics for a normalized procedural recipe. */
+export function recipeDiagnostics(recipe) {
+ const problems = recipe.materials.flatMap(materialProblems);
+ const usedMaterials = new Set(recipe.nodes.map(node => node.material).filter(Boolean));
+ const usedGeometries = new Set(recipe.nodes.map(node => node.geometry).filter(Boolean));
+ for (const material of recipe.materials.filter(candidate => !usedMaterials.has(candidate.id))) {
+ problems.push(diagnostic('unused-material', 'info', material.id,
+ `Material ${material.id} is used by no node.`,
+ 'Assign it to a node with scene_apply set-node, or remove it with remove-material.'));
+ }
+ for (const geometry of recipe.geometries.filter(candidate => !usedGeometries.has(candidate.id))) {
+ problems.push(diagnostic('unused-geometry', 'info', geometry.id,
+ `Geometry ${geometry.id} is used by no node, so nothing draws it.`,
+ 'Add a node that uses it with scene_apply add-node, or remove it with remove-geometry.'));
+ }
+ return problems;
+}
+
+/**
+ * Rig and asset diagnostics. `warnings` are the decoder's notes about features it accepted but does not draw.
+ */
+export function assetDiagnostics({ assetId, warnings = [], skinnedParts, jointCount, clipCount }) {
+ const problems = warnings.map(warning => diagnostic('unsupported-asset-feature', 'warning', assetId,
+ String(warning),
+ 'The asset loads without it. Remove the feature from the GLB, or bake it into the base colour texture.'));
+ if (skinnedParts > 0 && jointCount === 0) {
+ problems.push(diagnostic('rig-without-joints', 'error', assetId,
+ `${skinnedParts} meshes are skinned but the asset has no joint nodes, so no pose or ik can move them.`,
+ 'Re-export the GLB with its armature, or use an asset that has joints.'));
+ }
+ if (skinnedParts === 0 && jointCount > 0) {
+ problems.push(diagnostic('rig-without-skin', 'warning', assetId,
+ `The asset has ${jointCount} joint nodes but no mesh is skinned to them, so moving a joint changes nothing you can see.`,
+ 'Move the parent node with set-asset-node instead, or fix the skin binding in the source file.'));
+ }
+ if (clipCount === 0) {
+ problems.push(diagnostic('asset-without-clips', 'info', assetId,
+ 'The asset has no animation clips, so set-animation and the export clip option are unavailable.',
+ 'Pose it with motion tracks or ik, or choose an asset that ships clips.'));
+ }
+ return problems;
+}
diff --git a/src/agent-errors.js b/src/agent-errors.js
new file mode 100644
index 00000000..8238e0c4
--- /dev/null
+++ b/src/agent-errors.js
@@ -0,0 +1,10 @@
+/**
+ * Wording for the agent errors that recorded runs hit most. The session errors alone were a third of all tool errors
+ * (21 of 68): an agent used an ID it invented, or one from a scene that was disposed or never created.
+ */
+export function sessionProblem(requestedSessionId, activeSessionId) {
+ if (!activeSessionId) {
+ return 'No scene is active: it was never created, was disposed, or scene_create failed. Call scene_create or scene_create_asset first, then pass the sessionId it returns.';
+ }
+ return `Unknown scene session ${requestedSessionId}. The active session is ${activeSessionId}; pass that sessionId, or call scene_dispose and then scene_create for a new scene.`;
+}
diff --git a/src/agent-mesh.js b/src/agent-mesh.js
index a62113d9..a14a777a 100644
--- a/src/agent-mesh.js
+++ b/src/agent-mesh.js
@@ -131,7 +131,7 @@ export function meshReport(geometry) {
if (report) return report;
const polygon = polygonMeshes.get(geometry);
const mesh = polygon?.mesh ?? meshFromGeometry(geometry);
- const lint = lintMesh(mesh);
+ const lint = lintMesh(mesh, { geometry: true });
report = Object.freeze({
ok: lint.ok,
counts: { ...lint.counts, triangles: geometry.indices.length / 3, renderVertices: geometry.positions.length / 3 },
@@ -140,6 +140,7 @@ export function meshReport(geometry) {
tags: lint.tags,
bounds: roundedBounds(lint.bounds),
problems: lint.problems,
+ ...(lint.skippedChecks ? { skippedChecks: lint.skippedChecks } : {}),
...(polygon ? { edits: polygon.results, stack: polygon.stack } : {}),
});
reports.set(geometry, report);
diff --git a/src/agent-physics.js b/src/agent-physics.js
index e413ba7e..5fcd2838 100644
--- a/src/agent-physics.js
+++ b/src/agent-physics.js
@@ -30,7 +30,7 @@ function knownKeys(value, fields, label) {
}
for (const key of Object.keys(value)) {
if (!fields.includes(key)) {
- throw new TypeError(`Unknown or unsupported ${label} field: ${key}.`);
+ throw new TypeError(`Unknown or unsupported ${label} field: ${key}. Allowed fields: ${fields.join(", ")}.`);
}
}
}
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 25d1500c..564aa116 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -12,6 +12,7 @@ import { expandInstancedNodes } from './mesh-instances.js';
import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, MAX_MATERIAL_PATTERNS, RECIPE_ALPHA_MODES } from './agent-scene-capabilities.js';
import { MATERIAL_LAYER_FIELDS, validateMaterialLayers } from './material-layers.js';
import { materialPatternTextures, normalizeMaterialPattern } from './material-patterns.js';
+import { recipeDiagnostics } from './agent-diagnostics.js';
export { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS };
export { normalizeAgentLook, resolveAgentShadow } from './agent-look.js';
export { needsMeshBooleans } from './agent-mesh.js';
@@ -48,7 +49,7 @@ function knownKeys(value, allowed, label) {
}
for (const key of Object.keys(value)) {
if (!allowed.includes(key)) {
- throw new TypeError(`Unknown ${label} field: ${key}.`);
+ throw new TypeError(`Unknown ${label} field: ${key}. Allowed fields: ${allowed.join(", ")}.`);
}
}
}
@@ -179,7 +180,7 @@ function resources(values, maximum, label, validate) {
return values.map(value => {
identifier(value?.id);
if (seen.has(value.id)) {
- throw new RangeError(`Duplicate ${label} ID: ${value.id}.`);
+ throw new RangeError(`Duplicate ${label} ID: ${value.id}. IDs must be unique: rename one, or remove the other.`);
}
seen.add(value.id);
return validate(value);
@@ -273,7 +274,7 @@ function nodeFrom(value) {
}
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.');
+ throw new TypeError(`Node ${value.id}: set both geometry and material, or neither for a group node.`);
}
if (value.geometry !== undefined) {
identifier(value.geometry);
@@ -332,7 +333,7 @@ const GEOMETRY_FIELDS = {
function geometryEstimate(value) {
if (!Object.hasOwn(GEOMETRY_FIELDS, value.type)) {
- throw new TypeError('Unsupported geometry type.');
+ throw new TypeError(`Unsupported geometry type: ${value.type}. Use one of ${Object.keys(GEOMETRY_FIELDS).join(', ')}.`);
}
knownKeys(value, ['id', 'type', ...GEOMETRY_FIELDS[value.type]], 'geometry');
function detail(field, fallback, minimum, maximum) {
@@ -440,7 +441,7 @@ 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(`Unknown resource referenced by node ${node.id}.`);
+ throw new RangeError(`Node ${node.id} uses ${geometries.has(node.geometry) ? `material ${node.material}` : `geometry ${node.geometry}`}, which does not exist. Add it to the recipe, or point the node at one of: ${(geometries.has(node.geometry) ? [...materials.keys()] : [...geometries.keys()]).join(', ')}.`);
}
return { name: node.id, parent: node.parent,
matrix: mat4.fromRotationTranslationScale(mat4.create(), node.rotation, node.translation, node.scale),
@@ -670,7 +671,7 @@ function removeNode(candidate, operation) {
throw new TypeError('recursive must be boolean.');
}
if (!candidate.nodes.some(node => node.id === operation.id)) {
- throw new RangeError(`Operation ID was not found: ${operation.id}.`);
+ throw new RangeError(`${operation.type} target was not found: ${operation.id}. List current IDs with scene_inspect, or add it first with add-node, add-geometry or add-material.`);
}
const children = new Map();
for (const node of candidate.nodes) {
@@ -948,7 +949,7 @@ export function createAgentScene(input, inputLimits = {}) {
nodeFrom(record);
}
if (candidate[collection].some(existing => existing.id === record.id)) {
- throw new RangeError(`Duplicate ${collection} ID: ${record.id}.`);
+ throw new RangeError(`Duplicate ${collection} ID: ${record.id}. IDs must be unique: pick a new ID, or remove the existing one first.`);
}
candidate[collection].push(record);
continue;
@@ -958,7 +959,7 @@ export function createAgentScene(input, inputLimits = {}) {
identifier(operation.geometry);
const target = candidate.geometries.find(geometry => geometry.id === operation.geometry);
if (!target) {
- throw new RangeError(`Geometry ID was not found: ${operation.geometry}.`);
+ throw new RangeError(`Geometry ID was not found: ${operation.geometry}. Known geometry IDs: ${[...candidate.geometries.map(known => known.id)].join(', ')}.`);
}
if (target.type !== 'mesh') {
throw new TypeError(`Geometry ${operation.geometry} is a ${target.type}. Add a mesh geometry with base: { type: '${target.type}', ... } to edit it.`);
@@ -978,7 +979,7 @@ export function createAgentScene(input, inputLimits = {}) {
identifier(operation.geometry);
const target = candidate.geometries.find(geometry => geometry.id === operation.geometry);
if (!target) {
- throw new RangeError(`Geometry ID was not found: ${operation.geometry}.`);
+ throw new RangeError(`Geometry ID was not found: ${operation.geometry}. Known geometry IDs: ${[...candidate.geometries.map(known => known.id)].join(', ')}.`);
}
if (target.type !== 'mesh') {
throw new TypeError(`Geometry ${operation.geometry} is a ${target.type}. Only mesh geometries have a modifier stack.`);
@@ -1007,7 +1008,7 @@ export function createAgentScene(input, inputLimits = {}) {
identifier(operation.id);
const index = candidate[removal].findIndex(record => record.id === operation.id);
if (index < 0) {
- throw new RangeError(`Operation ID was not found: ${operation.id}.`);
+ throw new RangeError(`${operation.type} target was not found: ${operation.id}. List current IDs with scene_inspect, or add it first with add-node, add-geometry or add-material.`);
}
candidate[removal].splice(index, 1);
if (operation.type === 'remove-material') {
@@ -1027,11 +1028,11 @@ export function createAgentScene(input, inputLimits = {}) {
fields = CAMERA_FIELDS;
target = candidate.camera;
} else {
- throw new TypeError('Unsupported operation type.');
+ throw new TypeError(`Unsupported operation type: ${operation.type}. Use one of set-node, set-material, set-camera, set-motion, set-physics, set-environment, set-effects, set-shadow, add-node, add-geometry, add-material, remove-node, remove-geometry, remove-material, edit-mesh, set-mesh-stack.`);
}
knownKeys(operation, ['type', ...(operation.type === 'set-camera' ? [] : ['id']), ...fields], 'operation');
if (!target) {
- throw new RangeError(`Operation ID was not found: ${operation.id}.`);
+ throw new RangeError(`${operation.type} target was not found: ${operation.id}. List current IDs with scene_inspect, or add it first with add-node, add-geometry or add-material.`);
}
for (const field of fields) {
if (Object.hasOwn(operation, field)) {
@@ -1054,7 +1055,7 @@ export function createAgentScene(input, inputLimits = {}) {
identifier(id);
const node = state.recipe.nodes.find(value => value.id === id);
if (!node) {
- throw new RangeError(`Inspection ID was not found: ${id}.`);
+ throw new RangeError(`Inspection ID was not found: ${id}. Call scene_inspect without ids to list node IDs.`);
}
return node;
});
@@ -1072,12 +1073,14 @@ export function createAgentScene(input, inputLimits = {}) {
return result;
});
const resident = geometryStats(ownedGeometryRecords());
+ const diagnostics = recipeDiagnostics(state.recipe);
return {
revision, topologyRevision,
...(state.recipe.motion?.ik?.length ? { motionIk: compileAgentMotion(state.recipe.motion, state.recipe).sweepIk() } : {}),
motion: state.recipe.motion ? { duration: state.recipe.motion.duration, loop: state.recipe.motion.loop, tracks: state.recipe.motion.tracks.length, time: state.motionTime } : null,
physics: state.physicsSampler ? state.physicsSampler.report() : null,
boundsSpace: 'authored-base-world',
+ ...(diagnostics.length ? { diagnostics } : {}),
counts: {
nodes: state.recipe.nodes.length, parts: state.parts.length,
geometries: state.geometries.size, materials: state.recipe.materials.length,
@@ -1133,13 +1136,13 @@ export function createAgentScene(input, inputLimits = {}) {
expected(options);
const checkpoint = checkpoints.get(handle);
if (!checkpoint) {
- throw new RangeError('Unknown or released checkpoint.');
+ throw new RangeError('Unknown or released checkpoint. Save one with scene_checkpoint, or use a checkpointId that scene_checkpoint returned and you have not released.');
}
return commit(stage(checkpoint.recipe, checkpoint), true);
},
releaseCheckpoint(handle) {
if (!checkpoints.delete(handle)) {
- throw new RangeError('Unknown or released checkpoint.');
+ throw new RangeError('Unknown or released checkpoint. Save one with scene_checkpoint, or use a checkpointId that scene_checkpoint returned and you have not released.');
}
},
});
diff --git a/src/mesh-lint-geometry.js b/src/mesh-lint-geometry.js
new file mode 100644
index 00000000..42697587
--- /dev/null
+++ b/src/mesh-lint-geometry.js
@@ -0,0 +1,258 @@
+import { createMeshQueryIndex, createMeshPairQuery } from './mesh-query.js';
+import { faceNormals } from './mesh-normals.js';
+
+/**
+ * Shape checks that need a spatial index: parts that cross, solids that cross themselves, walls too thin to print or
+ * survive a bevel, parts that float free, and meshes that are almost symmetric. Each check has a budget so a lint call
+ * stays cheap; a check that would pass it is skipped and named in the result instead of running long.
+ */
+export const GEOMETRY_LINT_BUDGET = Object.freeze({
+ maxTrianglesPerPart: 20_000,
+ maxTotalTriangles: 60_000,
+ maxPartPairs: 64,
+ maxThinWallSamples: 256,
+ maxSymmetryVertices: 50_000,
+ maxSampleElements: 8,
+});
+
+// Fractions of the mesh bounds diagonal.
+const THIN_WALL_RATIO = 0.005;
+const CONTACT_RATIO = 1e-4;
+const SYMMETRY_MATCH_RATIO = 1e-4;
+// Below this share of matched vertices a mesh is simply not symmetric; at or above it, the misses are mistakes.
+const SYMMETRY_INTENT_SHARE = 0.8;
+const IDENTITY_MATRIX = Object.freeze([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
+
+function partFaces(facePart, partCount) {
+ const faces = Array.from({ length: partCount }, () => []);
+ for (let face = 0; face < facePart.length; face++) faces[facePart[face]].push(face);
+ return faces;
+}
+
+/** Fan-triangulates the faces of one part into a compact Float32/Uint32 geometry for the query index. */
+function partGeometry(mesh, faces) {
+ const compactIndex = new Map();
+ const positions = [];
+ const indices = [];
+ const compact = vertex => {
+ let index = compactIndex.get(vertex);
+ if (index === undefined) {
+ index = compactIndex.size;
+ compactIndex.set(vertex, index);
+ positions.push(mesh.positions[vertex * 3], mesh.positions[vertex * 3 + 1], mesh.positions[vertex * 3 + 2]);
+ }
+ return index;
+ };
+ for (const face of faces) {
+ const start = mesh.faceOffsets[face];
+ const end = mesh.faceOffsets[face + 1];
+ const anchor = compact(mesh.cornerVertices[start]);
+ for (let corner = start + 1; corner + 1 < end; corner++) {
+ indices.push(anchor, compact(mesh.cornerVertices[corner]), compact(mesh.cornerVertices[corner + 1]));
+ }
+ }
+ return { positions: Float32Array.from(positions), indices: Uint32Array.from(indices) };
+}
+
+function geometryBounds(geometry) {
+ const min = [Infinity, Infinity, Infinity];
+ const max = [-Infinity, -Infinity, -Infinity];
+ for (let offset = 0; offset < geometry.positions.length; offset += 3) {
+ for (let axis = 0; axis < 3; axis++) {
+ min[axis] = Math.min(min[axis], geometry.positions[offset + axis]);
+ max[axis] = Math.max(max[axis], geometry.positions[offset + axis]);
+ }
+ }
+ return { min, max };
+}
+
+function boundsGap(first, second) {
+ let squared = 0;
+ for (let axis = 0; axis < 3; axis++) {
+ const gap = Math.max(first.min[axis] - second.max[axis], second.min[axis] - first.max[axis], 0);
+ squared += gap * gap;
+ }
+ return Math.sqrt(squared);
+}
+
+function limitedSample(elements) {
+ return elements.slice(0, GEOMETRY_LINT_BUDGET.maxSampleElements);
+}
+
+function findFloatingParts(bounds, contactDistance) {
+ if (bounds.length < 2) return [];
+ const floating = [];
+ for (let part = 0; part < bounds.length; part++) {
+ const touching = bounds.some((other, otherPart) => otherPart !== part && boundsGap(bounds[part], other) <= contactDistance);
+ if (!touching) floating.push(part);
+ }
+ return floating;
+}
+
+function findIntersectingParts(geometries, bounds, contactDistance, skipped) {
+ const crossing = [];
+ let pairsTested = 0;
+ for (let first = 0; first < geometries.length; first++) {
+ for (let second = first + 1; second < geometries.length; second++) {
+ if (boundsGap(bounds[first], bounds[second]) > contactDistance) continue;
+ if (pairsTested++ >= GEOMETRY_LINT_BUDGET.maxPartPairs) {
+ skipped.add('intersecting-parts');
+ return crossing;
+ }
+ const firstIndex = createMeshQueryIndex(geometries[first]);
+ const secondIndex = createMeshQueryIndex(geometries[second]);
+ try {
+ const result = createMeshPairQuery(firstIndex, secondIndex).evaluate(IDENTITY_MATRIX, IDENTITY_MATRIX);
+ if (result.kind === 'surface-intersection') crossing.push(first * 1000 + second);
+ } catch {
+ skipped.add('intersecting-parts');
+ } finally {
+ firstIndex.dispose();
+ secondIndex.dispose();
+ }
+ }
+ }
+ return crossing;
+}
+
+const SELF_INTERSECTION_MESSAGE = /intersect|overlap/i;
+
+function hasSelfIntersection(geometry, skipped) {
+ try {
+ createMeshQueryIndex(geometry, { solid: true }).dispose();
+ return false;
+ } catch (error) {
+ if (SELF_INTERSECTION_MESSAGE.test(error.message)) return true;
+ skipped.add('self-intersection');
+ return false;
+ }
+}
+
+function faceCentroid(mesh, face) {
+ const start = mesh.faceOffsets[face];
+ const end = mesh.faceOffsets[face + 1];
+ const centroid = [0, 0, 0];
+ for (let corner = start; corner < end; corner++) {
+ for (let axis = 0; axis < 3; axis++) centroid[axis] += mesh.positions[mesh.cornerVertices[corner] * 3 + axis];
+ }
+ return centroid.map(value => value / (end - start));
+}
+
+/** Casts a ray from each sampled face straight into the solid; a near hit means the wall is thin there. */
+function findThinFaces(mesh, geometry, faces, normals, diagonal) {
+ const index = createMeshQueryIndex(geometry);
+ const nudge = diagonal * CONTACT_RATIO;
+ const limit = diagonal * THIN_WALL_RATIO;
+ const stride = Math.max(1, Math.ceil(faces.length / GEOMETRY_LINT_BUDGET.maxThinWallSamples));
+ const thin = [];
+ try {
+ for (let position = 0; position < faces.length; position += stride) {
+ const face = faces[position];
+ const normal = [normals[face * 3], normals[face * 3 + 1], normals[face * 3 + 2]];
+ const centroid = faceCentroid(mesh, face);
+ const origin = centroid.map((value, axis) => value - normal[axis] * nudge);
+ const hit = index.raycast(IDENTITY_MATRIX, { origin, direction: normal.map(value => -value) });
+ if (hit && hit.distance + nudge < limit) thin.push(face);
+ }
+ } finally {
+ index.dispose();
+ }
+ return thin;
+}
+
+function cellKey(cell) {
+ return `${cell[0]},${cell[1]},${cell[2]}`;
+}
+
+/** Vertices that have no partner when the mesh is mirrored across the plane at `plane` on one axis. */
+function unmatchedMirrorVertices(mesh, axis, plane, tolerance) {
+ const cellSize = tolerance * 4;
+ const cells = new Set();
+ const cellOf = point => point.map(value => Math.round(value / cellSize));
+ const pointOf = vertex => [mesh.positions[vertex * 3], mesh.positions[vertex * 3 + 1], mesh.positions[vertex * 3 + 2]];
+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) cells.add(cellKey(cellOf(pointOf(vertex))));
+ const unmatched = [];
+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {
+ const mirrored = pointOf(vertex);
+ mirrored[axis] = 2 * plane - mirrored[axis];
+ const home = cellOf(mirrored);
+ let matched = false;
+ for (let x = -1; x <= 1 && !matched; x++) {
+ for (let y = -1; y <= 1 && !matched; y++) {
+ for (let z = -1; z <= 1 && !matched; z++) {
+ matched = cells.has(cellKey([home[0] + x, home[1] + y, home[2] + z]));
+ }
+ }
+ }
+ if (!matched) unmatched.push(vertex);
+ }
+ return unmatched;
+}
+
+function findAsymmetry(mesh, bounds, diagonal) {
+ const found = [];
+ for (const [axis, name] of [[0, 'x'], [2, 'z']]) {
+ // A mirrored model is usually centred on the origin; otherwise on its bounds or its mean. Take the best plane.
+ let mean = 0;
+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) mean += mesh.positions[vertex * 3 + axis];
+ const planes = [0, (bounds.min[axis] + bounds.max[axis]) / 2, mean / mesh.vertexCount];
+ const candidates = planes.map(plane => unmatchedMirrorVertices(mesh, axis, plane, diagonal * SYMMETRY_MATCH_RATIO));
+ const unmatched = candidates.reduce((best, candidate) => (candidate.length < best.length ? candidate : best));
+ const matchedShare = 1 - unmatched.length / mesh.vertexCount;
+ if (unmatched.length > 0 && matchedShare >= SYMMETRY_INTENT_SHARE) found.push({ axis: name, unmatched });
+ }
+ return found;
+}
+
+// The query index rejects triangles below its precision domain; a check that cannot run is named, never thrown.
+function attempt(check, skipped, work, fallback) {
+ try {
+ return work();
+ } catch {
+ skipped.add(check);
+ return fallback;
+ }
+}
+
+function problem(kind, elements, extra = {}) {
+ return { kind, count: elements.length, sample: limitedSample(elements), ...extra };
+}
+
+/**
+ * Runs the spatial checks on a polygon mesh. `solidParts` lists the parts that are closed, consistently wound and
+ * outward facing. Returns { problems, skipped }, where each problem has kind, count and a sample of element indices
+ * (part pairs as first * 1000 + second, parts, faces or vertices by kind).
+ */
+export function lintMeshGeometry(mesh, { facePart, partCount, solidParts, bounds, diagonal }) {
+ const skipped = new Set();
+ const found = [];
+ const faces = partFaces(facePart, partCount);
+ const contactDistance = diagonal * CONTACT_RATIO;
+ const totalFaces = faces.reduce((total, partFaceList) => total + partFaceList.length, 0);
+ // Budgets count faces; a quad is two triangles, so these are loose upper-bound proxies for triangles.
+ const withinBudget = totalFaces <= GEOMETRY_LINT_BUDGET.maxTotalTriangles
+ && faces.every(partFaceList => partFaceList.length <= GEOMETRY_LINT_BUDGET.maxTrianglesPerPart);
+ if (withinBudget) {
+ const geometries = faces.map(partFaceList => partGeometry(mesh, partFaceList));
+ const partBounds = geometries.map(geometryBounds);
+ const crossing = attempt('intersecting-parts', skipped, () => findIntersectingParts(geometries, partBounds, contactDistance, skipped), []);
+ if (crossing.length) found.push(problem('intersecting-parts', crossing));
+ const selfCrossing = solidParts.filter(part => hasSelfIntersection(geometries[part], skipped));
+ if (selfCrossing.length) found.push(problem('self-intersection', selfCrossing));
+ const { normals } = faceNormals(mesh);
+ const thinFaces = solidParts.flatMap(part => attempt('thin-wall', skipped, () => findThinFaces(mesh, geometries[part], faces[part], normals, diagonal), []));
+ if (thinFaces.length) found.push(problem('thin-wall', thinFaces));
+ const floating = findFloatingParts(partBounds, contactDistance);
+ if (floating.length) found.push(problem('floating-part', floating));
+ } else {
+ for (const check of ['intersecting-parts', 'self-intersection', 'thin-wall', 'floating-part']) skipped.add(check);
+ }
+ if (mesh.vertexCount <= GEOMETRY_LINT_BUDGET.maxSymmetryVertices) {
+ for (const { axis, unmatched } of findAsymmetry(mesh, bounds, diagonal)) {
+ found.push(problem('asymmetric', unmatched, { axis }));
+ }
+ } else {
+ skipped.add('asymmetric');
+ }
+ return { problems: found, skipped: [...skipped] };
+}
diff --git a/src/mesh-lint.js b/src/mesh-lint.js
index 0873c9e5..fb78f87f 100644
--- a/src/mesh-lint.js
+++ b/src/mesh-lint.js
@@ -1,4 +1,5 @@
import { meshBounds, tagCounts } from './mesh-data.js';
+import { lintMeshGeometry } from './mesh-lint-geometry.js';
import { faceNormals } from './mesh-normals.js';
import { cornerFaces, edgeCornerTable, faceParts } from './mesh-topology.js';
@@ -14,6 +15,16 @@ const PROBLEMS = Object.freeze({
'boundary-edge': { severity: 'warning', fix: 'Open surface. Run fill_holes to cap each boundary loop, or add solidify if the part must be closed.' },
});
+// Spatial checks, opt in through lintMesh(mesh, { geometry: true }) because each builds a BVH. All are warnings: a mesh
+// can cross itself, be thin or float on purpose, so none of them turns ok off.
+export const GEOMETRY_PROBLEMS = Object.freeze({
+ 'intersecting-parts': { severity: 'warning', fix: 'Two parts cross each other (sample holds first * 1000 + second part index). Move them apart, or run a union boolean if they should be one solid.' },
+ 'self-intersection': { severity: 'warning', fix: 'A closed part cuts through itself. Undo the last extrude, inset or translate that folded it, or lower its offset.' },
+ 'thin-wall': { severity: 'warning', fix: 'The wall behind these faces (sample is face indices) is under 0.5% of the mesh size thick. Thicken it with solidify, or move the faces apart.' },
+ 'floating-part': { severity: 'warning', fix: 'This part (sample is part indices) touches no other part. Translate it onto its neighbour, or ignore this if it is meant to stand alone.' },
+ asymmetric: { severity: 'warning', fix: 'The mesh is mirror-symmetric except for the vertices in sample. Rebuild one half and mirror it, or set_position those vertices to their partners.' },
+});
+
function addProblem(problems, kind, element) {
let problem = problems.get(kind);
if (!problem) {
@@ -101,7 +112,7 @@ function insideOtherPart(mesh, facePart, part) {
* Returns { ok, counts, parts, tags, bounds, problems }, where each problem has kind, severity, count, a sample of
* element indices (faces, edges or vertices by kind) and a suggested fix. ok is false when any error is present.
*/
-export function lintMesh(mesh) {
+export function lintMesh(mesh, { geometry = false } = {}) {
const problems = new Map();
const table = edgeCornerTable(mesh);
const facesOfCorners = cornerFaces(mesh);
@@ -138,15 +149,25 @@ export function lintMesh(mesh) {
const volumes = partVolumes(mesh, facePart, partCount);
let closedParts = 0;
let cavities = 0;
+ const solidParts = [];
for (let part = 0; part < partCount; part++) {
if (partOpen[part] || partWindingBroken[part]) continue;
closedParts++;
- if (volumes[part] >= 0) continue;
+ if (volumes[part] >= 0) {
+ solidParts.push(part);
+ continue;
+ }
// A negative shell inside another part is a cavity (a hollow), which is valid; elsewhere it is inside out.
if (insideOtherPart(mesh, facePart, part)) cavities++;
else addProblem(problems, 'inverted-part', part);
}
const problemList = [...problems.values()];
+ let skippedChecks;
+ if (geometry) {
+ const spatial = lintMeshGeometry(mesh, { facePart, partCount, solidParts, bounds, diagonal });
+ for (const found of spatial.problems) problemList.push({ ...found, ...GEOMETRY_PROBLEMS[found.kind] });
+ if (spatial.skipped.length) skippedChecks = spatial.skipped;
+ }
return {
ok: !problemList.some(problem => problem.severity === 'error'),
counts: { vertices: mesh.vertexCount, edges: mesh.edgeCount, faces: mesh.faceCount, corners: mesh.cornerCount },
@@ -154,5 +175,6 @@ export function lintMesh(mesh) {
tags: tagCounts(mesh),
bounds,
problems: problemList,
+ ...(skippedChecks ? { skippedChecks } : {}),
};
}
diff --git a/src/motion-validation.js b/src/motion-validation.js
index 7acf1eae..dd49dfdf 100644
--- a/src/motion-validation.js
+++ b/src/motion-validation.js
@@ -7,7 +7,7 @@ export function knownKeys(value, fields, label) {
for (const key of Reflect.ownKeys(value)) {
const descriptor = Object.getOwnPropertyDescriptor(value, key);
if (typeof key !== 'string' || !fields.includes(key) || !descriptor.enumerable || !Object.hasOwn(descriptor, 'value')) {
- throw new TypeError(`Unknown or unsupported ${label} field: ${String(key)}.`);
+ throw new TypeError(`Unknown or unsupported ${label} field: ${String(key)}. Allowed fields: ${fields.join(", ")}.`);
}
}
}
diff --git a/src/scene-graph.js b/src/scene-graph.js
index 24c57f7a..3581df1b 100644
--- a/src/scene-graph.js
+++ b/src/scene-graph.js
@@ -107,7 +107,7 @@ export function createSceneGraph(definitions = [], { maxNodes = 4096, maxDepth =
let parents = new Int32Array(records.length);
for (let index = 0; index < records.length; index++) {
const parent = records[index].parent;
- if (parent !== null && !namedIndices.has(parent)) throw new RangeError(`Node ${records[index].name} parent was not found: ${parent}`);
+ if (parent !== null && !namedIndices.has(parent)) throw new RangeError(`Node ${records[index].name} parent was not found: ${parent}. Add that node first, or set parent to null for a root.`);
parents[index] = parent === null ? -1 : namedIndices.get(parent);
}
let order = compileOrder(parents, maxDepth);
diff --git a/tests/agent-runtime.test.js b/tests/agent-runtime.test.js
index 387d23b5..6e9f2910 100644
--- a/tests/agent-runtime.test.js
+++ b/tests/agent-runtime.test.js
@@ -255,8 +255,8 @@ test('invalid preview configuration rejects before any browser or renderer alloc
test('requests cannot address an absent session or enter a closing runtime', async () => {
const runtime = createAgentRuntime();
- await assert.rejects(runtime.inspect({ sessionId: 'missing' }), /Unknown/);
- await assert.rejects(runtime.look({ sessionId: 'missing' }), /Unknown/);
+ await assert.rejects(runtime.inspect({ sessionId: 'missing' }), /Unknown|No scene is active/);
+ await assert.rejects(runtime.look({ sessionId: 'missing' }), /Unknown|No scene is active/);
const closing = runtime.close();
await assert.rejects(runtime.checkpoint({ sessionId: 'missing' }), /closing|closed/);
await closing;
diff --git a/tests/mesh-bevel.test.js b/tests/mesh-bevel.test.js
index 23200c3c..9a904be8 100644
--- a/tests/mesh-bevel.test.js
+++ b/tests/mesh-bevel.test.js
@@ -1,3 +1,4 @@
+import { GEOMETRY_PROBLEMS } from '../src/mesh-lint.js';
import assert from 'node:assert/strict';
import test from 'node:test';
import { box, cylinder } from '../src/geometry.js';
@@ -58,7 +59,7 @@ function volume(mesh) {
function closed(mesh) {
validateTopology(editMesh(mesh));
const report = lintMesh(mesh);
- assert.deepEqual(report.problems, []);
+ assert.deepEqual(report.problems.filter(problem => !(problem.kind in GEOMETRY_PROBLEMS)), []);
assert.equal(report.parts.closed, 1);
return report;
}
diff --git a/tests/mesh-boolean.test.js b/tests/mesh-boolean.test.js
index eab17f5f..1eda1bb0 100644
--- a/tests/mesh-boolean.test.js
+++ b/tests/mesh-boolean.test.js
@@ -1,3 +1,4 @@
+import { GEOMETRY_PROBLEMS } from '../src/mesh-lint.js';
import assert from 'node:assert/strict';
import test from 'node:test';
import { box, cylinder, sphere } from '../src/geometry.js';
@@ -103,7 +104,7 @@ test('chained booleans with coplanar contact stay closed', () => {
validateTopology(editMesh(mesh));
const report = lintMesh(mesh);
assert.equal(report.ok, true, `${step.name ?? step.op}: ${JSON.stringify(report.problems)}`);
- assert.deepEqual(report.problems, []);
+ assert.deepEqual(report.problems.filter(problem => !(problem.kind in GEOMETRY_PROBLEMS)), []);
}
});
diff --git a/tests/mesh-lint-geometry.test.js b/tests/mesh-lint-geometry.test.js
new file mode 100644
index 00000000..86ca9ca4
--- /dev/null
+++ b/tests/mesh-lint-geometry.test.js
@@ -0,0 +1,75 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { box, cylinder, sphere } from '../src/geometry.js';
+import { meshFromGeometry, lintMesh } from '../src/mesh.js';
+import { GEOMETRY_LINT_BUDGET } from '../src/mesh-lint-geometry.js';
+
+function placedBox({ scale = [1, 1, 1], translation = [0, 0, 0] }) {
+ const source = box(0, 1);
+ const positions = Float32Array.from(source.positions, (value, index) => value * scale[index % 3] + translation[index % 3]);
+ return { positions, indices: source.indices };
+}
+
+function joined(...geometries) {
+ const positions = [];
+ const indices = [];
+ for (const geometry of geometries) {
+ const base = positions.length / 3;
+ positions.push(...geometry.positions);
+ indices.push(...Array.from(geometry.indices, index => index + base));
+ }
+ return { positions: Float32Array.from(positions), indices: Uint32Array.from(indices) };
+}
+
+function kinds(mesh) {
+ return lintMesh(mesh, { geometry: true }).problems.map(problem => problem.kind);
+}
+
+test('a single cube and a cylinder raise no spatial warnings', () => {
+ assert.deepEqual(kinds(meshFromGeometry(box(0, 1))), []);
+ assert.deepEqual(kinds(meshFromGeometry(cylinder(24, 0, 1))), []);
+});
+
+test('two boxes that cross are reported as intersecting parts with the pair in the sample', () => {
+ const mesh = meshFromGeometry(joined(placedBox({}), placedBox({ translation: [0.5, 0.5, 0.5] })));
+ const report = lintMesh(mesh, { geometry: true });
+ const crossing = report.problems.find(problem => problem.kind === 'intersecting-parts');
+ assert.equal(crossing.count, 1);
+ assert.equal(crossing.severity, 'warning');
+ assert.match(crossing.fix, /union boolean/);
+ assert.equal(report.ok, true);
+});
+
+test('a part that touches nothing floats, and a part resting on another does not', () => {
+ const apart = meshFromGeometry(joined(placedBox({}), placedBox({ translation: [3, 0, 0] })));
+ assert.equal(lintMesh(apart, { geometry: true }).problems.find(problem => problem.kind === 'floating-part').count, 2);
+ const resting = meshFromGeometry(joined(placedBox({}), placedBox({ translation: [1, 0, 0] })));
+ assert.equal(kinds(resting).includes('floating-part'), false);
+});
+
+test('a plate under half a percent of the mesh size is a thin wall, and a slab is not', () => {
+ const plate = meshFromGeometry(placedBox({ scale: [1, 0.002, 1] }));
+ const thin = lintMesh(plate, { geometry: true }).problems.find(problem => problem.kind === 'thin-wall');
+ assert.ok(thin.count > 0);
+ assert.match(thin.fix, /solidify/);
+ assert.equal(kinds(meshFromGeometry(placedBox({ scale: [1, 0.2, 1] }))).includes('thin-wall'), false);
+});
+
+test('a mesh that is mirror-symmetric except for one moved vertex names the axis and the vertex', () => {
+ const mesh = meshFromGeometry(sphere(16, 10));
+ const symmetric = kinds(mesh);
+ assert.equal(symmetric.includes('asymmetric'), false);
+ const moved = { ...mesh, positions: Float32Array.from(mesh.positions) };
+ const vertex = Array.from({ length: moved.vertexCount }, (value, index) => index).find(index => moved.positions[index * 3] > 0.3);
+ moved.positions[vertex * 3] += 0.05;
+ const problem = lintMesh(moved, { geometry: true }).problems.find(found => found.kind === 'asymmetric' && found.axis === 'x');
+ assert.ok(problem.sample.includes(vertex));
+ assert.match(problem.fix, /mirror/);
+});
+
+test('plain lintMesh stays free of spatial checks and a clean mesh skips none', () => {
+ const mesh = meshFromGeometry(placedBox({ scale: [1, 0.002, 1] }));
+ assert.deepEqual(lintMesh(mesh).problems.map(problem => problem.kind), []);
+ assert.equal(lintMesh(mesh, { geometry: true }).skippedChecks, undefined);
+ assert.ok(GEOMETRY_LINT_BUDGET.maxTotalTriangles >= GEOMETRY_LINT_BUDGET.maxTrianglesPerPart);
+});
diff --git a/tests/skill-mesh-recipes.test.js b/tests/skill-mesh-recipes.test.js
index f6951e17..f8d8cff4 100644
--- a/tests/skill-mesh-recipes.test.js
+++ b/tests/skill-mesh-recipes.test.js
@@ -1,3 +1,4 @@
+import { GEOMETRY_PROBLEMS } from '../src/mesh-lint.js';
import assert from 'node:assert/strict';
import test from 'node:test';
import { readFile } from 'node:fs/promises';
@@ -25,7 +26,7 @@ for (const geometry of geometries) {
});
const [report] = scene.inspectMeshes().meshes;
assert.equal(report.ok, true, JSON.stringify(report.problems));
- assert.deepEqual(report.problems, []);
+ assert.deepEqual(report.problems.filter(problem => !(problem.kind in GEOMETRY_PROBLEMS)), []);
assert.equal(report.parts.closed, report.parts.count, 'every part is closed');
});
}
diff --git a/tests/tool-cost.test.js b/tests/tool-cost.test.js
new file mode 100644
index 00000000..cbebe7e3
--- /dev/null
+++ b/tests/tool-cost.test.js
@@ -0,0 +1,32 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { measureToolCost } from '../scripts/measure-tool-cost.mjs';
+
+const budgets = JSON.parse(readFileSync(new URL('../bench/tool-cost-budgets.json', import.meta.url), 'utf8'));
+const report = await measureToolCost();
+
+test('the tool schemas an agent reads on every turn stay under their total budget', () => {
+ assert.ok(report.schemaTotal.bytes <= budgets.schemaTotalBytes,
+ `tool schemas are ${report.schemaTotal.bytes} bytes, over the ${budgets.schemaTotalBytes} budget. Move rare detail into scene_capabilities or reference a shared schema; raise bench/tool-cost-budgets.json only for a feature that needs it.`);
+});
+
+test('each large tool schema and every small one stays under its own budget', () => {
+ for (const row of report.schemas) {
+ const budget = budgets.schemaToolBytes[row.name] ?? budgets.schemaOtherToolBytes;
+ assert.ok(row.bytes <= budget, `${row.name} is ${row.bytes} bytes, over its ${budget} budget.`);
+ }
+});
+
+test('typical results stay under their budgets', () => {
+ for (const row of report.results) {
+ const budget = budgets.resultBytes[row.name];
+ assert.ok(budget !== undefined, `${row.name} has no result budget; add one to bench/tool-cost-budgets.json.`);
+ assert.ok(row.bytes <= budget, `${row.name} result is ${row.bytes} bytes, over its ${budget} budget.`);
+ }
+});
+
+test('a small mesh change as a mesh_edit call is smaller than rewriting the recipe', () => {
+ const { meshEditCall, rewriteCall } = report.comparison;
+ assert.ok(meshEditCall.bytes * 3 < rewriteCall.bytes, `mesh_edit ${meshEditCall.bytes} B against rewrite ${rewriteCall.bytes} B`);
+});
diff --git a/tests/tool-errors.test.js b/tests/tool-errors.test.js
new file mode 100644
index 00000000..3bf1d000
--- /dev/null
+++ b/tests/tool-errors.test.js
@@ -0,0 +1,83 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createAgentScene } from '../src/agent-scene.js';
+import { sessionProblem } from '../src/agent-errors.js';
+import { readableErrorMessage } from '../scripts/mcp-server.mjs';
+
+function baseRecipe() {
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'cube', type: 'box', bevel: 0 }, { id: 'block', type: 'mesh', base: { type: 'box', bevel: 0 } }],
+ materials: [{ id: 'paint', color: [0.2, 0.4, 0.8] }],
+ nodes: [{ id: 'body', geometry: 'cube', material: 'paint' }, { id: 'child', parent: 'body' }],
+ };
+}
+
+function withRecipe(change) {
+ const recipe = baseRecipe();
+ change(recipe);
+ return () => createAgentScene(recipe);
+}
+
+function onScene(action) {
+ return () => action(createAgentScene(baseRecipe()));
+}
+
+// Each trigger is a way an agent reaches an error. The message must say what failed and what to do next.
+const TRIGGERS = {
+ 'unknown geometry type': withRecipe(recipe => { recipe.geometries[0].type = 'pyramid'; }),
+ 'unknown geometry field': withRecipe(recipe => { recipe.geometries[0].width = 2; }),
+ 'node refers to a missing geometry': withRecipe(recipe => { recipe.nodes[0].geometry = 'nothing'; }),
+ 'node refers to a missing material': withRecipe(recipe => { recipe.nodes[0].material = 'nothing'; }),
+ 'node with a geometry and no material': withRecipe(recipe => { delete recipe.nodes[0].material; }),
+ 'node parent that does not exist': withRecipe(recipe => { recipe.nodes[1].parent = 'ghost'; }),
+ 'duplicate node id': withRecipe(recipe => { recipe.nodes.push({ id: 'body' }); }),
+ 'opacity above one': withRecipe(recipe => { recipe.materials[0].opacity = 2; }),
+ 'unknown alpha mode': withRecipe(recipe => { recipe.materials[0].alphaMode = 'additive'; }),
+ 'pattern with one colour': withRecipe(recipe => { recipe.materials[0].pattern = { type: 'bricks', colors: [[1, 1, 1]] }; }),
+ 'transmission on an unlit material': withRecipe(recipe => { Object.assign(recipe.materials[0], { tag: 'unlit', transmission: 0.5 }); }),
+ 'mesh edit with an unknown op': withRecipe(recipe => { recipe.geometries[1].edits = [{ op: 'explode' }]; }),
+ 'mesh edit that selects nothing': onScene(scene => scene.apply([{ type: 'edit-mesh', geometry: 'block', edits: [{ op: 'delete', select: { tag: 'nowhere' } }] }], { expectedRevision: 0 })),
+ 'mesh edit on a primitive geometry': onScene(scene => scene.apply([{ type: 'edit-mesh', geometry: 'cube', edits: [{ op: 'flip_normals', select: { all: true } }] }], { expectedRevision: 0 })),
+ 'mesh edit on a missing geometry': onScene(scene => scene.apply([{ type: 'edit-mesh', geometry: 'nothing', edits: [{ op: 'flip_normals', select: { all: true } }] }], { expectedRevision: 0 })),
+ 'stale revision': onScene(scene => scene.apply([{ type: 'set-node', id: 'body', translation: [1, 0, 0] }], { expectedRevision: 9 })),
+ 'unknown operation type': onScene(scene => scene.apply([{ type: 'set-everything' }], { expectedRevision: 0 })),
+ 'set-node on a missing node': onScene(scene => scene.apply([{ type: 'set-node', id: 'ghost', translation: [1, 0, 0] }], { expectedRevision: 0 })),
+ 'set-node with an unknown field': onScene(scene => scene.apply([{ type: 'set-node', id: 'body', colour: 'red' }], { expectedRevision: 0 })),
+ 'remove a geometry that a node uses': onScene(scene => scene.apply([{ type: 'remove-geometry', id: 'cube' }], { expectedRevision: 0 })),
+ 'remove a node that has children': onScene(scene => scene.apply([{ type: 'remove-node', id: 'body' }], { expectedRevision: 0 })),
+ 'inspect a missing node': onScene(scene => scene.inspect({ ids: ['ghost'] })),
+ 'inspect with an unknown option': onScene(scene => scene.inspect({ kind: 'hierarchy' })),
+ 'mesh inspect of a missing geometry': onScene(scene => scene.inspectMeshes({ geometries: ['nothing'] })),
+ 'rotation that is not a unit quaternion': withRecipe(recipe => { recipe.nodes[0].rotation = [0, 0, 0, 0]; }),
+ 'scale that is not positive': withRecipe(recipe => { recipe.nodes[0].scale = [1, 0, 1]; }),
+ 'motion with an unknown field': withRecipe(recipe => { recipe.motion = { duration: 1, loop: false, tracks: [], speed: 2 }; }),
+};
+
+// A message needs a next action: an imperative, a statement of the accepted values, or a list of valid choices.
+const NEXT_ACTION = /\b(use|call|set|remove|drop|pass|add|move|run|raise|lower|choose|check|read|list|re-?export|undo|assign|thicken|try|fix|delete|select|dispose|create|inspect|provide|name|must|needs?|expected|allowed|one of|known|between|within|at most|at least|nonzero|positive|finite)\b/i;
+
+for (const [label, trigger] of Object.entries(TRIGGERS)) {
+ test(`error for ${label} names what failed and what to do next`, () => {
+ let message;
+ try {
+ trigger();
+ } catch (error) {
+ message = readableErrorMessage(error);
+ }
+ assert.ok(message, `${label} must throw`);
+ assert.ok(message.length >= 30, `too short to name what failed: "${message}"`);
+ assert.match(message, NEXT_ACTION, `no next action in: "${message}"`);
+ assert.doesNotMatch(message, /^page\.evaluate|https?:\/\//, `leaks bundle internals: "${message}"`);
+ });
+}
+
+test('a session error names the active session or says how to create one', () => {
+ assert.match(sessionProblem('abc', undefined), /scene_create/);
+ assert.match(sessionProblem('abc', 'live-id'), /active session is live-id/);
+});
+
+test('page errors lose the evaluate prefix and the bundle stack', () => {
+ const error = new Error('page.evaluate: RangeError: Unknown mesh ID: node1. Use mesh-0. at Object.inspect (http://127.0.0.1:5173/preview.js:1:2) at Array.map (<anonymous>)');
+ assert.equal(readableErrorMessage(error), 'Unknown mesh ID: node1. Use mesh-0.');
+});