Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Serve Manifold from the peer dependency to keep the package under 1 MiB

Nguyen Xuan Aned6c47adf1c5
diff --git a/.gitignore b/.gitignore
index c7848efc..06b70b72 100644
--- a/.gitignore
+++ b/.gitignore
@@ -15,6 +15,7 @@ public/export-glb.md
public/sculpt.md
public/surface.md
public/mesh-query.md
+public/mesh.md
public/primitives.md
public/shrinkwrap.md
public/spume.md
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 33920134..95504bee 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,7 +5,7 @@
- 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 result
-- Add mesh booleans (union, difference, intersect) through Manifold WebAssembly as the `boolean` edit with an inline primitive cutter, tag transfer and polygon rebuilding; `manifold-3d` is an optional peer dependency, embedded in the MCP preview
+- Add mesh booleans (union, difference, intersect) through Manifold WebAssembly as the `boolean` edit with an inline primitive cutter, tag transfer and polygon rebuilding; `manifold-3d` is an optional peer dependency, which the MCP runtime serves to its preview page when installed
- Add mirror, array and solidify as mesh edits and as a non-destructive modifier stack evaluated after the edits, with every prefix cached, and the `mesh_stack` MCP tool to set the stack or apply its first nodes into the edit log
- Report hollow cavities as valid in `lintMesh` instead of as inverted parts
- Add the `mesh_inspect` MCP tool: polygon counts, face sizes, parts, face tags, bounds and lint problems with suggested fixes for every recipe geometry
diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md
index c5981086..fdde476f 100644
--- a/THIRD-PARTY-NOTICES.md
+++ b/THIRD-PARTY-NOTICES.md
@@ -95,7 +95,7 @@ The mesh addon loads `manifold-3d` as a separate dependency for booleans.
Manifold is distributed under the Apache License, Version 2.0.
Its dependency package includes the complete license text.
Manifold's JavaScript and WASM code are not bundled into the 67.js library archive.
-The MCP browser preview bundle embeds them; its LICENSES.md carries the license.
+The MCP runtime serves them to its preview page from the installed peer dependency.
Source and license: https://github.com/elalish/manifold.
## Rapier 3D 0.21.0 (optional physics peer dependency)
diff --git a/docs/mesh.md b/docs/mesh.md
index 4970dfa9..1ce9692d 100644
--- a/docs/mesh.md
+++ b/docs/mesh.md
@@ -163,8 +163,11 @@ an inverted part.
Outside recipes, call `await loadMeshBooleans()` once, then `meshBoolean(mesh, cutter, operation, { cutTag })` or
`applyMeshEdits(mesh, edits, { resolveCutter })`. The library loads `manifold-3d` as an optional peer dependency,
-like Rapier for physics: install `[email protected]` to use booleans. The MCP preview bundle embeds it; its page
-allows WebAssembly compilation (`'wasm-unsafe-eval'`) and `data:` reads for the embedded binary, and nothing else.
+like Rapier for physics: install `[email protected]` next to `@codepawlhq/67js` to use booleans, in the library and
+in the MCP server alike. The MCP runtime serves Manifold's module and binary to its preview page from that
+installation, on the page's own origin; the page policy adds only WebAssembly compilation (`'wasm-unsafe-eval'`).
+Without the peer, a boolean edit fails with the install command and everything else keeps working. Keeping
+Manifold out of the package holds the npm archive under its 1 MiB budget.
Measured on this machine (Node 24, one thread): engine load 26–45 ms; cube minus a 32-sided cylinder 25–30 ms;
a 32,768-face sphere minus a box about 0.6 s including conversion and lint.
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index 30c4f698..52ac3c6e 100644
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@ -1,4 +1,4 @@
-import { createAgentScene, needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded } from '../src/agent-scene.js';
+import { createAgentScene, needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, setManifoldModuleLoader } from '../src/agent-scene.js';
import { Renderer67 } from '../src/renderer.js';
import { applyProjection } from '../src/camera.js';
import { mat4 } from 'gl-matrix';
@@ -167,6 +167,9 @@ function createPreview(scene, { sessionId, memoryBudgetMiB, backend }, asset) {
}
}
+// Manifold is an optional peer dependency; the runtime serves it from the host's node_modules on this origin.
+setManifoldModuleLoader(() => import(/* @vite-ignore */ new URL('/vendor/manifold.js', location.href).href));
+
// The boolean engine is WebAssembly and loads asynchronously, once. Calls that do not need it stay synchronous.
function afterMeshBooleans(value, run) {
if (meshBooleansLoaded() || !needsMeshBooleans(value)) return run();
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
index df31c290..9d64a340 100644
--- a/scripts/agent-runtime.mjs
+++ b/scripts/agent-runtime.mjs
@@ -3,6 +3,7 @@ import { randomUUID } from 'node:crypto';
import { existsSync } from 'node:fs';
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 { createAgentAssetCatalog } from './agent-asset-catalog.mjs';
@@ -18,6 +19,11 @@ const EVALUATION_TIMEOUT_MS = 30000;
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. */
+const MANIFOLD_FILES = Object.freeze({
+ '/vendor/manifold.js': { file: 'manifold.js', type: 'application/javascript; charset=utf-8' },
+ '/vendor/manifold.wasm': { file: 'manifold.wasm', type: 'application/wasm' },
+});
+
export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memory = 192, assets: assetRoot,
jobs: jobRoot, ffmpeg = 'ffmpeg',
previewUrl = new URL(/* @vite-ignore */ '../build/mcp/preview.js', import.meta.url) } = {}) {
@@ -106,6 +112,26 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo
}
}
+ // Mesh booleans load Manifold, an optional peer dependency, from the host's node_modules. Without it the page gets
+ // a 404 and the boolean edit reports the install command.
+ function serveManifoldFile({ file, type }, response) {
+ let path;
+ try {
+ path = createRequire(import.meta.url).resolve(`manifold-3d/${file}`);
+ } catch {
+ response.writeHead(404);
+ response.end();
+ return;
+ }
+ readFile(path).then(bytes => {
+ response.setHeader('Content-Type', type);
+ response.end(bytes);
+ }, () => {
+ response.writeHead(404);
+ response.end();
+ });
+ }
+
async function boot() {
if (page) {
return;
@@ -118,7 +144,12 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo
]);
httpServer = createServer((request, response) => {
response.setHeader('Cache-Control', 'no-store');
- response.setHeader('Content-Security-Policy', "default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'unsafe-inline'; img-src data: blob:; connect-src blob: data:");
+ response.setHeader('Content-Security-Policy', "default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'unsafe-inline'; img-src data: blob:; connect-src 'self' blob:");
+ const vendor = request.method === 'GET' ? MANIFOLD_FILES[request.url] : undefined;
+ if (vendor) {
+ serveManifoldFile(vendor, 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.mjs
index ee90de23..13287fbe 100644
--- a/scripts/build-mcp.mjs
+++ b/scripts/build-mcp.mjs
@@ -107,7 +107,8 @@ function singleModule(result, filename, browser) {
}
for (const specifier of chunk.dynamicImports) {
// Rolldown retains a self import to initialize inlined lazy modules without an extra chunk.
- if (specifier !== filename && (browser || (!isBuiltin(specifier) && specifier !== 'playwright-core'))) {
+ // manifold-3d is an optional peer dependency loaded on demand; the preview replaces this import at runtime.
+ if (specifier !== filename && specifier !== 'manifold-3d' && (browser || (!isBuiltin(specifier) && specifier !== 'playwright-core'))) {
throw new Error(`${filename} has an unexpected dynamic import: ${specifier}.`);
}
}
@@ -141,7 +142,7 @@ export async function buildMcp({ outDir = join(root, 'build', 'mcp') } = {}) {
...configuration.build,
target: 'es2022',
lib: { entry: join(root, 'scripts', 'agent-preview-browser.js'), formats: ['es'], fileName: () => 'preview.js' },
- rolldownOptions: { platform: 'browser', output: { codeSplitting: false, comments: { legal: true }, banner: legalBanner } },
+ rolldownOptions: { platform: 'browser', external: ['manifold-3d'], output: { codeSplitting: false, comments: { legal: true }, banner: legalBanner } },
},
}), 'preview.js', true);
const server = singleModule(await build({
@@ -153,7 +154,7 @@ export async function buildMcp({ outDir = join(root, 'build', 'mcp') } = {}) {
lib: { entry: join(root, 'scripts', 'mcp-server.mjs'), formats: ['es'], fileName: () => 'server.mjs' },
rolldownOptions: {
platform: 'node',
- external: specifier => isBuiltin(specifier) || specifier === 'playwright-core',
+ external: specifier => isBuiltin(specifier) || specifier === 'playwright-core' || specifier === 'manifold-3d',
output: { codeSplitting: false, comments: { legal: true }, banner: legalBanner },
},
},
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 15ab8534..a29d7c87 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -9,7 +9,7 @@ import { meshReport, generateMeshGeometry, MESH_SMOOTH_ANGLE_DEFAULT } from './a
import { normalizeMeshEdits, normalizeMeshStack, MESH_EDIT_OPERATIONS, MAX_MESH_EDITS, STACK_OPERATIONS, MAX_STACK_NODES } from './mesh-recipe.js';
export { normalizeAgentLook, resolveAgentShadow } from './agent-look.js';
export { needsMeshBooleans } from './agent-mesh.js';
-export { loadMeshBooleans, meshBooleansLoaded } from './mesh-boolean.js';
+export { loadMeshBooleans, meshBooleansLoaded, setManifoldModuleLoader } from './mesh-boolean.js';
const DEFAULT_LIMITS = Object.freeze({
maxNodes: 4096, maxDepth: 256, maxGeometries: 256, maxMaterials: 256,
diff --git a/src/mesh-boolean.js b/src/mesh-boolean.js
index 8977f193..7ea68e56 100644
--- a/src/mesh-boolean.js
+++ b/src/mesh-boolean.js
@@ -10,13 +10,20 @@ import { joinTriangles } from './mesh-convert.js';
let manifoldPromise = null;
let manifoldModule = null;
+let loadManifoldModule = () => import('manifold-3d');
+
+/** Replace how the Manifold module is imported, for hosts that serve it from elsewhere. Call before loading. */
+export function setManifoldModuleLoader(loader) {
+ if (typeof loader !== 'function') throw new TypeError('The Manifold loader must be a function returning a module promise.');
+ loadManifoldModule = loader;
+}
/**
* Load the boolean engine. In Node the binary is found next to the package; in a browser bundle pass the binary
* bytes as `wasmBinary` (an ArrayBuffer or Uint8Array). Safe to call repeatedly.
*/
export function loadMeshBooleans({ wasmBinary } = {}) {
- manifoldPromise ??= import('manifold-3d').catch(error => {
+ manifoldPromise ??= loadManifoldModule().catch(error => {
throw new Error(`Mesh booleans need the optional peer dependency manifold-3d 3.5.4: npm install [email protected] (${error.message}).`);
}).then(async ({ default: createModule }) => {
const module = await createModule(wasmBinary ? { wasmBinary } : undefined);
diff --git a/tests/agent-preview.test.js b/tests/agent-preview.test.js
index e6e48635..7f023f0c 100644
--- a/tests/agent-preview.test.js
+++ b/tests/agent-preview.test.js
@@ -65,6 +65,8 @@ function previewHarness() {
? frame => scene.sampleFrame(JSON.parse(JSON.stringify(frame))) : scene[field] });
},
needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded,
+ // The harness loads Manifold from node_modules directly, so the preview's served-file loader is ignored.
+ setManifoldModuleLoader: () => {},
parseGltf, Uint8Array, atob,
applyProjection, mat4, resolveAgentShadow,
Renderer67: FaultInjectedRenderer,