3D engine that AI agents drive
Keep the scene engine out of the MCP server bundle
Nguyen Xuan An48f1bbfcd5ad
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex df4a1824..20794406 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,7 @@## Unreleased+- Shrink the MCP server bundle from 1,072 KB to 590 KB by keeping the scene engine out of it: capabilities and default limits now come from plain-data modules (`agent-scene-capabilities.js`, `mesh-operations.js`), and the MCP build fails if engine code returns; the npm archive drops from 1,003 KB to 887 KB- Add `67js/addons/mesh`, a polygon mesh core for agent modeling: compact `MeshData` with attributes on point, edge, face and corner domains, a half-edge `EditMesh` with typed-array disk and radial cycles, `validateTopology`, conversion from renderer geometry with welding, quads and axis face tags, hard-edge corner normals, n-gon triangulation, render extraction and `lintMesh`- Add semantic face selection and mesh edits (extrude region and individual, inset region and individual, delete, flip normals, translate with proportional falloff, merge by distance, tag) that tag the faces they create- Add the recipe geometry type `mesh` (a base shape plus a replayable edit log) and the `mesh_edit` MCP tool, which appends or replaces edits atomically and reports each edit's resultdiff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjsindex 9d64a340..14ef078b 100644--- a/scripts/agent-runtime.mjs+++ b/scripts/agent-runtime.mjs@@ -5,14 +5,13 @@ import { readFile, writeFile } from 'node:fs/promises';import { isAbsolute, join } from 'node:path';import { createRequire } from 'node:module';import packageMetadata from '../package.json' with { type: 'json' };-import { createAgentScene, AGENT_SCENE_CAPABILITIES } from '../src/agent-scene.js';+import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS } from '../src/agent-scene-capabilities.js';import { createAgentAssetCatalog } from './agent-asset-catalog.mjs';import { createAgentRenderJobs } from './agent-render-jobs.mjs';import { createFrameEncoder } from './frame-encoder.mjs';import { normalizeReview, REVIEW_LIMITS } from './agent-review.mjs';-const EMPTY_RECIPE = { format: '67js.scene', schemaVersion: 1, geometries: [], materials: [], nodes: [] };-const SCENE_LIMITS = createAgentScene(EMPTY_RECIPE).limits;+const SCENE_LIMITS = AGENT_SCENE_DEFAULT_LIMITS;const MAXIMUM_IMAGE_BYTES = 1024 * 1024;const MAXIMUM_QUEUED_CALLS = 16;const EVALUATION_TIMEOUT_MS = 30000;diff --git a/scripts/build-mcp.mjs b/scripts/build-mcp.mjsindex 13287fbe..32edca15 100644--- a/scripts/build-mcp.mjs+++ b/scripts/build-mcp.mjs@@ -159,6 +159,13 @@ export async function buildMcp({ outDir = join(root, 'build', 'mcp') } = {}) {},},}), 'server.mjs', false);+ // The scene engine runs in the preview page; bundling it into the server again would cost ~120 KB of the npm+ // archive's 1 MiB budget for code the server never calls.+ for (const marker of ['ExtrudeGeometry', 'extrudeFaceRegion', 'createAgentScene']) {+ if (server.code.includes(marker)) {+ throw new Error(`server.mjs includes scene engine code (${marker}). Import plain data from agent-scene-capabilities.js instead of agent-scene.js.`);+ }+ }if (!server.exports.includes('createAgentMcpServer') || !server.exports.includes('runMcpCli')) {throw new Error('Node bundle must export createAgentMcpServer and runMcpCli.');}diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsnew file mode 100644index 00000000..3380b52c--- /dev/null+++ b/src/agent-scene-capabilities.js@@ -0,0 +1,31 @@+import { MESH_EDIT_OPERATIONS, MAX_MESH_EDITS, STACK_OPERATIONS, MAX_STACK_NODES } from './mesh-operations.js';++// What agent scenes support and their default limits, as plain data. The MCP server reads these without bundling+// the scene engine (geometry, three.js decoders, the mesh core), which runs in the preview page instead.++export const AGENT_SCENE_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,+});++// Procedural recipes have no textures, so cutout masking has nothing to cut.+export const RECIPE_ALPHA_MODES = Object.freeze(['opaque', 'blend']);++export const AGENT_SCENE_CAPABILITIES = Object.freeze({+ format: '67js.scene', schemaVersion: 1,+ geometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'mesh']),+ meshEdits: Object.freeze({ operations: Object.freeze(Object.keys(MESH_EDIT_OPERATIONS)), maxEdits: MAX_MESH_EDITS }),+ meshStack: Object.freeze({ operations: STACK_OPERATIONS, maxNodes: MAX_STACK_NODES }),+ operations: Object.freeze([+ 'set-node', 'set-material', 'set-camera', 'add-node', 'remove-node',+ 'add-geometry', 'remove-geometry', 'add-material', 'remove-material',+ 'set-environment', 'set-effects', 'set-shadow', 'set-motion', 'edit-mesh', 'set-mesh-stack',+ ]),+ materialTags: Object.freeze(['surface', 'unlit', 'liquid', 'foam']),+ alphaModes: RECIPE_ALPHA_MODES,+ fixedResources: false, dynamicTopology: true, checkpoints: true, positiveScaleOnly: true,+ authoredLook: true, maxPointLights: 8,+ proceduralMotion: true,+ motionLimits: Object.freeze({ maxTracks: 128, maxKeyframesPerTrack: 64, maxKeyframes: 2048, maxDuration: 30 }),+});diff --git a/src/agent-scene.js b/src/agent-scene.jsindex a29d7c87..14f4228f 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -6,22 +6,18 @@ import { applyProjection } from './camera.js';import { normalizeAgentLook } from './agent-look.js';import { normalizeAgentMotion, compileAgentMotion } from './agent-motion.js';import { meshReport, generateMeshGeometry, MESH_SMOOTH_ANGLE_DEFAULT } from './agent-mesh.js';-import { normalizeMeshEdits, normalizeMeshStack, MESH_EDIT_OPERATIONS, MAX_MESH_EDITS, STACK_OPERATIONS, MAX_STACK_NODES } from './mesh-recipe.js';+import { normalizeMeshEdits, normalizeMeshStack } from './mesh-recipe.js';+import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, RECIPE_ALPHA_MODES } from './agent-scene-capabilities.js';+export { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS };export { normalizeAgentLook, resolveAgentShadow } from './agent-look.js';export { needsMeshBooleans } from './agent-mesh.js';export { loadMeshBooleans, meshBooleansLoaded, setManifoldModuleLoader } from './mesh-boolean.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 DEFAULT_LIMITS = AGENT_SCENE_DEFAULT_LIMITS;const MAX_MESH_REPORTS = 16;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', 'geometry', 'material'];const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor', 'opacity', 'alphaMode', 'doubleSided'];-// Procedural recipes have no textures, so cutout masking has nothing to cut.-const RECIPE_ALPHA_MODES = ['opaque', 'blend'];const CAMERA_FIELDS = Object.keys(CAMERA_DEFAULTS);const LOOK_OPERATION_FIELDS = Object.freeze({'set-environment': 'environment',@@ -38,23 +34,6 @@ const REMOVAL_FIELDS = Object.freeze({'remove-material': 'materials',});-export const AGENT_SCENE_CAPABILITIES = Object.freeze({- format: '67js.scene', schemaVersion: 1,- geometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'mesh']),- meshEdits: Object.freeze({ operations: Object.freeze(Object.keys(MESH_EDIT_OPERATIONS)), maxEdits: MAX_MESH_EDITS }),- meshStack: Object.freeze({ operations: STACK_OPERATIONS, maxNodes: MAX_STACK_NODES }),- operations: Object.freeze([- 'set-node', 'set-material', 'set-camera', 'add-node', 'remove-node',- 'add-geometry', 'remove-geometry', 'add-material', 'remove-material',- 'set-environment', 'set-effects', 'set-shadow', 'set-motion', 'edit-mesh', 'set-mesh-stack',- ]),- materialTags: Object.freeze(['surface', 'unlit', 'liquid', 'foam']),- alphaModes: Object.freeze(RECIPE_ALPHA_MODES),- fixedResources: false, dynamicTopology: true, checkpoints: true, positiveScaleOnly: true,- authoredLook: true, maxPointLights: 8,- proceduralMotion: true,- motionLimits: Object.freeze({ maxTracks: 128, maxKeyframesPerTrack: 64, maxKeyframes: 2048, maxDuration: 30 }),-});function knownKeys(value, allowed, label) {if (!value || typeof value !== 'object' || Array.isArray(value)) {diff --git a/src/mesh-operations.js b/src/mesh-operations.jsnew file mode 100644index 00000000..2655cf99--- /dev/null+++ b/src/mesh-operations.js@@ -0,0 +1,25 @@+// The mesh edit vocabulary as plain data, with no geometry code, so capability listings and the MCP server can+// describe it without bundling the mesh engine.++export const MAX_MESH_EDITS = 64;++export const MESH_EDIT_OPERATIONS = Object.freeze({+ extrude_face_region: { fields: ['select', 'name', 'offset', 'direction', 'alongNormals'], tags: ['cap', 'side'] },+ extrude_individual: { fields: ['select', 'name', 'offset', 'direction'], tags: ['cap', 'side'] },+ inset_region: { fields: ['select', 'name', 'thickness', 'depth'], tags: ['cap', 'rim'] },+ inset_individual: { fields: ['select', 'name', 'thickness', 'depth'], tags: ['cap', 'rim'] },+ delete: { fields: ['select'], tags: [] },+ flip_normals: { fields: ['select'], tags: [] },+ translate: { fields: ['select', 'offset', 'falloff'], tags: [] },+ merge_by_distance: { fields: ['distance'], tags: [] },+ tag: { fields: ['select', 'name'], tags: [] },+ boolean: { fields: ['name', 'operation', 'cutter', 'translation', 'rotation', 'scale'], tags: ['cut'] },+ mirror: { fields: ['name', 'axis', 'merge'], tags: ['mirrored'] },+ array: { fields: ['name', 'count', 'offset', 'relativeOffset', 'merge'], tags: ['last'] },+ solidify: { fields: ['name', 'thickness', 'offset', 'evenThickness'], tags: ['inner', 'rim'] },+ bevel: { fields: ['name', 'edges', 'width', 'segments', 'profile', 'clampOverlap'], tags: ['strip', 'corner'] },+ loop_cut: { fields: ['name', 'edges', 'cuts', 'factor'], tags: ['band-<k>'] },+});++export const STACK_OPERATIONS = Object.freeze(['mirror', 'array', 'solidify', 'bevel']);+export const MAX_STACK_NODES = 16;diff --git a/src/mesh-recipe.js b/src/mesh-recipe.jsindex b9596336..09e2249d 100644--- a/src/mesh-recipe.js+++ b/src/mesh-recipe.js@@ -9,30 +9,14 @@ import { createMeshData } from './mesh-data.js';import { mirrorMesh, arrayMesh, solidifyMesh } from './mesh-stack.js';import { bevelEdges } from './mesh-bevel.js';import { loopCut } from './mesh-loopcut.js';+import { MESH_EDIT_OPERATIONS, MAX_MESH_EDITS, STACK_OPERATIONS, MAX_STACK_NODES } from './mesh-operations.js';+export { MESH_EDIT_OPERATIONS, MAX_MESH_EDITS, STACK_OPERATIONS, MAX_STACK_NODES };// Replayable edit log for agent recipes. Each edit is plain JSON; names follow Blender's bmesh.ops where they match.-export const MAX_MESH_EDITS = 64;const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,47}$/;const MAX_OFFSET = 1e6;-export const MESH_EDIT_OPERATIONS = Object.freeze({- extrude_face_region: { fields: ['select', 'name', 'offset', 'direction', 'alongNormals'], tags: ['cap', 'side'] },- extrude_individual: { fields: ['select', 'name', 'offset', 'direction'], tags: ['cap', 'side'] },- inset_region: { fields: ['select', 'name', 'thickness', 'depth'], tags: ['cap', 'rim'] },- inset_individual: { fields: ['select', 'name', 'thickness', 'depth'], tags: ['cap', 'rim'] },- delete: { fields: ['select'], tags: [] },- flip_normals: { fields: ['select'], tags: [] },- translate: { fields: ['select', 'offset', 'falloff'], tags: [] },- merge_by_distance: { fields: ['distance'], tags: [] },- tag: { fields: ['select', 'name'], tags: [] },- boolean: { fields: ['name', 'operation', 'cutter', 'translation', 'rotation', 'scale'], tags: ['cut'] },- mirror: { fields: ['name', 'axis', 'merge'], tags: ['mirrored'] },- array: { fields: ['name', 'count', 'offset', 'relativeOffset', 'merge'], tags: ['last'] },- solidify: { fields: ['name', 'thickness', 'offset', 'evenThickness'], tags: ['inner', 'rim'] },- bevel: { fields: ['name', 'edges', 'width', 'segments', 'profile', 'clampOverlap'], tags: ['strip', 'corner'] },- loop_cut: { fields: ['name', 'edges', 'cuts', 'factor'], tags: ['band-<k>'] },-});function editError(index, message) {return new TypeError(`Mesh edit ${index} (${message})`);@@ -347,8 +331,6 @@ export function applyMeshEdits(mesh, edits, { maxVertices = 250_000, maxFaces =return { mesh: current, results };}-export const STACK_OPERATIONS = Object.freeze(['mirror', 'array', 'solidify', 'bevel']);-export const MAX_STACK_NODES = 16;/** Validate a modifier stack: edits restricted to mirror, array and solidify, at most 16. */export function normalizeMeshStack(stack) {diff --git a/tests/agent-runtime.test.js b/tests/agent-runtime.test.jsindex dd851db6..6a124ad3 100644--- a/tests/agent-runtime.test.js+++ b/tests/agent-runtime.test.js@@ -5,7 +5,7 @@ import { readFile } from 'node:fs/promises';import { createServer } from 'node:http';import { randomUUID } from 'node:crypto';import { createContext, Script } from 'node:vm';-import { createAgentScene, AGENT_SCENE_CAPABILITIES } from '../src/agent-scene.js';+import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS } from '../src/agent-scene-capabilities.js';import { normalizeReview, REVIEW_LIMITS } from '../scripts/agent-review.mjs';test('runtime reports real scene capabilities without launching a browser and closes idempotently', async () => {@@ -94,8 +94,8 @@ async function reviewRuntimeHarness({ failShot, blockShot = false, oversize = faif (deadlineMs) source = source.replace('const EVALUATION_TIMEOUT_MS = 30000;', `const EVALUATION_TIMEOUT_MS = ${deadlineMs};`);const context = createContext({ createServer, randomUUID, existsSync: () => true,readFile: async () => '', packageMetadata: { version: 'test' },- createAgentScene: input => createAgentScene(JSON.parse(JSON.stringify(input))),- AGENT_SCENE_CAPABILITIES, normalizeReview, REVIEW_LIMITS,+ createRequire: () => ({ resolve: () => { throw new Error('no peer in tests'); } }),+ AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, normalizeReview, REVIEW_LIMITS,chromium: { launch: async () => browser }, URL, Buffer, process, performance, setTimeout, clearTimeout,});new Script(`${source}\nglobalThis.runtime = createAgentRuntime({ backend: 'cpu' });`).runInContext(context);diff --git a/tests/agent-scene.test.js b/tests/agent-scene.test.jsindex 6807c02c..7ce5ca12 100644--- a/tests/agent-scene.test.js+++ b/tests/agent-scene.test.js@@ -1,7 +1,16 @@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';+import { createAgentScene, AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS } from '../src/agent-scene.js';+import * as lightweightCapabilities from '../src/agent-scene-capabilities.js';++test('the plain-data capabilities module matches the scene engine', () => {+ const scene = createAgentScene({ format: '67js.scene', schemaVersion: 1, geometries: [], materials: [], nodes: [] });+ assert.deepEqual(scene.limits, lightweightCapabilities.AGENT_SCENE_DEFAULT_LIMITS);+ assert.equal(AGENT_SCENE_DEFAULT_LIMITS, lightweightCapabilities.AGENT_SCENE_DEFAULT_LIMITS);+ assert.equal(AGENT_SCENE_CAPABILITIES, lightweightCapabilities.AGENT_SCENE_CAPABILITIES);+ assert.equal(scene.capabilities, lightweightCapabilities.AGENT_SCENE_CAPABILITIES);+});function recipe() {return { format: '67js.scene', schemaVersion: 1,