3D engine that AI agents drive
Share the package's engine chunks with the MCP preview page
Nguyen Xuan An23e60d0126b2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b12b7d71..3a49d041 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,7 @@## Unreleased+- Make room in the npm package (part of issue #36). The MCP preview page, `build/mcp/preview.js`, is now an entry of the library build and imports the engine chunks that the package entries already ship, instead of bundling its own copy of the engine. The archive drops from 904,975 to 666,214 bytes. `build/mcp/manifest.json` lists those chunks under `previewChunks` with their hashes, the MCP runtime serves them next to `preview.js`, and `bench/size/budgets.json` gains `archiveBytes`, which `npm run smoke:package` checks.- Add frustum culling, levels of detail and live adaptive resolution (part of issue #37). `Renderer67` tests each instance of a batch against the view frustum with the geometry's bounding sphere and draws only the visible ones (on by default, `culling: false` turns it off; skinned, morphed, swaying, fire, smoke, water, assembly and blended batches and the shadow passes are not culled). A part's `lods`, the array from `generateGeometryLods`, makes each instance pick a level by pixel error (`lodPixelError`, default 1). Selection is a pure function of the camera and the matrices, so a seek draws the same frame. `createGpuTimer` and `AdaptiveResolution` in `src/adaptive-quality.js` give live viewers GPU timing and a resolution scale with a minimum; an export can not build one, and `src/main.js` uses it only outside `export=1`. New `large-outdoor` scene in `bench/runtime` with ablations: 1.55 ms against 8.41 ms without culling and 6.0 ms for three.js on an RTX 3060, 517 ms against 4,428 ms and 944 ms on SwiftShader. Core grows 1,845 bytes gzip (budget 81,500). Recipes cannot declare `lods` yet. See `docs/culling-lod.md`.- Add relations between parts (part of issue #44, no new tool): a mesh node takes `relations` (`attach`, `gap`, `flush`, `align`, `centered`, up to 8) against other mesh nodes, or against the faces of one carrying a mesh tag (`region`). They work on world bounds, are solved after geometry exists and again on every `scene_apply`, so one edit to a body keeps the parts that sit against it. Unknown IDs and tags, two relations on one axis and cycles (a part waiting on its own child included) are rejected with the next action; solving is deterministic and independent of node order. The code loads on demand (`relations`). The schema carries only a generic `relations` list (597 bytes over `scene_create` and `scene_apply` together); the kinds and fields are in `scene_capabilities` `relations`, and the engine validates them. Measured on Sonnet (3 runs each), relations did not cut tool calls or errors: the kettle resize took 3.3 calls against 3.0, and a 12-part desk with three inspected resizes took 8 against 8, with 13% fewer output tokens (3,833 against 4,403) and the same cost and pass rate. The suite gains `kettle-resize`, `desk-resize` and their plain twins, and `touches` and `centreAt` checks.diff --git a/bench/size/README.md b/bench/size/README.mdindex 4a9725c6..5fbf898a 100644--- a/bench/size/README.md+++ b/bench/size/README.md@@ -37,6 +37,10 @@ Run `node scripts/measure-size.mjs --update-baseline` to record the new sizes, sUse `--set-budgets` to reset every budget to 2% over the current size. Use it after work that makes bundles smaller, so that the saving stays. A reset also hides any growth since the last reset, so check the diff.+## Package archive++`archiveBytes` in `budgets.json` caps the npm archive that `npm pack` makes. `npm run smoke:package` checks it, after `npm run prepare:release`. The archive was 904,975 bytes before the MCP preview shared the package's engine chunks and 666,214 after, so lower `archiveBytes` when work shrinks it.+## LimitsThe check reads gzip size only. It does not measure parse time, memory or runtime speed.diff --git a/bench/size/budgets.json b/bench/size/budgets.jsonindex ddfcd88e..3a3a8137 100644--- a/bench/size/budgets.json+++ b/bench/size/budgets.json@@ -1,4 +1,5 @@{+ "archiveBytes": 680000,"goals": {"lit-box": 50000,"gltf-box": 80000,diff --git a/docs/release-verification.md b/docs/release-verification.mdindex 82e96d2c..c58ca995 100644--- a/docs/release-verification.md+++ b/docs/release-verification.md@@ -1,5 +1,19 @@# Release verification+## Unreleased: preview shares the package chunks++The MCP preview page no longer bundles its own engine copy; it imports the chunks of the package build.+Source checks used Windows Node.js, installed Chrome and CPU SwiftShader. Registry publication was not checked.++| Check | Measured result |+| --- | --- |+| Archive | 904,975 bytes before, 666,214 after, so 382,362 bytes are free under 1 MiB. |+| Node tests | 1129 tests passed. |+| Clean source archive | `npm run smoke:package` passed. |+| Installed MCP CLI | `npm run smoke:mcp-package` (not protocol only) passed with a modern and a legacy client, and checked every `previewChunks` hash. |+| Real character | `npm run smoke:character` passed on the GPU. |+| First scene | Median of runtime launch, page load and first scene on SwiftShader: 981 ms before (7 runs), 974 ms after (11 runs). |+## 0.9.1This patch updates the packaged roadmap and standalone MCP command. Runtime behavior matches the verified `0.9.0` source below.diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjsindex cd7607fd..f4b82d59 100644--- a/scripts/agent-runtime.mjs+++ b/scripts/agent-runtime.mjs@@ -4,6 +4,7 @@ import { existsSync } from 'node:fs';import { lstat, mkdir, readFile, unlink, writeFile } from 'node:fs/promises';import { dirname, isAbsolute, join } from 'node:path';import { createRequire } from 'node:module';+import { fileURLToPath } from 'node:url';import packageMetadata from '../package.json' with { type: 'json' };import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, RENDER_PASS_NAMES, RENDER_PASS_DEPTH_RANGE } from '../src/agent-scene-capabilities.js';import { createAgentAssetCatalog } from './agent-asset-catalog.mjs';@@ -22,6 +23,8 @@ const MAXIMUM_QUEUED_CALLS = 16;const MAXIMUM_GLB_BYTES = 32 * 1024 * 1024;const MAXIMUM_KEPT_GLBS = 8;const EVALUATION_TIMEOUT_MS = 30000;+// The preview page imports engine chunks that sit beside the package entries, one folder above preview.js.+const ENGINE_CHUNK_URL = /^\/[\w.-]+\.js$/;const html = '<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#182126}canvas{display:block;width:100vw;height:100vh}</style></head><body><canvas></canvas><script type="module" src="/preview.js"></script></body></html>';/** Local, serialized browser preview. No browser is launched until scene creation. */@@ -135,6 +138,18 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo}}+ // The page shares engine chunks with the package entries, so it asks for them by name next to preview.js.+ function serveEngineChunk(url, response) {+ const chunkDirectory = fileURLToPath(new URL('../', previewUrl));+ readFile(join(chunkDirectory, url.slice(1))).then(bytes => {+ response.setHeader('Content-Type', 'application/javascript; charset=utf-8');+ response.end(bytes);+ }, () => {+ response.writeHead(404);+ response.end();+ });+ }+// Mesh booleans load Manifold and recipe physics loads Rapier, both optional peer dependencies, from the host's// node_modules. Without one the page gets a 404 and the edit reports the install command.function serveVendorFile({ resolve, type }, response) {@@ -178,6 +193,10 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memoserveVendorFile(vendor, response);return;}+ if (request.method === 'GET' && request.url !== '/preview.js' && ENGINE_CHUNK_URL.test(request.url)) {+ serveEngineChunk(request.url, response);+ return;+ }if (request.method !== 'GET' || !['/', '/preview.js'].includes(request.url)) {response.writeHead(404);response.end();diff --git a/scripts/build-mcp.mjs b/scripts/build-mcp.mjsindex f976bee0..5f4f741f 100644--- a/scripts/build-mcp.mjs+++ b/scripts/build-mcp.mjs@@ -6,6 +6,7 @@ import { constants, setPriority } from 'node:os';import { isBuiltin } from 'node:module';import { dirname, resolve, join, relative, isAbsolute } from 'node:path';import { fileURLToPath, pathToFileURL } from 'node:url';+import libraryConfiguration from '../vite.lib.config.js';const root = fileURLToPath(new URL('..', import.meta.url));@@ -94,27 +95,68 @@ async function collectLicenses(chunks) {return { text: `${[...notices, ...embeddedNotices].join('\n\n')}\n`, dependencies: records, embeddedDependencies: [...embedded.values()], licenseGaps: gaps };}-function singleModule(result, filename, browser) {+function singleModule(result, filename) {const outputs = (Array.isArray(result) ? result : [result]).flatMap(bundle => bundle.output);if (outputs.length !== 1 || outputs[0].type !== 'chunk' || !outputs[0].isEntry || outputs[0].fileName !== filename) {throw new Error(`${filename} must be exactly one self-contained entry module, without additional assets or chunks.`);}const chunk = outputs[0];for (const specifier of chunk.imports) {- if (browser || (!isBuiltin(specifier) && specifier !== 'playwright-core')) {+ if (!isBuiltin(specifier) && specifier !== 'playwright-core') {throw new Error(`${filename} has an unexpected external import: ${specifier}.`);}}for (const specifier of chunk.dynamicImports) {// Rolldown retains a self import to initialize inlined lazy modules without an extra chunk.- // manifold-3d is an optional peer dependency loaded on demand; the preview replaces this import at runtime.- if (specifier !== filename && specifier !== 'manifold-3d' && specifier !== '@dimforge/rapier3d-compat' && (browser || (!isBuiltin(specifier) && specifier !== 'playwright-core'))) {+ // manifold-3d is an optional peer dependency loaded on demand.+ if (specifier !== filename && specifier !== 'manifold-3d' && specifier !== '@dimforge/rapier3d-compat' && !isBuiltin(specifier) && specifier !== 'playwright-core') {throw new Error(`${filename} has an unexpected dynamic import: ${specifier}.`);}}return chunk;}+const PREVIEW_ENTRY_FILE = 'mcp/preview.js';++/**+ * The preview page is an entry of the library build, so it shares chunks with the package entries instead of+ * carrying its own copy of the engine. Rebuild the library in memory to learn which chunks the preview reaches,+ * then check them on disk, because the manifest and the license notices must cover exactly those files.+ */+async function reachablePreviewChunks(build, libraryDirectory) {+ const libraryResult = await build({+ ...libraryConfiguration,+ configFile: false,+ logLevel: 'silent',+ build: { ...libraryConfiguration.build, write: false, emptyOutDir: false },+ });+ const chunksByName = new Map();+ for (const bundle of Array.isArray(libraryResult) ? libraryResult : [libraryResult]) {+ for (const output of bundle.output) {+ if (output.type === 'chunk') chunksByName.set(output.fileName, output);+ }+ }+ const reached = new Map();+ const pending = [PREVIEW_ENTRY_FILE];+ while (pending.length) {+ const fileName = pending.pop();+ if (reached.has(fileName)) continue;+ const chunk = chunksByName.get(fileName);+ if (!chunk) continue;+ reached.set(fileName, chunk);+ pending.push(...chunk.imports, ...chunk.dynamicImports);+ }+ if (!reached.has(PREVIEW_ENTRY_FILE)) {+ throw new Error(`The library build has no ${PREVIEW_ENTRY_FILE} entry.`);+ }+ const chunks = [];+ for (const [fileName, chunk] of reached) {+ const bytes = await readFile(join(libraryDirectory, fileName));+ chunks.push({ fileName, chunk, bytes });+ }+ return chunks;+}+export async function buildMcp({ outDir = join(root, 'build', 'mcp') } = {}) {const destination = resolve(root, outDir);const offset = relative(root, destination);@@ -136,15 +178,7 @@ export async function buildMcp({ outDir = join(root, 'build', 'mcp') } = {}) {build: { write: false, copyPublicDir: false, emptyOutDir: false, outDir: destination, sourcemap: false, minify: true },};const legalBanner = '/*! 67js MCP bundle. Complete license texts and notices: ./LICENSES.md */';- const preview = singleModule(await build({- ...configuration,- build: {- ...configuration.build,- target: 'es2022',- lib: { entry: join(root, 'scripts', 'agent-preview-browser.js'), formats: ['es'], fileName: () => 'preview.js' },- rolldownOptions: { platform: 'browser', external: ['manifold-3d', '@dimforge/rapier3d-compat'], output: { codeSplitting: false, comments: { legal: true }, banner: legalBanner } },- },- }), 'preview.js', true);+ const previewChunks = await reachablePreviewChunks(build, join(root, 'build'));const server = singleModule(await build({...configuration,resolve: { conditions: ['node', 'import', 'default'], mainFields: ['main', 'module'] },@@ -158,7 +192,7 @@ export async function buildMcp({ outDir = join(root, 'build', 'mcp') } = {}) {output: { codeSplitting: false, comments: { legal: true }, banner: legalBanner },},},- }), 'server.mjs', false);+ }), 'server.mjs');// 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']) {@@ -169,8 +203,9 @@ export async function buildMcp({ outDir = join(root, 'build', 'mcp') } = {}) {if (!server.exports.includes('createAgentMcpServer') || !server.exports.includes('runMcpCli')) {throw new Error('Node bundle must export createAgentMcpServer and runMcpCli.');}- const licenses = await collectLicenses([preview, server]);- const files = new Map([['preview.js', preview.code], ['server.mjs', server.code], ['LICENSES.md', licenses.text]]);+ const licenses = await collectLicenses([...previewChunks.map(({ chunk }) => chunk), server]);+ const previewEntry = previewChunks.find(({ fileName }) => fileName === PREVIEW_ENTRY_FILE);+ const files = new Map([['preview.js', previewEntry.bytes], ['server.mjs', server.code], ['LICENSES.md', licenses.text]]);const outputs = [...files].map(([filename, text]) => {const bytes = Buffer.from(text);return { filename, bytes: bytes.length, sha256: digest(bytes) };@@ -188,6 +223,10 @@ export async function buildMcp({ outDir = join(root, 'build', 'mcp') } = {}) {embeddedDependencies: licenses.embeddedDependencies,licenseGaps: licenses.licenseGaps,outputs,+ previewChunks: previewChunks+ .filter(({ fileName }) => fileName !== PREVIEW_ENTRY_FILE)+ .map(({ fileName, bytes }) => ({ filename: fileName, bytes: bytes.length, sha256: digest(bytes) }))+ .sort((left, right) => left.filename.localeCompare(right.filename)),};await mkdir(destination, { recursive: true });for (const [filename, contents] of files) {diff --git a/scripts/smoke-mcp-package.mjs b/scripts/smoke-mcp-package.mjsindex 33398bb7..52abbcb7 100644--- a/scripts/smoke-mcp-package.mjs+++ b/scripts/smoke-mcp-package.mjs@@ -57,6 +57,14 @@ for (const output of manifest.outputs) {assert.equal(bytes.length, output.bytes);assert.equal(createHash('sha256').update(bytes).digest('hex'), output.sha256);}+// The preview page imports engine chunks shared with the package entries, so each one must ship and match.+assert.ok(manifest.previewChunks.length > 0, 'The manifest must list the engine chunks the preview imports.');+for (const chunk of manifest.previewChunks) {+ assert.ok(packed.files.some(file => file.path === `build/${chunk.filename}`), `Packed CLI must contain build/${chunk.filename}.`);+ const bytes = await readFile(join(installedRoot, 'build', chunk.filename));+ assert.equal(bytes.length, chunk.bytes);+ assert.equal(createHash('sha256').update(bytes).digest('hex'), chunk.sha256);+}const cli = join(installedRoot, 'bin', '67js-mcp.mjs');const version = spawnSync(process.execPath, [cli, '--version'], { cwd: consumer, encoding: 'utf8', windowsHide: true });assert.equal(version.status, 0, version.stderr);diff --git a/scripts/smoke-package.mjs b/scripts/smoke-package.mjsindex cc2f4b48..c28a37bf 100644--- a/scripts/smoke-package.mjs+++ b/scripts/smoke-package.mjs@@ -7,6 +7,7 @@ import { createHash } from 'node:crypto';const metadata = JSON.parse(await readFile('package.json', 'utf8'));const release = JSON.parse(await readFile('public/release.json', 'utf8'));+const sizeBudgets = JSON.parse(await readFile('bench/size/budgets.json', 'utf8'));const archive = resolve('public', release.tarball.slice(1));const binary = await readFile(archive);assert.equal(release.version, metadata.version);@@ -31,7 +32,7 @@ if (published) {const sourcePackResult = JSON.parse(sourcePack.stdout);const packedSource = Array.isArray(sourcePackResult) ? sourcePackResult[0] : sourcePackResult[metadata.name];assert.ok(packedSource?.filename, 'npm pack must return a source archive.');- assert.ok(packedSource.size < 1024 * 1024, 'The current source package must fit within a 1 MiB archive.');+ assert.ok(packedSource.size <= sizeBudgets.archiveBytes, `The current source package is ${packedSource.size} bytes, over its archive budget of ${sizeBudgets.archiveBytes} in bench/size/budgets.json.`);const sourceArchive = resolve(consumer, packedSource.filename);installTarget = `67js@file:${sourceArchive.replaceAll('\\', '/')}`;}diff --git a/vite.lib.config.js b/vite.lib.config.jsindex afba8f1b..60b3a0c6 100644--- a/vite.lib.config.js+++ b/vite.lib.config.js@@ -40,6 +40,8 @@ export default defineConfig({hdri: 'src/hdri.js','camera-effects': 'src/camera-effects.js','render-passes': 'src/render-passes.js',+ // Page of the MCP preview. It imports the engine chunks above instead of bundling its own copy.+ 'mcp/preview': 'scripts/agent-preview-browser.js',},formats: ['es'],fileName: (_, entry) => entry === 'core' ? '67.module.js' : `${entry}.js`,