3D engine that AI agents drive
Share one set of glTF limits across the MCP asset catalog and name the limit in errors (closes #492)
Nguyen Xuan An60ef9f3b9ff0
diff --git a/changes/492.md b/changes/492.mdnew file mode 100644index 00000000..20efd616--- /dev/null+++ b/changes/492.md@@ -0,0 +1 @@+- The MCP asset catalog takes GLB files up to 64 MiB and 1,000,000 vertices (was 16 MiB and 250,000), and all its limits come from one module, `src/agent-asset-limits.js`, which the catalog, the runtime, the preview page and the render jobs share. A file over a limit fails with an error that names the limit and the value it hit. The limits stay below the `loadGltf` defaults because the file crosses one browser call as base64, which crashed the page from 80 MiB in a local Chrome test (#492).diff --git a/docs/agent-render-jobs.md b/docs/agent-render-jobs.mdindex ff20e5b5..fa3da323 100644--- a/docs/agent-render-jobs.md+++ b/docs/agent-render-jobs.md@@ -280,7 +280,7 @@ This conservative repair step prevents two recovery processes from deleting a ne| Combined output bytes per job | 128 MiB || PNG artifact bytes | 12 MiB each (a 1920x1080 frame) || Snapshot JSON | 1 MiB |-| Asset bytes | 16 MiB |+| Asset bytes | 64 MiB || Dimensions | 64 to 1920 pixels each, at most 1920x1080 pixels in all (1080x1920 fits) || Video frame rate | 1 to 30 fps || Duration | 0.1 to 60 seconds |diff --git a/docs/agent-scene.md b/docs/agent-scene.mdindex e888f278..0312bfd9 100644--- a/docs/agent-scene.md+++ b/docs/agent-scene.md@@ -204,7 +204,7 @@ and the geometry UVs.{ "id": "screen", "map": { "sequence": { "frames": ["<catalog image id>", "<catalog image id>"], "fps": 12 } } }```-- `frames` lists 2 to 64 IDs from `scene_asset_catalog`. The `--assets` folder takes PNG, JPEG and WebP files next to GLBs, with the same 16 MiB file budget, content-bound SHA-256 IDs and no links. An extension that does not match the file signature rejects the catalog. Entries report `kind: "image"` and `mimeType`; GLBs report `kind: "glb"`. No remote URLs are read.+- `frames` lists 2 to 64 IDs from `scene_asset_catalog`. The `--assets` folder takes PNG, JPEG and WebP files next to GLBs, with the same 64 MiB file budget, content-bound SHA-256 IDs and no links. An extension that does not match the file signature rejects the catalog. Entries report `kind: "image"` and `mimeType`; GLBs report `kind: "glb"`. No remote URLs are read.- All frames share one size, at most 1024 pixels a side, and a scene decodes at most 64 MiB of frames. Frames are read without colour conversion and should be opaque.- `fps` is above 0 and at most 60. The frame at scene time `t` is `floor(t * fps)`: wrapped around the list when `loop` is true (the default), held on the last frame when `loop` is false. Frame 0 shows before any motion time is set.- The clock is `motionTime`, the one `scene_look`, `scene_review` and `motion` use. A seek is deterministic: the same time gives the same frame and the same PNG bytes. `scene_render_submit` reads it from `settings.motion.start` plus the elapsed time (or a timeline shot), so a still or video frame shows the frame that `scene_look` shows at that time. A recipe with a sequence and no authored `motion` accepts `settings.motion`.diff --git a/docs/gltf.md b/docs/gltf.mdindex 09fa8eb8..5875eb3c 100644--- a/docs/gltf.md+++ b/docs/gltf.md@@ -48,7 +48,7 @@ Every numeric limit must be a positive safe integer.The defaults take one large exported scene, such as a 240 MB GLB with 8 million vertices and 8192 x 8192 textures, and `GLTF_CAPABILITIES.limits` holds them.A file over its limits fails with one `RangeError` that names each limit it goes over, the measured value and the value that fits, for example `glTF over its limits: vertices 9120000, over maxVertices 8000000; image 6 (6144x3072) pixels 18874368, over maxTextureImagePixels 16777216. Fix: pass { maxVertices: 9120000, maxTextureImagePixels: 18874368 }.`The file size and the decoded geometry and parts are checked as they are read, so they fail on their own.-The MCP server decodes catalog files with tighter limits: 16 MiB a file, 250,000 vertices (see [mcp.md](mcp.md)). A larger scene loads through `loadGltf` in code or split into parts; meshopt compression shrinks the file.+The MCP server decodes catalog files with tighter limits: 64 MiB a file, 1,000,000 vertices, 4,096 parts, 1,024 joints, 4,194,304 texture pixels (larger images are scaled down), 256 clips and 64 files, all from `src/agent-asset-limits.js`. The reason is the hand-off: the server reads the whole file, base64-encodes it and sends it to the preview page in one browser call. Measured with a local Chrome, a 64 MiB file crossed that call (a 128 MiB rise in server memory, 2.7 s), 72 MiB took 4.9 s, and 80 MiB and above crashed the page. A file over a limit fails with an error that names the limit and the value it hit. A larger scene loads through `loadGltf` in code, where the defaults above apply and the file never crosses that call; meshopt compression shrinks a file for the catalog. See [mcp.md](mcp.md).The importer rejects cyclic hierarchies, multiple parents, and hierarchies deeper than 256 levels.It checks PNG, JPEG and WebP dimensions before browser image decoding.Decoded accessor data has a separate ceiling of four times `maxBytes`.diff --git a/docs/mcp.md b/docs/mcp.mdindex de4ea000..1f884674 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -59,7 +59,7 @@ Using Node directly also avoids shell-specific npm launcher behavior in MCP clie`--memory` accepts an integer from 32 to 384 MiB and defaults to 192. A 1920x1080 frame needs about 175 MiB of render targets (measured, 4 samples), so the default fits an empty room at that size and 256 leaves room for textures; raise it for textured scenes.`--assets` selects an absolute directory containing self-contained GLB files.-The asset catalog reads regular files directly inside that directory, with limits of 64 files and 16 MiB per file.+The asset catalog reads regular files directly inside that directory, with limits of 64 files and 64 MiB per file. Decoding takes 1,000,000 vertices, 4,096 parts and 1,024 joints at most; `scene_capabilities` reports every number under `assets`. They are lower than the `loadGltf` defaults (256 MiB, 8,000,000 vertices) because the server hands the whole file to the preview page as one base64 string, which crashed the page from 80 MiB in a local Chrome test. A file over a limit fails with an error that names the limit and the value it hit; a larger scene loads through `loadGltf` in code (see [gltf.md](gltf.md)). All limits live in `src/agent-asset-limits.js`.Asset IDs bind file contents through SHA-256. Changed files require a runtime restart before they receive refreshed IDs.Catalog imports retain supported textures, skins, morphs and animation clips.The catalog takes self-contained GLB only. Poly Haven and similar sites ship a glTF folder (`.gltf`, `.bin` and textures): bundle it first with one command, then put the result in the catalog directory: `npx @gltf-transform/cli copy tree_01_1k.gltf tree_01.glb`. A recipe places a catalog asset with an `asset` node field (see [the scene guide](agent-scene.md#placed-catalog-assets)).diff --git a/public/llms.txt b/public/llms.txtindex 40fe4558..02fafd5f 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -157,7 +157,7 @@ Nearest projection can collapse vertices on coarse meshes. Preserve the error anVertex clearance does not certify whole-triangle clearance. Compatible static output can become a GPU morph target without repeating queries per frame.-GLB support loads transparent, double-sided and meshopt-compressed files. Unsupported features require visible errors. The MCP asset catalog takes 16 MiB and 250,000 vertices a file. A file with a skin or clips but no mesh loads with `parts: []` and works as a clip source (`motion.layers[].from`).+GLB support loads transparent, double-sided and meshopt-compressed files. Unsupported features require visible errors. The MCP asset catalog takes 64 MiB and 1,000,000 vertices a file (the library loadGltf takes 256 MiB and 8,000,000). A file with a skin or clips but no mesh loads with `parts: []` and works as a clip source (`motion.layers[].from`).Version `0.4.1` adds `addons/surface-attachment`. Read `docs/surface-attachment.md` before binding.Bind a triangle and barycentric coordinates once. Assign the retained attachment.matrix to the accessory.diff --git a/scripts/agent-asset-catalog.mjs b/scripts/agent-asset-catalog.mjsindex f8efd683..19b7fe20 100644--- a/scripts/agent-asset-catalog.mjs+++ b/scripts/agent-asset-catalog.mjs@@ -2,8 +2,10 @@ import { createHash } from 'node:crypto';import { open, readdir, realpath, lstat } from 'node:fs/promises';import { basename, isAbsolute, join, relative, sep } from 'node:path';-const MAXIMUM_ASSETS = 64;-const MAXIMUM_BYTES = 16 * 1024 * 1024;+import { AGENT_ASSET_LIMITS, assetBytesLimitMessage } from '../src/agent-asset-limits.js';++const MAXIMUM_ASSETS = AGENT_ASSET_LIMITS.maxAssets;+const MAXIMUM_BYTES = AGENT_ASSET_LIMITS.maxBytes;const IMAGE_EXTENSIONS = { png: /\.png$/i, jpeg: /\.jpe?g$/i, webp: /\.webp$/i };const IMAGE_MIME = { png: 'image/png', jpeg: 'image/jpeg', webp: 'image/webp' };@@ -66,8 +68,11 @@ export async function createAgentAssetCatalog(root) {const handle = await open(resolved, 'r');try {const current = await handle.stat();- if (!current.isFile() || current.dev !== original.dev || current.ino !== original.ino || current.size < 20 || current.size > MAXIMUM_BYTES) {- throw new Error('Asset changed during opening or exceeds the 16 MiB file budget.');+ if (current.isFile() && current.size > MAXIMUM_BYTES) {+ throw new RangeError(`${filename}: ${assetBytesLimitMessage(current.size)}`);+ }+ if (!current.isFile() || current.dev !== original.dev || current.ino !== original.ino || current.size < 20) {+ throw new Error('Asset changed during opening or is too small to be a GLB.');}const bytes = Buffer.alloc(current.size);let position = 0;@@ -93,7 +98,7 @@ export async function createAgentAssetCatalog(root) {const files = (await readdir(directory, { withFileTypes: true })).filter(entry => /\.(glb|png|jpe?g|webp)$/i.test(entry.name)).sort((left, right) => left.name.localeCompare(right.name));- if (files.length > MAXIMUM_ASSETS) throw new Error('Asset catalog exceeds the 64-file budget.');+ if (files.length > MAXIMUM_ASSETS) throw new RangeError(`Asset catalog has ${files.length} files, over its maxAssets ${MAXIMUM_ASSETS}. Remove files from the --assets directory.`);for (const file of files) {const { bytes, document, assetId, imageFormat } = await readFile(file.name);if (entries.has(assetId)) continue;@@ -125,7 +130,8 @@ export async function createAgentAssetCatalog(root) {if (!entry) throw new Error('Unknown asset ID. Read the configured asset catalog first.');const result = await readFile(entry.filename);if (result.assetId !== assetId) throw new Error('Asset bytes changed since catalog creation. Restart the runtime to refresh the catalog.');- if ((result.document?.animations?.length ?? 0) > 256) throw new Error('Asset exceeds the 256-clip decoding budget.');+ const clipCount = result.document?.animations?.length ?? 0;+ if (clipCount > AGENT_ASSET_LIMITS.maxClips) throw new RangeError(`Asset has ${clipCount} animation clips, over the catalog maxClips ${AGENT_ASSET_LIMITS.maxClips}. Remove clips from the file.`);return result.bytes;},});diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.jsindex 72037c4b..e16b7079 100644--- a/scripts/agent-preview-browser.js+++ b/scripts/agent-preview-browser.js@@ -25,6 +25,7 @@ import { weightTracksFromGltfAnimation } from '../src/export-skeleton.js';import { clipFromGltfAnimation } from '../src/skeleton-pose.js';import { sessionProblem } from '../src/agent-errors.js';import { BRANCH_LIMITS, createBranchStore, printableLabel } from '../src/agent-branches.js';+import { agentAssetDecodeOptions, withCatalogLimitAdvice } from '../src/agent-asset-limits.js';let active = null;let canvas = document.querySelector('canvas');@@ -49,7 +50,7 @@ function bytesFromBase64(data) {async function decodeMotionSources(encoded = {}) {const decoded = {};for (const [assetId, data] of Object.entries(encoded)) {- const source = await parseGltf(bytesFromBase64(data).buffer, { maxBytes: 16 * 1024 * 1024, maxVertices: 250000, maxParts: 4096, maxTexturePixels: 4194304, maxJoints: 1024 });+ const source = await parseCatalogAsset(bytesFromBase64(data).buffer);decoded[assetId] = { animations: source.animations, nodes: source.nodes };source.dispose();}@@ -411,7 +412,16 @@ setPhysicsModuleLoader(() => import(/* @vite-ignore */ new URL('/vendor/rapier.j// The preview bundle is one file, so the on-demand scene modules load together on the first call and later calls stay// synchronous. The boolean engine is WebAssembly and loads asynchronously, once, only for calls that need it.-const ASSET_DECODE_LIMITS = { maxBytes: 16 * 1024 * 1024, maxVertices: 250000, maxParts: 4096, maxTexturePixels: 4194304, maxJoints: 1024 };+const ASSET_DECODE_LIMITS = agentAssetDecodeOptions();++// An agent cannot pass loadGltf options, so a limit error names the catalog limits instead of "Fix: pass { ... }".+async function parseCatalogAsset(buffer) {+ try {+ return await parseGltf(buffer, ASSET_DECODE_LIMITS);+ } catch (error) {+ throw withCatalogLimitAdvice(error);+ }+}function disposePlacedAssets(pool) {for (const asset of pool?.values() ?? []) asset.dispose();@@ -426,7 +436,7 @@ async function loadPlacedAssets(pool, value, assetData) {const key = assetCopyKey(id, copy);if (pool.has(key)) continue;if (!assetData?.[id]) throw new Error(`Asset ${id.slice(0, 12)} was not supplied. Check asset_catalog for its id.`);- pool.set(key, await parseGltf(bytesFromBase64(assetData[id]).buffer, ASSET_DECODE_LIMITS));+ pool.set(key, await parseCatalogAsset(bytesFromBase64(assetData[id]).buffer));}}}@@ -823,7 +833,7 @@ window.__agentPreview = {try {// Labels, mesh reports and motion read the on-demand modules on any asset, not only one with mesh edits.await loadAllAgentSceneModules();- asset = await parseGltf(bytes.buffer, { maxBytes: 16 * 1024 * 1024, maxVertices: 250000, maxParts: 4096, maxTexturePixels: 4194304, maxJoints: 1024 });+ asset = await parseCatalogAsset(bytes.buffer);return createPreview(createAgentAssetScene(asset, input.recipe, { sources: await decodeMotionSources(input.sources) }), input, asset);} catch (error) {asset?.dispose();diff --git a/scripts/agent-render-jobs.mjs b/scripts/agent-render-jobs.mjsindex 6ed45a9c..6ec721a9 100644--- a/scripts/agent-render-jobs.mjs+++ b/scripts/agent-render-jobs.mjs@@ -6,6 +6,7 @@ import { RENDER_PASS_NAMES, VIDEO_ENCODERS, AUDIO_FILE_PATTERN, MAXIMUM_VIDEO_SEimport { recipeAssetNeeds } from '../src/agent-scene-assets.js';import { normalizeFilmTimeline, filmTimelineDuration } from '../src/film-timeline.js';import { OIDN_DEFAULT_SAMPLES, PATH_TRACER_DENOISERS, PATH_TRACER_JOB_LIMITS } from '../src/path-tracer-capabilities.js';+import { AGENT_ASSET_LIMITS, describeAssetBytes } from '../src/agent-asset-limits.js';const UUID =/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/;const STATES = ['queued', 'running', 'finalizing', 'completed', 'cancelling', 'cancelled', 'failed', 'interrupted'];@@ -32,7 +33,7 @@ export function jobDeadlineMs({ frameCount, width, height, renderer }, maximumMsreturn Math.min(maximumMs, Math.max(frameDeadline, traceDeadline));}const MAXIMUM_JSON_BYTES = 1024 ** 2;-const MAXIMUM_ASSET_BYTES = 16 * 1024 ** 2;+const MAXIMUM_ASSET_BYTES = AGENT_ASSET_LIMITS.maxBytes;/** Sibling folder of the job directories where the runtime keeps GLB exports; the store never reads or counts it. */export const EXPORT_DIRECTORY_NAME = 'exports';const STORE_FILES = ['store.json', 'store.lock', EXPORT_DIRECTORY_NAME];@@ -529,7 +530,7 @@ export async function createAgentRenderJobs({ root, run, limits: inputLimits = {if (!recipe || typeof recipe !== 'object' || Array.isArray(recipe)) throw new TypeError('Snapshot recipe must be a JSON object.');const snapshotMetadata = jsonCopy({ recipe, clips });const settings = settingsFrom(input.settings, clips, recipe);- if (input.snapshot.assetBytes !== undefined && (!Buffer.isBuffer(input.snapshot.assetBytes) || input.snapshot.assetBytes.length > MAXIMUM_ASSET_BYTES || !input.snapshot.assetBytes.length)) throw new RangeError('Asset snapshot must be a nonempty Buffer of at most 16 MiB.');+ if (input.snapshot.assetBytes !== undefined && (!Buffer.isBuffer(input.snapshot.assetBytes) || input.snapshot.assetBytes.length > MAXIMUM_ASSET_BYTES || !input.snapshot.assetBytes.length)) throw new RangeError(`Asset snapshot must be a nonempty Buffer of at most ${MAXIMUM_ASSET_BYTES} bytes (${describeAssetBytes(MAXIMUM_ASSET_BYTES)}).`);const snapshot = { recipe, clips, ...(input.snapshot.assetBytes ? { assetBytes: Buffer.from(input.snapshot.assetBytes) } : {}) };if (recipe.format === '67js.asset' && (!snapshot.assetBytes || createHash('sha256').update(snapshot.assetBytes).digest('hex') !== recipe.assetId)) throw new Error('Asset snapshot bytes must match the recipe SHA256 assetId.');const operation = (async () => {diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjsindex 2438e5c6..a48c9a95 100644--- a/scripts/agent-runtime.mjs+++ b/scripts/agent-runtime.mjs@@ -15,6 +15,7 @@ import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, RENDER_PASS_NAMESimport { PATH_TRACER_CAPABILITIES } from '../src/path-tracer-capabilities.js';import { chooseDenoiser, finishWithOidn } from './agent-path-trace-denoise.mjs';import { createAgentAssetCatalog } from './agent-asset-catalog.mjs';+import { AGENT_ASSET_LIMITS } from '../src/agent-asset-limits.js';import { recipeAssetNeeds } from '../src/agent-scene-assets.js';import { sequenceFrameIds } from '../src/agent-texture-sequence.js';import { TEXTURE_SEQUENCE_CAPABILITIES } from '../src/texture-sequence-limits.js';@@ -587,8 +588,9 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', browavailableIn: packageMetadata.version,assets: {configured: Boolean(assetRoot), formats: ['self-contained GLB', 'PNG, JPEG or WebP image (map sequence frame)'],- maximumBytes: 16 * 1024 * 1024, maximumAssets: 64,- maximumVertices: 250000, maximumParts: 4096, maximumTexturePixels: 4194304, maximumJoints: 1024, maximumClips: 256,+ maximumBytes: AGENT_ASSET_LIMITS.maxBytes, maximumAssets: AGENT_ASSET_LIMITS.maxAssets,+ maximumVertices: AGENT_ASSET_LIMITS.maxVertices, maximumParts: AGENT_ASSET_LIMITS.maxParts, maximumTexturePixels: AGENT_ASSET_LIMITS.maxTexturePixels,+ maximumJoints: AGENT_ASSET_LIMITS.maxJoints, maximumClips: AGENT_ASSET_LIMITS.maxClips,commands: ['set-root', 'set-asset-node', 'set-motion', 'set-animation', 'set-material', 'set-camera', 'set-environment', 'set-effects', 'set-shadow'],},jobs: { configured: Boolean(jobRoot), kinds: ['image', 'stills', 'video'], passes: RENDER_PASS_NAMES, pathTracer: PATH_TRACER_CAPABILITIES, maximumActiveJobs: 1,diff --git a/src/agent-asset-limits.js b/src/agent-asset-limits.jsnew file mode 100644index 00000000..efd4bb33--- /dev/null+++ b/src/agent-asset-limits.js@@ -0,0 +1,48 @@+// Limits for GLB files an agent imports through the MCP asset catalog. The catalog, the runtime, the preview page and the+// render jobs all read this one object, so the numbers cannot drift apart.+//+// These are tighter than the loadGltf defaults (256 MiB, 8,000,000 vertices) on purpose. The server reads the whole file,+// turns it into a base64 string and hands it to the preview page in one browser call. Measured with a local Chrome:+// 64 MiB and 72 MiB crossed that call (a rise of 128 and 264 MiB in server memory, in 2.7 s and 4.9 s), and 80 MiB and+// above crashed the page. 64 MiB keeps a margin under that ceiling. A scene beyond it loads through loadGltf in code, where the file never+// crosses that call.+export const AGENT_ASSET_LIMITS = Object.freeze({+ maxBytes: 64 * 1024 * 1024,+ maxAssets: 64,+ // About 32 bytes a vertex fills a 64 MiB file with 2,000,000; half of that keeps the decoded copy inside the preview memory budget.+ maxVertices: 1_000_000,+ maxParts: 4096,+ maxTexturePixels: 4_194_304,+ maxJoints: 1024,+ maxClips: 256,+});++const MEBIBYTE = 1024 * 1024;++/** The options `parseGltf` takes for a catalog file. */+export function agentAssetDecodeOptions() {+ const { maxBytes, maxVertices, maxParts, maxTexturePixels, maxJoints } = AGENT_ASSET_LIMITS;+ return { maxBytes, maxVertices, maxParts, maxTexturePixels, maxJoints };+}++/** "64 MiB" for byte limits, so a message and the docs read the same. */+export function describeAssetBytes(bytes) {+ return bytes % MEBIBYTE === 0 ? `${bytes / MEBIBYTE} MiB` : `${bytes} bytes`;+}++/** Message for a catalog file over its byte limit; it names the limit, the size it hit and the way out. */+export function assetBytesLimitMessage(size) {+ const limit = AGENT_ASSET_LIMITS.maxBytes;+ return `Asset is ${size} bytes, over the catalog maxBytes ${limit} (${describeAssetBytes(limit)}). Shrink it (meshopt compression, smaller textures) or split it into parts; a larger scene loads through loadGltf in code.`;+}++/**+ * parseGltf tells a code caller to "pass { maxVertices: n }", which an MCP agent cannot do. Swap that advice for the+ * catalog limits and the way out.+ */+export function withCatalogLimitAdvice(error) {+ if (!(error instanceof RangeError) || !/Fix: pass \{[^}]*\}\./.test(error.message)) return error;+ const { maxBytes, maxVertices, maxParts, maxJoints, maxTexturePixels } = AGENT_ASSET_LIMITS;+ const advice = `The MCP catalog limits are maxBytes ${maxBytes}, maxVertices ${maxVertices}, maxParts ${maxParts}, maxJoints ${maxJoints} and maxTexturePixels ${maxTexturePixels}, and an agent cannot raise them. Simplify the asset (fewer vertices, meshopt compression, smaller textures) or load it with loadGltf in code.`;+ return new RangeError(error.message.replace(/Fix: pass \{[^}]*\}\./, advice));+}diff --git a/tests/agent-asset-catalog.test.js b/tests/agent-asset-catalog.test.jsindex ee38eda6..04b9bba0 100644--- a/tests/agent-asset-catalog.test.js+++ b/tests/agent-asset-catalog.test.js@@ -1,12 +1,14 @@import test from 'node:test';import assert from 'node:assert/strict';-import { mkdtemp, writeFile, rm, symlink } from 'node:fs/promises';+import { mkdtemp, writeFile, rm, symlink, readdir, readFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join, dirname } from 'node:path';import { mat4 } from 'gl-matrix';import { box } from '../src/geometry.js';import { exportGlb } from '../src/export.js';import { createAgentAssetCatalog } from '../scripts/agent-asset-catalog.mjs';+import { AGENT_ASSET_LIMITS, agentAssetDecodeOptions, withCatalogLimitAdvice } from '../src/agent-asset-limits.js';+import { GLTF_CAPABILITIES, parseGltf } from '../src/gltf.js';async function fixture(context) {const directory = await mkdtemp(join(tmpdir(), '67js-catalog-'));@@ -65,8 +67,9 @@ test('catalog rejects external resources and malformed or over-budget GLBs beforconst { directory, bytes } = await fixture(context);await writeFile(join(directory, 'cube.glb'), withDocument(bytes, document => { document.buffers[0].uri = 'https://example.invalid/private'; }));await assert.rejects(createAgentAssetCatalog(directory), /embed all/);- await writeFile(join(directory, 'cube.glb'), Buffer.alloc(16 * 1024 * 1024 + 1));- await assert.rejects(createAgentAssetCatalog(directory), /16 MiB/);+ await writeFile(join(directory, 'cube.glb'), Buffer.alloc(AGENT_ASSET_LIMITS.maxBytes + 1));+ await assert.rejects(createAgentAssetCatalog(directory), error => error instanceof RangeError+ && error.message.includes('cube.glb: Asset is 67108865 bytes, over the catalog maxBytes 67108864 (64 MiB)'));await writeFile(join(directory, 'cube.glb'), Buffer.alloc(28));await assert.rejects(createAgentAssetCatalog(directory), /complete glTF/);});@@ -82,7 +85,7 @@ test('declared clip metadata stays bounded even when a GLB contains many animatiassert.equal(listing.assets[0].animations.length, 16);assert.equal(listing.assets[0].animationsTruncated, true);assert.ok(Buffer.byteLength(JSON.stringify(listing)) < 4096);- await assert.rejects(catalog.read(listing.assets[0].assetId), /256-clip/);+ await assert.rejects(catalog.read(listing.assets[0].assetId), /100000 animation clips, over the catalog maxClips 256/);});test('catalog rejects linked assets and requires an explicitly absolute directory', async context => {@@ -91,3 +94,36 @@ test('catalog rejects linked assets and requires an explicitly absolute directorawait symlink(join(directory, 'cube.glb'), join(directory, 'linked.glb'), 'file');await assert.rejects(createAgentAssetCatalog(directory), /without links/);});++test('the catalog limits are the documented values and never exceed the loadGltf defaults', () => {+ assert.deepEqual({ ...AGENT_ASSET_LIMITS }, {+ maxBytes: 64 * 1024 * 1024, maxAssets: 64, maxVertices: 1_000_000, maxParts: 4096,+ maxTexturePixels: 4_194_304, maxJoints: 1024, maxClips: 256,+ });+ const defaults = GLTF_CAPABILITIES.limits;+ for (const [name, value] of Object.entries(agentAssetDecodeOptions())) {+ assert.ok(value <= defaults[name], `${name} ${value} is above the loadGltf default ${defaults[name]}`);+ assert.equal(value, AGENT_ASSET_LIMITS[name]);+ }+});++test('no MCP script writes an asset limit as a literal number', async () => {+ const names = (await readdir(new URL('../scripts/', import.meta.url))).filter(name => /^agent-.*\.(mjs|js)$/.test(name));+ for (const name of names) {+ const source = await readFile(new URL(`../scripts/${name}`, import.meta.url), 'utf8');+ assert.doesNotMatch(source, /maxVertices: 250000|maximumVertices: 250000|MAXIMUM_ASSET_BYTES = 16|MAXIMUM_BYTES = 16/, name);+ }+});++test('a decode limit error names the catalog limit and the value the file hit, with no code-only advice', async context => {+ const { bytes } = await fixture(context);+ const tight = { ...agentAssetDecodeOptions(), maxVertices: 4 };+ const failure = await parseGltf(new Uint8Array(bytes).buffer, tight).then(() => null, error => error);+ assert.ok(failure instanceof RangeError);+ const advised = withCatalogLimitAdvice(failure);+ assert.match(advised.message, /vertices \d+, over maxVertices 4/);+ assert.match(advised.message, new RegExp(`MCP catalog limits are maxBytes ${AGENT_ASSET_LIMITS.maxBytes}, maxVertices ${AGENT_ASSET_LIMITS.maxVertices}`));+ assert.doesNotMatch(advised.message, /Fix: pass/);+ const other = new Error('unrelated');+ assert.equal(withCatalogLimitAdvice(other), other);+});diff --git a/tests/support/preview-harness.mjs b/tests/support/preview-harness.mjsindex c9497310..a095ea2b 100644--- a/tests/support/preview-harness.mjs+++ b/tests/support/preview-harness.mjs@@ -12,6 +12,7 @@ import { hasPatternTextures } from '../../scripts/agent-preview-textures.js';import { assetCopyKey, recipeAssetNeeds } from '../../src/agent-scene-assets.js';import { BRANCH_LIMITS, createBranchStore, printableLabel } from '../../src/agent-branches.js';import { sessionProblem } from '../../src/agent-errors.js';+import { agentAssetDecodeOptions, withCatalogLimitAdvice } from '../../src/agent-asset-limits.js';// Runs the preview page's adapter code in a VM with a fault-injected renderer, the way the MCP preview runs it in a browser.const source = (await readFile(new URL('../../scripts/agent-preview-browser.js', import.meta.url), 'utf8')).replace(/^import .+;\r?$/gm, '');@@ -76,7 +77,7 @@ export function previewHarness() {// The harness loads Manifold from node_modules directly, so the preview's served-file loader is ignored.setManifoldModuleLoader: () => {},needsPhysics, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader: () => {},- parseGltf, hasPatternTextures, Uint8Array, atob, sessionProblem, assetCopyKey, recipeAssetNeeds,+ parseGltf, hasPatternTextures, Uint8Array, atob, sessionProblem, assetCopyKey, recipeAssetNeeds, agentAssetDecodeOptions, withCatalogLimitAdvice,applyProjection, mat4, resolveAgentShadow, agentEnvironmentMap, BRANCH_LIMITS,// Line art needs a real renderer with render passes, so the fault-injected one gets a no-op install.agentSceneModule: name => (name === 'lineArt' ? { installLineArt: renderer => renderer } : name === 'userPass' ? { ...agentSceneModule(name), installUserPasses: renderer => renderer } : agentSceneModule(name)), agentSceneModuleLoaded, createBranchStore, printableLabel,