3D engine that AI agents drive
Preserve imported GLB assets in agent authoring sessions
Nguyen Xuan An9a34a67fe04b
diff --git a/.gitignore b/.gitignoreindex e18fe901..d5d99b85 100644--- a/.gitignore+++ b/.gitignore@@ -38,3 +38,4 @@ public/surface-attachment.mdpublic/agent-scene.mdpublic/mcp.mdpublic/agent-look.md+public/agent-asset.mddiff --git a/README.md b/README.mdindex bead8329..6c9cee42 100644--- a/README.md+++ b/README.md@@ -130,10 +130,11 @@ Agents can add or remove nodes and shared resources in the same revisioned commaThe optional addon retains unchanged parts and geometry across supported edits.The source [MCP server](docs/mcp.md) connects these sessions to a persistent browser renderer.-Agents receive PNG previews and structured scene metadata through ten stdio tools.+Agents receive PNG previews and structured scene metadata through twelve stdio tools.Agents can author [lights, volumetric fog, grading and shadow coverage](docs/agent-look.md), then restore the complete look from a checkpoint.Run `node scripts/mcp-server.mjs --backend gpu --memory 192` from a checkout with project dependencies and a local Chrome installation.-Asset ingestion, animation authoring and persistent video jobs remain implementation work.+The [asset adapter](docs/agent-asset.md) imports catalog GLBs with supported textures, rigs, morphs and clips.+Animation track authoring, imported mesh topology edits and persistent video jobs remain implementation work.## Checks and performancediff --git a/ROADMAP.md b/ROADMAP.mdindex 0a1eb53f..8163ec12 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -23,10 +23,11 @@ This document separates shipping capabilities from work in progress. Performance## NextThe current source, after npm `0.4.1`, includes agent scenes with stable IDs, atomic resource/node edits and checkpoints.-Its stdio MCP server supplies ten schema-backed tools and persistent CPU/GPU image previews.+Its stdio MCP server supplies twelve schema-backed tools and persistent CPU/GPU image previews.Recipes retain lighting, volumetric fog, grading and directional shadow coverage with atomic edits and undo.+Imported asset sessions retain supported textures, rigs, morphs and clips from a configured local GLB catalog.-1. Extend agent sessions to ingest validated local assets with stable IDs, bounded allocation, replay and undo.+1. Extend imported asset sessions with node-level editing, topology changes and deformed geometry diagnostics.2. Extend MCP visual feedback with bounded multi-angle and absolute animation-time previews.3. Persistent render jobs with progress, cancellation, explicit CPU/GPU budgets and deterministic image and video export.4. Geometry, rig and asset diagnostics that help agents correct intersections, invalid transforms and unsupported materials.diff --git a/docs/agent-asset.md b/docs/agent-asset.mdnew file mode 100644index 00000000..f2cbe8bf--- /dev/null+++ b/docs/agent-asset.md@@ -0,0 +1,142 @@+# Imported asset authoring++`src/agent-asset.js` is an optional source module added after 0.4.1. It wraps one+decoded `parseGltf()` asset in a JSON authoring session. It preserves renderer+geometry, texture descriptors, skins, morph targets, and their typed arrays.+The module performs CPU validation and creates no GPU resources.++```js+import { parseGltf } from './src/gltf.js';+import { createAgentAssetScene } from './src/agent-asset.js';++const asset = await parseGltf(glbBytes);+const scene = createAgentAssetScene(asset, {+ format: '67js.asset',+ schemaVersion: 1,+ assetId: sha256Hex,+});+const checkpoint = scene.checkpoint();+scene.apply([+ { type: 'set-root', translation: [0, 1, 0] },+ { type: 'set-animation', clip: 0, time: 0.5 },+], { expectedRevision: scene.revision });+scene.restore(checkpoint, { expectedRevision: scene.revision });+scene.releaseCheckpoint(checkpoint);+```++## Recipe and IDs++The recipe requires `format: '67js.asset'`, `schemaVersion: 1`, and a 64-character+SHA256 hexadecimal `assetId`. The caller binds that digest to the decoded bytes.+This helper validates its spelling and retains it in lowercase. It does not+hash or fetch assets. Ordinary finite JSON is required: unknown keys, accessors,+sparse arrays, cycles, and non-JSON objects reject.++| Field | Default and meaning |+| --- | --- |+| `root.translation` | `[0,0,0]`, applied to all decoded world matrices |+| `root.rotation` | `[0,0,0,1]`, XYZW quaternion; nonzero input is normalized |+| `root.scale` | `[1,1,1]`, positive values representable at Float32 precision |+| `animation` | `null`, the pose captured when the session was created |+| `animation.clip` | Integer index into decoded animation clips |+| `animation.time` | Absolute seconds, from zero through that clip's duration |+| `materialOverrides` | `[]`, unique overrides keyed by `material-N` |+| `camera` | Automatically frames conservative authored base bounds when omitted |+| `environment`, `effects`, `shadow` | Complete defaults from [agent look](agent-look.md) |++The camera uses a 45-degree perspective lens, square aspect assumption, and+20% fit padding when generated. Its target follows the initial root and decoded+node pose. Skin deformation and morph displacement are excluded from that fit.+Later root or animation edits preserve the canonical camera. Use `set-camera`+to change the view. Explicit cameras use the same defaults and validation as+[agent scenes](agent-scene.md).++Parts receive stable IDs `mesh-0`, `mesh-1`, and so on in decoded order. Labels+remain display metadata. Geometry IDs identify shared decoded geometry.+Material IDs `material-0`, `material-1`, and so on identify unique decoded+material objects in first-use order. Overrides accept `color`, `metallic`,+`roughness`, `emission`, and `emissiveColor`, with the agent scene material+domains.++Other glTF material fields and texture descriptors retain their+decoded values. These commands do not edit alpha modes, maps, skin joints,+vertices, indices, mesh membership, or morph target definitions.++## Commands and transactions++`apply(operations, {expectedRevision})` requires 1 to 256 commands. The expected+revision must equal the current revision. Commands form one atomic transaction.+Invalid input, stale revision, invalid pose, or numeric overflow prevents publication.+The recipe, revision, material values, adapter matrices, and accessible decoded+pose arrays remain unchanged.++| Command | Fields |+| --- | --- |+| `set-root` | Optional flat `translation`, `rotation`, `scale` |+| `set-animation` | Optional `clip`, `time`; `clip:null` restores the captured pose |+| `set-material` | Existing `id` plus optional editable material fields |+| `set-camera` | Optional flat `eye`, `target`, `up`, `fov`, `near`, `far` |+| `set-environment` | `{environment: partial}` |+| `set-effects` | `{effects: partial}` |+| `set-shadow` | `{shadow: partial}` |++Animation seeks are absolute. Omitting time preserves time for the same clip.+Changing the clip defaults time to zero. With `clip:null`, omit time.++Environment+`volumeFog` and effects `bloom` merge partial nested records. A supplied+`pointLights` list replaces the full list, including `[]` to clear it.+Geometry and topology commands reject. Imported mesh editing or sculpting+through MCP is outside this module's contract.++`parts` is a frozen, stable list. Part objects, matrices, geometry, skin, morph,+and material wrapper identities survive every successful transaction. Material+factor getters read immutable snapshots. Map descriptors retain their original+references. `topologyRevision` remains zero. Renderer adapters can call their+ordinary update path after edits without replacing geometry resources.++`checkpoint()` returns an opaque private handle. At most eight handles can be+live. `restore(handle, {expectedRevision})` publishes its recipe and increments+revision. `releaseCheckpoint(handle)` frees the slot. Foreign and released+handles reject. Checkpoints contain recipe snapshots, sharing existing asset+resources rather than duplicating geometry or textures.++Recipes and operation+JSON are bounded to 1 MiB, with at most 64 nesting levels. Construction rejects+more than 4096 parts, 4096 unique materials, or 256 clips. Decoder resource+budgets still belong to `parseGltf()`. Configure them before decoding.++## Inspection and ownership++`exportRecipe()` and the camera/look getters return detached JSON.+`inspect({ids?, limit?, includeBounds?})` returns revision, fixed topology+revision, IDs, labels, counts, unique geometry bytes, animation metadata, and+at most 64 nodes by default. The limit can be 1 to 256. Bounds requests scan at+most two million authored base vertices across the selected visible nodes.++Returned bounds are explicitly labelled `authored-base-world`: actual base+positions transformed by the current root and decoded mesh node matrix. Skin+palettes and morph weights are preserved and validated for rendering, but+inspection does not evaluate their vertex deformation. Geometry bytes count+unique static typed arrays and morph delta arrays, excluding texture storage,+pose buffers, renderer allocations, and GPU timing.++The session requires exclusive ownership of the decoded asset's animation+state. Do not call its `applyAnimation()` separately or replace its parts,+matrices, palettes, or morph weights while the session is active. Returning to+`animation:null` restores captured public pose arrays. The decoder's private+animation mixer is not exposed. Subsequent seeks use its absolute pose API.+On failed staging, the adapter restores public arrays and, when available,+replays the preceding successful clip to recover mixer state.++Parts and resource arrays are privileged renderer handles under the existing+read-only geometry contract. External writes to geometry or texture data are+unsupported. Detached adapter matrices or replaced decoded pose buffers reject+before publication. The caller owns disposal: dispose the renderer first, then+call `asset.dispose()` once. The session does not dispose shared imported data.++Two designs were considered: rebuilding imported assets from authoring JSON,+and wrapping the decoder's retained resources. The retained adapter preserves+maps and deformation resources while keeping the JSON surface small. Its+fixed topology and honest base-bounds inspection make ownership and replay+explicit without claiming Blender feature parity.diff --git a/docs/guide.md b/docs/guide.mdindex 1e31f61d..943c33dc 100644--- a/docs/guide.md+++ b/docs/guide.md@@ -401,9 +401,10 @@ Disconnect observers, cancel animation frames, release pointer state and call `d## Models and AI agentsThe current source includes [agent scene sessions](/agent-scene.md), newer than npm `0.4.1`.-Its [MCP server](/mcp.md) provides ten tools for creating, inspecting, editing and previewing scenes through a persistent browser renderer.+Its [MCP server](/mcp.md) provides twelve tools for creating, inspecting, editing and previewing scenes through a persistent browser renderer.Read the matching checkout's MCP guide for launch configuration, CPU/GPU selection and source-only availability.The [agent look contract](/agent-look.md) adds retained lighting, volumetric fog, grading and directional shadows to recipe edits and checkpoints.+The [asset adapter](/agent-asset.md) imports local catalog GLBs with supported textures, rigs, morphs and deterministic clip sampling.The addon accepts JSON recipes with stable object IDs, shared geometry and material resources, hierarchy and a camera.Edits use an expected revision and commit as one batch. Checkpoints restore the supported scene state.diff --git a/docs/mcp.md b/docs/mcp.mdindex abe23c85..96e86c16 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -5,7 +5,7 @@ The published `0.4.1` package does not include this server.It uses the maintained MCP TypeScript SDK v2 server and a local browser runtime.The [official SDK documentation](https://ts.sdk.modelcontextprotocol.io/v2/) describes its transport and protocol APIs.-The server exposes ten tools for bounded JSON scene authoring.+The server exposes twelve tools for bounded JSON scene authoring and local GLB imports.It renders one active scene and returns PNG images through MCP image content.Tool results also contain JSON text and structured metadata.The image bytes appear only in the image content block.@@ -13,7 +13,7 @@ The image bytes appear only in the image content block.## Requirements and launchThe server requires Node.js 20 or later, installed project dependencies, and a local Chrome or Chromium executable.-The browser starts when `scene_create` runs.+The browser and its build dependencies load when `scene_create` or `scene_create_asset` runs.The runtime serves its generated scene page on the loopback interface.The MCP connection uses stdin and stdout, without an HTTP MCP listener.@@ -44,6 +44,12 @@ The MCP connection uses stdin and stdout, without an HTTP MCP listener.The browser path is optional when the runtime can locate a supported browser.`--backend` accepts `gpu` or `cpu` and defaults to `gpu`.`--memory` accepts an integer from 32 to 256 MiB and defaults to 192.++`--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.+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.+These launch options remain outside tool arguments.The process runs below normal priority to reduce interference with other work.@@ -81,6 +87,8 @@ Inspect or export the recipe before retrying. Context loss still permits recipe| --- | --- | --- || `scene_capabilities` | None | Features, limits, and backend information || `scene_create` | `recipe` | Session ID, revision, inspection, and render status |+| `scene_asset_catalog` | None | Configured catalog and content-bound GLB IDs |+| `scene_create_asset` | `recipe` using `67js.asset` | Imported scene ID, revision, inspection and render status || `scene_inspect` | `sessionId`, optional `ids`, `limit`, `includeBounds` | Compact node records and revision || `scene_apply` | `sessionId`, `expectedRevision`, `operations` | Updated revision, inspection, and render status || `scene_look` | `sessionId`, optional `width`, `height` | PNG image and metadata |@@ -157,7 +165,12 @@ Staging must fit alongside the current render allocations, so a replacement canThe committed revision and separate render failure remain visible in that case.Request a smaller `scene_look` to release large frame targets before retrying reconciliation.-The tools expose no arbitrary JavaScript execution, URLs, file access, asset ingestion, animation authoring, or render jobs.+The [asset scene contract](agent-asset.md) defines root transforms, material overrides and absolute clip/time samples.+Imported scenes retain their decoded topology. Mesh membership edits remain specific to procedural scenes.+Their bounds describe authored base vertices in the sampled world transforms, without claiming deformed skin or morph bounds.++The tools expose no arbitrary JavaScript execution, URLs, arbitrary file paths, animation track authoring or render jobs.+Embedded texture decoding uses private browser blob URLs. Remote asset requests remain blocked.The transport supplies a visual feedback loop, but visual quality still depends on the authored scene and image assessment.MCP support does not establish Blender feature parity.@@ -179,3 +192,6 @@ The scripts save images and metadata under `artifacts/`. They use one isolated bRun `node scripts/smoke-agent-topology.mjs` to inspect native GPU allocations during a shared-geometry addition and restoration.Its staging-budget failure must allocate no buffers and retain the previous rendered frame.Use `node scripts/smoke-agent-topology.mjs cpu` for software rendering. Both modes also verify recovery through a smaller CPU preview under a 32 MiB budget.++Run `node scripts/smoke-agent-assets.mjs` for actual imported WALL-E and textured rig previews through CPU stdio tools.+The script checks content IDs, root edits, retained texture decoding, reverse animation sampling and exact checkpoint restoration.diff --git a/package.json b/package.jsonindex b048aec6..00f174bc 100644--- a/package.json+++ b/package.json@@ -44,7 +44,8 @@"docs/surface-attachment.md","docs/agent-scene.md","docs/mcp.md",- "docs/agent-look.md"+ "docs/agent-look.md",+ "docs/agent-asset.md"],"main": "./build/67.module.js","module": "./build/67.module.js",@@ -64,6 +65,7 @@"./addons/surface-attachment": "./build/surface-attachment.js","./addons/physics": "./build/physics.js","./addons/agent-scene": "./build/agent-scene.js",+ "./addons/agent-asset": "./build/agent-asset.js","./package.json": "./package.json"},"scripts": {@@ -86,6 +88,7 @@"smoke:mcp": "node scripts/smoke-mcp.mjs","smoke:agent-topology": "node scripts/smoke-agent-topology.mjs","smoke:agent-look": "node scripts/smoke-agent-look.mjs",+ "smoke:agent-assets": "node scripts/smoke-agent-assets.mjs","smoke:enhancements": "node scripts/smoke-enhancements.mjs","smoke:site": "node scripts/smoke-site.mjs","publish:ci": "node scripts/publish-ci.mjs"diff --git a/public/llms.txt b/public/llms.txtindex 0ca89ea7..6794e16c 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -16,6 +16,11 @@ This addon does not expose an MCP server or a render job queue.The source checkout provides a separate stdio MCP server in `scripts/mcp-server.mjs`, after npm `0.4.1`.Read `/mcp.md` before configuring it. Start with `scene_capabilities`, create a recipe and inspect its stable IDs.+Read `/agent-asset.md` for source-only imported asset sessions and the `67js/addons/agent-asset` addon.+Configure --assets with an absolute GLB directory, then call scene_asset_catalog and scene_create_asset with a content-bound asset ID.+Imported scenes preserve supported maps, skins, morphs and clips. Their topology remains fixed.+Use set-root for asset placement and set-animation for absolute clip/time sampling. Checkpoint before sampling or relighting.+Read `/agent-look.md` for recipe environment, effects and shadow fields.Use `set-environment`, `set-effects` and `set-shadow` for atomic partial look patches.Nested volumeFog/bloom fields merge. pointLights replaces the list. Volume fog requires HDR/depth support.diff --git a/scripts/agent-asset-catalog.mjs b/scripts/agent-asset-catalog.mjsnew file mode 100644index 00000000..2fc87a20--- /dev/null+++ b/scripts/agent-asset-catalog.mjs@@ -0,0 +1,114 @@+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;++function selfContainedGlb(bytes) {+ if (bytes.length < 20 || bytes.readUInt32LE(0) !== 0x46546c67 || bytes.readUInt32LE(4) !== 2 || bytes.readUInt32LE(8) !== bytes.length) {+ throw new Error('Asset must be a complete glTF 2.0 binary file.');+ }+ const jsonLength = bytes.readUInt32LE(12);+ if (bytes.readUInt32LE(16) !== 0x4e4f534a || jsonLength % 4 !== 0 || jsonLength > bytes.length - 20) {+ throw new Error('GLB must start with a bounded JSON chunk.');+ }+ const document = JSON.parse(bytes.subarray(20, 20 + jsonLength).toString('utf8'));+ if (document.asset?.version !== '2.0') {+ throw new Error('Asset must declare glTF version 2.0.');+ }+ for (const collection of ['buffers', 'images']) {+ if (document[collection] !== undefined && !Array.isArray(document[collection])) {+ throw new Error(`GLB ${collection} must be an array.`);+ }+ for (const resource of document[collection] ?? []) {+ if (!resource || typeof resource !== 'object' || Object.hasOwn(resource, 'uri')) {+ throw new Error('Catalog GLBs must embed all buffers and images, without resource URIs.');+ }+ }+ }+ return document;+}++/** Explicit local directory catalog. IDs bind bytes, rather than agent-supplied file paths. */+export async function createAgentAssetCatalog(root) {+ if (typeof root !== 'string' || !isAbsolute(root)) {+ throw new TypeError('Asset root must be an explicit absolute directory path.');+ }+ const directory = await realpath(root);+ if (!(await lstat(directory)).isDirectory()) {+ throw new TypeError('Asset root must be a directory.');+ }+ const entries = new Map();++ async function readFile(filename) {+ const path = join(directory, filename);+ const original = await lstat(path);+ if (!original.isFile() || original.isSymbolicLink()) {+ throw new Error('Catalog assets must be regular files, without links.');+ }+ const resolved = await realpath(path);+ const offset = relative(directory, resolved);+ if (offset.startsWith(`..${sep}`) || offset === '..' || isAbsolute(offset) || basename(resolved) !== filename) {+ throw new Error('Asset must remain inside its configured directory.');+ }+ 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.');+ }+ const bytes = Buffer.alloc(current.size);+ let position = 0;+ while (position < bytes.length) {+ const result = await handle.read(bytes, position, bytes.length - position, position);+ if (result.bytesRead === 0) throw new Error('Asset was truncated during reading.');+ position += result.bytesRead;+ }+ const after = await handle.stat();+ if (after.size !== current.size || after.mtimeMs !== current.mtimeMs || after.ctimeMs !== current.ctimeMs) {+ throw new Error('Asset changed during reading.');+ }+ const document = selfContainedGlb(bytes);+ const assetId = createHash('sha256').update(bytes).digest('hex');+ return { bytes, document, assetId };+ } finally {+ await handle.close();+ }+ }++ const files = (await readdir(directory, { withFileTypes: true }))+ .filter(entry => /\.glb$/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.');+ for (const file of files) {+ const { bytes, document, assetId } = await readFile(file.name);+ if (entries.has(assetId)) continue;+ const animations = document.animations ?? [];+ if (!Array.isArray(animations)) throw new Error('GLB animations must be an array.');+ entries.set(assetId, {+ filename: file.name,+ metadata: Object.freeze({+ assetId, name: file.name, bytes: bytes.length,+ meshes: document.meshes?.length ?? 0,+ skins: document.skins?.length ?? 0,+ images: document.images?.length ?? 0,+ animationCount: animations.length,+ animationsTruncated: animations.length > 16,+ animations: animations.slice(0, 16).map((animation, index) => ({ index, name: String(animation?.name ?? `Clip ${index}`).slice(0, 80) })),+ }),+ });+ }+ return Object.freeze({+ list() {+ return { assets: structuredClone([...entries.values()].map(entry => entry.metadata)), maximumBytes: MAXIMUM_BYTES, maximumAssets: MAXIMUM_ASSETS };+ },+ async read(assetId) {+ const entry = entries.get(assetId);+ 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.');+ return result.bytes;+ },+ });+}diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.jsindex 55e1411f..1b459cca 100644--- a/scripts/agent-preview-browser.js+++ b/scripts/agent-preview-browser.js@@ -3,6 +3,8 @@ import { Renderer67 } from '../src/renderer.js';import { applyProjection } from '../src/camera.js';import { mat4 } from 'gl-matrix';import { resolveAgentShadow } from '../src/agent-look.js';+import { createAgentAssetScene } from '../src/agent-asset.js';+import { parseGltf } from '../src/gltf.js';let active = null;let canvas = document.querySelector('canvas');@@ -51,6 +53,9 @@ function renderInfo(renderer) {hdr: renderer.capabilities.hdr,depth: renderer.depth,geometryBuffers: renderer.geometryBuffers?.size ?? 0,+ materialTextures: renderer.textures ? [...renderer.textures.keys()].filter(Boolean).length : 0,+ skinTextures: renderer.skinTextures?.size ?? 0,+ morphTextures: renderer.morphTextures?.size ?? 0,gpuBuffers: renderer.buffers?.length ?? 0,drawBatches: renderer.batches?.length ?? 0,};@@ -115,41 +120,64 @@ function mutationStatus(record) {}}+function createPreview(scene, { sessionId, memoryBudgetMiB, backend }, asset) {+ if (active) {+ throw new Error('Dispose the current scene before creating another.');+ }+ validatePreviewCamera(scene.camera);+ let renderer;+ try {+ renderer = new Renderer67(canvas, scene.parts, {+ ground: false,+ hdr: true,+ depth: true,+ world: scene.environment.world,+ environment: scene.environment,+ shadowBounds: resolveAgentShadow(scene.shadow, scene.environment.lightDirection),+ pixelRatio: 1,+ samples: backend === 'cpu' ? 1 : 4,+ memoryBudgetMiB,+ });+ const record = { scene, renderer, asset, sessionId, checkpoints: new Map(), rendererTopology: scene.topologyRevision };+ draw(record);+ const result = status(record);+ if (backend === 'gpu' && /swiftshader|llvmpipe|software/i.test(result.render.graphics)) {+ throw new Error('Hardware GPU rendering was requested, but the browser selected a software renderer.');+ }+ active = record;+ return result;+ } catch (error) {+ renderer?.dispose();+ // A throwing constructor may already own GPU objects without returning an instance.+ canvas.getContext('webgl2')?.getExtension('WEBGL_lose_context')?.loseContext();+ const replacement = document.createElement('canvas');+ canvas.replaceWith(replacement);+ canvas = replacement;+ throw error;+ }+}+window.__agentPreview = {- create({ recipe, sessionId, memoryBudgetMiB, backend }) {- if (active) {- throw new Error('Dispose the current scene before creating another.');+ create(input) {+ if (active) throw new Error('Dispose the current scene before creating another.');+ return createPreview(createAgentScene(input.recipe), input);+ },+ async createAsset(input) {+ if (active) throw new Error('Dispose the current scene before creating another.');+ let bytes;+ if (typeof Uint8Array.fromBase64 === 'function') {+ bytes = Uint8Array.fromBase64(input.data);+ } else {+ const binary = atob(input.data);+ bytes = new Uint8Array(binary.length);+ for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);}- const scene = createAgentScene(recipe);- validatePreviewCamera(scene.camera);- let renderer;+ let asset;try {- renderer = new Renderer67(canvas, scene.parts, {- ground: false,- hdr: true,- depth: true,- world: scene.environment.world,- environment: scene.environment,- shadowBounds: resolveAgentShadow(scene.shadow, scene.environment.lightDirection),- pixelRatio: 1,- samples: backend === 'cpu' ? 1 : 4,- memoryBudgetMiB,- });- const record = { scene, renderer, sessionId, checkpoints: new Map(), rendererTopology: scene.topologyRevision };- draw(record);- const result = status(record);- if (backend === 'gpu' && /swiftshader|llvmpipe|software/i.test(result.render.graphics)) {- throw new Error('Hardware GPU rendering was requested, but the browser selected a software renderer.');- }- active = record;- return result;+ asset = await parseGltf(bytes.buffer, { maxBytes: 16 * 1024 * 1024, maxVertices: 250000, maxParts: 4096, maxTexturePixels: 4194304, maxJoints: 1024 });+ return createPreview(createAgentAssetScene(asset, input.recipe), input, asset);} catch (error) {- renderer?.dispose();- // A throwing constructor may already own GPU objects without returning an instance.- canvas.getContext('webgl2')?.getExtension('WEBGL_lose_context')?.loseContext();- const replacement = document.createElement('canvas');- canvas.replaceWith(replacement);- canvas = replacement;+ asset?.dispose();throw error;}},@@ -215,7 +243,11 @@ window.__agentPreview = {},dispose({ sessionId }) {const record = requireSession(sessionId);- record.renderer.dispose();+ try {+ record.renderer.dispose();+ } finally {+ record.asset?.dispose();+ }record.checkpoints.clear();active = null;return { sessionId, disposed: true };diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjsindex 290c9480..31a7a78c 100644--- a/scripts/agent-runtime.mjs+++ b/scripts/agent-runtime.mjs@@ -2,9 +2,9 @@ import { createServer } from 'node:http';import { randomUUID } from 'node:crypto';import { existsSync } from 'node:fs';import { fileURLToPath } from 'node:url';-import { build } from 'vite';-import { chromium } from 'playwright';+import { isAbsolute } from 'node:path';import { createAgentScene, AGENT_SCENE_CAPABILITIES } from '../src/agent-scene.js';+import { createAgentAssetCatalog } from './agent-asset-catalog.mjs';const EMPTY_RECIPE = { format: '67js.scene', schemaVersion: 1, geometries: [], materials: [], nodes: [] };const SCENE_LIMITS = createAgentScene(EMPTY_RECIPE).limits;@@ -14,7 +14,7 @@ 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. */-export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memory = 192 } = {}) {+export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memory = 192, assets: assetRoot } = {}) {if (!['gpu', 'cpu'].includes(backend)) {throw new RangeError('backend must be gpu or cpu.');}@@ -24,6 +24,9 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memoif (browserPath !== undefined && (typeof browserPath !== 'string' || !existsSync(browserPath))) {throw new Error('The configured browser executable does not exist.');}+ if (assetRoot !== undefined && (typeof assetRoot !== 'string' || !isAbsolute(assetRoot))) {+ throw new TypeError('Asset root must be an explicit absolute directory path.');+ }let phase = 'idle';let browserInstance;let httpServer;@@ -32,6 +35,12 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memolet queuedCalls = 0;let queue = Promise.resolve();let closing;+ let catalogPromise;+ function catalog() {+ if (!assetRoot) throw new Error('Configure --assets with an absolute directory before importing GLB assets.');+ catalogPromise ??= createAgentAssetCatalog(assetRoot);+ return catalogPromise;+ }function enqueue(task) {if (closing || phase === 'closing' || phase === 'closed' || phase === 'failed') {@@ -73,6 +82,10 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo}phase = 'starting';try {+ const [{ build }, { chromium }] = await Promise.all([+ import('vite'),+ import('playwright'),+ ]);const root = fileURLToPath(new URL('..', import.meta.url));const bundle = await build({root,@@ -91,7 +104,7 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memoconst code = outputs[0].code;httpServer = createServer((request, response) => {response.setHeader('Cache-Control', 'no-store');- response.setHeader('Content-Security-Policy', "default-src 'none'; script-src 'self'; style-src 'unsafe-inline'; img-src data:; connect-src 'none'");+ response.setHeader('Content-Security-Policy', "default-src 'none'; script-src 'self'; style-src 'unsafe-inline'; img-src data: blob:; connect-src blob:");if (request.method !== 'GET' || !['/', '/preview.js'].includes(request.url)) {response.writeHead(404);response.end();@@ -176,7 +189,13 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memopreview: { backend, memoryBudgetMiB: memory, maximumWidth: 1024, maximumHeight: 1024, maximumImageBytes: MAXIMUM_IMAGE_BYTES, maximumActiveScenes: 1, maximumQueuedCalls: MAXIMUM_QUEUED_CALLS, evaluationTimeoutMs: EVALUATION_TIMEOUT_MS },phase: closing && phase !== 'closed' ? 'closing' : phase,availableIn: 'source after npm 0.4.1',- unsupported: ['asset providers', 'arbitrary code execution', 'animation authoring', 'video jobs'],+ assets: {+ configured: Boolean(assetRoot), formats: ['self-contained GLB'],+ maximumBytes: 16 * 1024 * 1024, maximumAssets: 64,+ maximumVertices: 250000, maximumParts: 4096, maximumTexturePixels: 4194304, maximumJoints: 1024, maximumClips: 256,+ commands: ['set-root', 'set-animation', 'set-material', 'set-camera', 'set-environment', 'set-effects', 'set-shadow'],+ },+ unsupported: ['remote asset providers', 'arbitrary code execution', 'animation authoring', 'video jobs'],};},create({ recipe }) {@@ -191,6 +210,20 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memoreturn result;});},+ assetCatalog() {+ return enqueue(async () => assetRoot ? { configured: true, ...(await catalog()).list() } : { configured: false, assets: [] });+ },+ createAsset({ recipe }) {+ return enqueue(async () => {+ if (activeSessionId) throw new Error('Dispose the current scene before creating another.');+ const bytes = await (await catalog()).read(recipe.assetId);+ await boot();+ const sessionId = randomUUID();+ const result = await evaluate('createAsset', { recipe, data: bytes.toString('base64'), sessionId, memoryBudgetMiB: memory, backend });+ activeSessionId = sessionId;+ return result;+ });+ },inspect(input) {return enqueue(() => invoke('inspect', input));},diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex f1beee89..3a2daacd 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -116,6 +116,21 @@ const recipe = z.strictObject({effects: effects.optional(),shadow: shadow.optional(),}).describe('Bounded scene recipe. Backend validates references, mesh resource pairs, hierarchy, geometry budgets and camera consistency.');+const assetRecipe = z.strictObject({+ format: z.literal('67js.asset'),+ schemaVersion: z.literal(1),+ assetId: z.string().regex(/^[a-f0-9]{64}$/).describe('SHA-256 asset ID from scene_asset_catalog.'),+ camera: z.strictObject(cameraFields).optional(),+ environment: environment.optional(),+ effects: effects.optional(),+ shadow: shadow.optional(),+ root: z.strictObject({+ translation: vector3.optional(), rotation: quaternion.optional(),+ scale: z.tuple([positive, positive, positive]).optional(),+ }).optional(),+ 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(),+});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 }),@@ -123,6 +138,8 @@ const operation = z.discriminatedUnion('type', [z.strictObject({ type: z.literal('set-environment'), environment }),z.strictObject({ type: z.literal('set-effects'), effects }),z.strictObject({ type: z.literal('set-shadow'), shadow }),+ z.strictObject({ type: z.literal('set-root'), translation: vector3.optional(), rotation: quaternion.optional(), scale: z.tuple([positive, positive, positive]).optional() }),+ z.strictObject({ type: z.literal('set-animation'), clip: z.number().int().min(0).nullable().optional(), time: nonnegative.optional() }),z.strictObject({ type: z.literal('add-node'), node: nodeRecord }),z.strictObject({ type: z.literal('remove-node'), id: identifier, recursive: z.boolean().optional().describe('Remove descendants too. Defaults to false; dangling children reject the batch.') }),z.strictObject({ type: z.literal('add-geometry'), geometry }),@@ -142,7 +159,7 @@ function jsonResult(value) {export function createAgentMcpServer(runtime, { version = '0.4.1' } = {}) {const server = new McpServer({ name: '67js-scene', version }, {- instructions: 'Start with scene_capabilities, then scene_create and scene_inspect. Before editing, save a scene_checkpoint. Apply small batches with the current expectedRevision and check committed, revision and renderSucceeded. Add nodes and shared geometry/material resources through explicit commands; references must resolve in the final batch. Removing a parent requires recursive:true or removing/reparenting its children. A committed edit can have a separate renderError; do not retry it with an old revision. Use scene_look to judge the rendered image. Restore failed experiments or release unused checkpoints. Export the final recipe and dispose the scene when finished. No arbitrary JavaScript, URLs, files or jobs are exposed.',+ instructions: 'Start with scene_capabilities. Create a procedural recipe with scene_create, or select a configured GLB digest from scene_asset_catalog and use scene_create_asset. Inspect stable IDs and save a checkpoint before editing. Apply small batches with the current expectedRevision and check committed, revision and renderSucceeded. Procedural scenes support topology edits; imported assets preserve decoded meshes and support root, material, look and absolute clip sampling. A committed edit can have a separate renderError; do not retry it with an old revision. Use scene_look to judge the actual image. Restore experiments or release unused checkpoints. Export the final recipe and dispose the scene when finished. No arbitrary JavaScript, remote URLs, file paths or jobs are exposed.',});let closePromise;server.server.onclose = () => {@@ -164,8 +181,10 @@ export function createAgentMcpServer(runtime, { version = '0.4.1' } = {}) {}register('scene_capabilities', 'Read supported recipe features and runtime budgets before authoring. Does not launch a browser.', z.strictObject({}), readOnly, async () => jsonResult(await runtime.capabilities()));register('scene_create', 'Create the single active render scene from a JSON recipe. Dispose an existing scene first.', z.strictObject({ recipe }), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.create(argumentsValue)));+ register('scene_asset_catalog', 'List content-bound GLB IDs from the configured local asset directory. No arbitrary paths or downloads.', z.strictObject({}), readOnly, async () => jsonResult(await runtime.assetCatalog()));+ register('scene_create_asset', 'Create the active scene from a catalog GLB and editable asset recipe. Preserves supported maps, skins, morphs and clips. Dispose the existing scene first.', z.strictObject({ recipe: assetRecipe }), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.createAsset(argumentsValue)));register('scene_inspect', 'Read revision, counts and selected nodes. Bounds describe authored geometry rather than shader displacement.', z.strictObject({ ...sessionFields, ids: z.array(identifier).max(4096).optional().describe('Selected node IDs. Omit to inspect scene order.'), limit: z.number().int().min(1).max(4096).optional().describe('Maximum returned node records. Defaults to 64.'), includeBounds: z.boolean().optional().describe('Include world geometry bounds. Defaults to false.') }), readOnly, async argumentsValue => jsonResult(await runtime.inspect(argumentsValue)));- register('scene_apply', 'Atomically edit transforms, camera, materials or scene membership. Add immutable geometry and shared materials; remove unused resources explicitly. Successful batches increment revision once.', z.strictObject({ ...sessionFields, expectedRevision, operations: z.array(operation).min(1).max(256).describe('Set commands use flat fields; add commands contain node, geometry or material records. Final references and budgets validate before publication.') }), edit, async argumentsValue => jsonResult(await runtime.apply(argumentsValue)));+ register('scene_apply', 'Atomically edit transforms, look, camera or materials. Procedural scenes support membership commands. Imported assets support set-root and absolute set-animation sampling. Successful batches increment revision once.', z.strictObject({ ...sessionFields, expectedRevision, operations: z.array(operation).min(1).max(256).describe('Node/material/camera/root/animation commands use flat fields. Look patches and add commands contain nested records. Backend validates each scene mode before publication.') }), edit, async argumentsValue => jsonResult(await runtime.apply(argumentsValue)));register('scene_look', 'Render the active scene as a bounded PNG image for visual assessment.', z.strictObject({ ...sessionFields, width: z.number().int().min(64).max(1024).default(768).describe('PNG width in pixels.'), height: z.number().int().min(64).max(1024).default(512).describe('PNG height in pixels.') }), readOnly, async argumentsValue => {const { data, mimeType, metadata } = await runtime.look(argumentsValue);return { content: [{ type: 'image', data, mimeType }, { type: 'text', text: JSON.stringify(metadata) }], structuredContent: metadata };@@ -184,8 +203,8 @@ async function main() {for (let index = 0; index < argumentsValue.length; index += 2) {const name = argumentsValue[index];const value = argumentsValue[index + 1];- if (!['--backend', '--browser', '--memory'].includes(name) || value === undefined) {- throw new Error('Use --backend cpu|gpu, --browser <local executable path>, and --memory <32..256 MiB>.');+ if (!['--backend', '--browser', '--memory', '--assets'].includes(name) || value === undefined) {+ throw new Error('Use --backend cpu|gpu, --browser <local executable path>, --memory <32..256 MiB>, and --assets <absolute GLB directory>.');}options[name.slice(2)] = name === '--memory' ? Number(value) : value;}diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjsindex 913bc202..91d96e2b 100644--- a/scripts/prepare-release.mjs+++ b/scripts/prepare-release.mjs@@ -40,7 +40,7 @@ const sourceDocuments = ['gltf-morph.md', 'morph-targets.md', 'skinning.md', 'physics.md','export-glb.md', 'sculpt.md', 'surface.md', 'mesh-query.md', 'primitives.md', 'shrinkwrap.md','camera-path.md', 'lighting.md', 'volumetric.md', 'film-physics.md',- 'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md',+ 'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md', 'agent-asset.md',];for (const name of sourceDocuments) {await copyFile(resolve(root, 'docs', name), resolve(root, 'public', name));diff --git a/scripts/smoke-agent-assets.mjs b/scripts/smoke-agent-assets.mjsnew file mode 100644index 00000000..ce2f7679--- /dev/null+++ b/scripts/smoke-agent-assets.mjs@@ -0,0 +1,101 @@+import assert from 'node:assert/strict';+import { mkdir, readFile, writeFile } from 'node:fs/promises';+import { constants, setPriority } from 'node:os';+import { resolve } from 'node:path';+import { Client } from '@modelcontextprotocol/client';+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';+import { skinnedStripAsset } from '../tests/fixtures/skinned-strip.js';++setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+await mkdir('artifacts/asset-catalog-proof', { recursive: true });+await writeFile('artifacts/asset-catalog-proof/wall-e.glb', await readFile('public/wall-e.glb'));+const texturedDocument = JSON.parse(await readFile('tests/fixtures/textured-triangle.gltf', 'utf8'));+const image = Buffer.from(texturedDocument.images[0].uri.split(',')[1], 'base64');+const skinned = skinnedStripAsset((document, append) => {+ append(new Uint8Array(image), 'SCALAR');+ document.images = [{ bufferView: document.bufferViews.length - 1, mimeType: 'image/png' }];+ document.textures = [{ source: 0 }];+ document.materials[0].pbrMetallicRoughness.baseColorTexture = { index: 0 };+});+await writeFile('artifacts/asset-catalog-proof/textured-rig.glb', Buffer.from(skinned));+const transport = new StdioClientTransport({ command: process.execPath,+ args: [resolve('scripts/mcp-server.mjs'), '--backend', 'cpu', '--memory', '192', '--assets', resolve('artifacts/asset-catalog-proof')],+ stderr: 'pipe', cwd: process.cwd(),+});+let diagnostics = '';+transport.stderr.on('data', chunk => { diagnostics += chunk.toString(); });+const client = new Client({ name: '67js-asset-proof', version: '1' }, {+ versionNegotiation: { mode: { pin: '2026-07-28' }, probe: { timeoutMs: 180000 } },+});+async function call(name, argumentsValue = {}) {+ const timeout = name === 'scene_create_asset' ? 180000 : 60000;+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout });+ assert.equal(result.isError, undefined, result.content?.find(item => item.type === 'text')?.text);+ return result;+}+async function look(sessionId, label) {+ const result = await call('scene_look', { sessionId, width: 768, height: 512 });+ const bytes = Buffer.from(result.content.find(item => item.type === 'image').data, 'base64');+ await writeFile(`artifacts/agent-asset-${label}.png`, bytes);+ assert.match(result.structuredContent.graphics, /SwiftShader/);+ assert.ok(result.structuredContent.estimatedBytes < 192 * 1024 * 1024);+ return bytes;+}+try {+ await client.connect(transport, { timeout: 180000 });+ assert.equal((await client.listTools()).tools.length, 12);+ const catalog = (await call('scene_asset_catalog')).structuredContent;+ assert.equal(catalog.configured, true);+ assert.equal(catalog.assets.length, 2);+ const robot = catalog.assets.find(asset => asset.name === 'wall-e.glb');+ const created = (await call('scene_create_asset', { recipe: { format: '67js.asset', schemaVersion: 1, assetId: robot.assetId } })).structuredContent;+ const sessionId = created.sessionId;+ const before = await look(sessionId, 'wall-e-before');+ const checkpoint = (await call('scene_checkpoint', { sessionId })).structuredContent;+ const edited = (await call('scene_apply', { sessionId, expectedRevision: 0, operations: [+ { type: 'set-root', rotation: [0, Math.sin(0.3), 0, Math.cos(0.3)] },+ { type: 'set-environment', environment: { keyColor: [2.8, 3.5, 5], fillIntensity: 0.4 } },+ ] })).structuredContent;+ assert.equal(edited.renderSucceeded, true);+ const after = await look(sessionId, 'wall-e-after');+ assert.notDeepEqual(after, before);+ await call('scene_restore', { sessionId, checkpointId: checkpoint.checkpointId, expectedRevision: 1 });+ assert.deepEqual(await look(sessionId, 'wall-e-restored'), before);+ const exported = (await call('scene_export_recipe', { sessionId })).structuredContent;+ assert.equal(exported.recipe.assetId, robot.assetId);+ await call('scene_dispose', { sessionId });+ const rig = catalog.assets.find(asset => asset.name === 'textured-rig.glb');+ assert.equal(rig.skins, 1);+ assert.equal(rig.images, 1);+ assert.equal(rig.animations.length, 2);+ const rigCreated = (await call('scene_create_asset', { recipe: { format: '67js.asset', schemaVersion: 1, assetId: rig.assetId,+ camera: { eye: [1, 3, 7], target: [1, 3, 0], near: 0.1, far: 40, fov: 35 },+ } })).structuredContent;+ const rigId = rigCreated.sessionId;+ assert.equal(rigCreated.render.materialTextures, 1);+ assert.equal(rigCreated.render.skinTextures, 1);+ const initial = await look(rigId, 'rig-initial');+ const initialCheckpoint = (await call('scene_checkpoint', { sessionId: rigId })).structuredContent;+ const sampled = (await call('scene_apply', { sessionId: rigId, expectedRevision: 0, operations: [{ type: 'set-animation', clip: 0, time: 1.1 }] })).structuredContent;+ assert.equal(sampled.renderSucceeded, true);+ assert.equal(sampled.render.materialTextures, 1);+ assert.equal(sampled.render.skinTextures, 1);+ assert.equal(sampled.render.gpuBuffers, rigCreated.render.gpuBuffers);+ const bent = await look(rigId, 'rig-bent');+ assert.notDeepEqual(bent, initial);+ await call('scene_apply', { sessionId: rigId, expectedRevision: 1, operations: [{ type: 'set-animation', clip: 0, time: 0.4 }] });+ await call('scene_apply', { sessionId: rigId, expectedRevision: 2, operations: [{ type: 'set-animation', clip: 0, time: 1.1 }] });+ assert.deepEqual(await look(rigId, 'rig-repeated'), bent);+ await call('scene_restore', { sessionId: rigId, checkpointId: initialCheckpoint.checkpointId, expectedRevision: 3 });+ assert.deepEqual(await look(rigId, 'rig-restored'), initial);+ await call('scene_dispose', { sessionId: rigId });+ const report = { tools: 12, backend: 'cpu', robotParts: created.inspection.counts.parts,+ robotRestoreExact: true, texturedRigLoaded: true, backwardSeekExact: true, originalPoseRestoreExact: true };+ await writeFile('artifacts/agent-assets-cpu.json', JSON.stringify(report, null, 2));+ console.log(JSON.stringify(report));+} catch (error) {+ console.error(diagnostics);+ throw error;+} finally {+ await client.close();+}diff --git a/scripts/smoke-mcp.mjs b/scripts/smoke-mcp.mjsindex 9f929a66..2b2032da 100644--- a/scripts/smoke-mcp.mjs+++ b/scripts/smoke-mcp.mjs@@ -53,7 +53,7 @@ try {await client.connect(transport);processId = transport.pid;const listing = await client.listTools();- assert.equal(listing.tools.length, 10);+ assert.equal(listing.tools.length, 12);const capabilities = (await call('scene_capabilities')).structuredContent;assert.equal(capabilities.phase, 'idle');const fixture = createAgentPreviewFixture();diff --git a/scripts/smoke-package.mjs b/scripts/smoke-package.mjsindex d9a273e4..7531e25a 100644--- a/scripts/smoke-package.mjs+++ b/scripts/smoke-package.mjs@@ -168,6 +168,17 @@ if (${!published}) {agentScene.restore(lookCheckpoint, { expectedRevision: agentScene.revision });assert.deepEqual(agentScene.exportRecipe(), originalLook);agentScene.releaseCheckpoint(lookCheckpoint);+ const { createAgentAssetScene } = await import('67js/addons/agent-asset');+ const parsedAgentAsset = await parseGltf(exportGlb(agentScene.parts));+ const importedSession = createAgentAssetScene(parsedAgentAsset, { format: '67js.asset', schemaVersion: 1, assetId: '0'.repeat(64) });+ const importedPart = importedSession.parts[0];+ const importedCheckpoint = importedSession.checkpoint();+ importedSession.apply([{ type: 'set-root', translation: [1, 0, 0] }], { expectedRevision: 0 });+ assert.equal(importedSession.parts[0], importedPart);+ importedSession.restore(importedCheckpoint, { expectedRevision: 1 });+ assert.equal(importedSession.parts[0], importedPart);+ assert.equal(importedSession.exportRecipe().format, '67js.asset');+ parsedAgentAsset.dispose();}const parts = createModel();assert.equal(parts.length, 574);diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.mdindex 998e3f03..a5244b94 100644--- a/skills/build-67js-scene/references/scene-contract.md+++ b/skills/build-67js-scene/references/scene-contract.md@@ -150,7 +150,12 @@ Call `scene_capabilities`, create one JSON scene, inspect IDs, checkpoint, applyUse the revision returned by each committed apply or restore. A response with `committed: true` and `renderSucceeded: false` still advances revision.Inspect or export the canonical recipe after a render failure; do not retry the edit with its old revision.The server retains one renderer, bounds image dimensions and payloads, and closes its browser on stdio EOF.-Export the recipe before disposal. Asset ingestion, animation authoring and video jobs remain unsupported by these tools.+Export the recipe before disposal. Animation authoring and video jobs remain unsupported by these tools.+For imported models, read `docs/agent-asset.md`, configure `--assets` with an absolute local GLB directory, then select a digest from `scene_asset_catalog`.+Use `scene_create_asset` with a `67js.asset` recipe; supported texture maps, skinning, morphs and existing clips remain attached to decoded meshes.+Edit imported models through `set-root`, factor-only `set-material`, look commands and absolute `set-animation` sampling. Imported topology is immutable.+Use `{ type: 'set-animation', time }` to sample the current clip; `{ type: 'set-animation', clip: null }` restores the decoded pose.+Bounds describe authored base geometry, not the deformed skin/morph silhouette. Check the rendered PNG before accepting framing.Read `docs/agent-look.md` for authored lighting, fog, effects and shadow coverage, available after npm `0.4.1`.Use atomic `set-environment`, `set-effects` and `set-shadow` partial records instead of editing renderer internals through MCP.Nested volumeFog/bloom fields merge; pointLights replaces the full list. Point lights do not cast local shadows.diff --git a/src/agent-asset.js b/src/agent-asset.jsnew file mode 100644index 00000000..c13f6cb9--- /dev/null+++ b/src/agent-asset.js@@ -0,0 +1,685 @@+import { mat4, mat3 } from 'gl-matrix';+import { createAgentScene } from './agent-scene.js';+import { fitPerspectiveDistance } from './camera.js';+import { validateSkinGeometry, validateSkinPose } from './skinning.js';+import { validateMorphGeometry, validateMorphTransform } from './morph.js';++const MAX_RECIPE_BYTES = 1024 * 1024;+const MAX_CHECKPOINTS = 8;+const MAX_OPERATIONS = 256;+const MAX_INSPECTION_VERTICES = 2_000_000;+const ROOT_FIELDS = ['translation', 'rotation', 'scale'];+const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor'];+const LOOK_FIELDS = ['environment', 'effects', 'shadow'];+const LOOK_OPERATIONS = Object.freeze({+ 'set-environment': 'environment',+ 'set-effects': 'effects',+ 'set-shadow': 'shadow',+});++export const AGENT_ASSET_CAPABILITIES = Object.freeze({+ format: '67js.asset', schemaVersion: 1, fixedTopology: true,+ operations: Object.freeze([+ 'set-camera', 'set-environment', 'set-effects', 'set-shadow',+ 'set-root', 'set-animation', 'set-material',+ ]),+ boundsKind: 'authored-base-world',+});++function knownKeys(value, fields, label) {+ if (!value || typeof value !== 'object' || Array.isArray(value) ||+ (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)) {+ throw new TypeError(`${label} must be a plain JSON object.`);+ }+ for (const key of Object.keys(value)) {+ if (!fields.includes(key)) {+ throw new TypeError(`Unknown ${label} field: ${key}.`);+ }+ }+}++function copiedJson(input) {+ let bytes = 0;+ const ancestors = new Set();+ const encoder = new TextEncoder();+ function charge(count) {+ bytes += count;+ if (bytes > MAX_RECIPE_BYTES) {+ throw new RangeError('Asset recipe JSON exceeds 1 MiB. Reduce the input.');+ }+ }+ function copy(value, depth) {+ if (depth > 64) {+ throw new RangeError('Asset recipe JSON nesting exceeds 64 levels.');+ }+ if (value === null || typeof value === 'boolean') {+ charge(value === null ? 4 : String(value).length);+ return value;+ }+ if (typeof value === 'number' && Number.isFinite(value) && Number.isFinite(Math.fround(value))) {+ charge(String(value).length);+ return value;+ }+ if (typeof value === 'string') {+ if (value.length > MAX_RECIPE_BYTES) {+ throw new RangeError('Asset recipe JSON exceeds 1 MiB.');+ }+ charge(encoder.encode(JSON.stringify(value)).length);+ return value;+ }+ if (!value || typeof value !== 'object' || ancestors.has(value)) {+ throw new TypeError('Asset recipe requires finite, acyclic JSON data.');+ }+ const array = Array.isArray(value);+ if (array && (value.length > MAX_RECIPE_BYTES || Object.getPrototypeOf(value) !== Array.prototype)) {+ throw new TypeError('Asset recipe arrays must be ordinary bounded JSON arrays.');+ }+ if (!array && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {+ throw new TypeError('Asset recipe objects must be plain JSON objects.');+ }+ ancestors.add(value);+ charge(2);+ const result = array ? [] : {};+ for (const key of Reflect.ownKeys(value)) {+ if (array && key === 'length') {+ continue;+ }+ if (typeof key !== 'string' || key === '__proto__') {+ throw new TypeError('Invalid asset recipe JSON key.');+ }+ const descriptor = Object.getOwnPropertyDescriptor(value, key);+ if (!descriptor.enumerable || !Object.hasOwn(descriptor, 'value')) {+ throw new TypeError('Asset recipe accessors and hidden fields are unsupported.');+ }+ if (array && key !== String(result.length)) {+ throw new TypeError('Asset recipe arrays must be dense without extra fields.');+ }+ charge(array ? 1 : encoder.encode(JSON.stringify(key)).length + 2);+ result[key] = copy(descriptor.value, depth + 1);+ }+ if (array && result.length !== value.length) {+ throw new TypeError('Asset recipe arrays cannot contain trailing holes.');+ }+ ancestors.delete(value);+ return result;+ }+ const result = copy(input, 0);+ if (encoder.encode(JSON.stringify(result)).length > MAX_RECIPE_BYTES) {+ throw new RangeError('Asset recipe JSON exceeds 1 MiB.');+ }+ return result;+}++function vector(value, length, label) {+ if (!Array.isArray(value) || value.length !== length ||+ !value.every(component => typeof component === 'number' && Number.isFinite(Math.fround(component)))) {+ throw new TypeError(`${label} requires ${length} finite Float32 numbers.`);+ }+ return [...value];+}++function rootFrom(input = {}) {+ knownKeys(input, ROOT_FIELDS, 'root');+ const root = {+ translation: vector(input.translation === undefined ? [0, 0, 0] : input.translation, 3, 'root translation'),+ rotation: vector(input.rotation === undefined ? [0, 0, 0, 1] : input.rotation, 4, 'root rotation'),+ scale: vector(input.scale === undefined ? [1, 1, 1] : input.scale, 3, 'root scale'),+ };+ const rotationLength = Math.hypot(...root.rotation);+ if (rotationLength === 0 || root.scale.some(component => Math.fround(component) <= 0)) {+ throw new RangeError('Root needs a nonzero quaternion and positive Float32 scales.');+ }+ root.rotation = root.rotation.map(component => component / rotationLength);+ return root;+}++function viewRecipe(input, materials = []) {+ const recipe = { format: '67js.scene', schemaVersion: 1, geometries: [], materials, nodes: [] };+ for (const field of ['camera', ...LOOK_FIELDS]) {+ if (Object.hasOwn(input, field)) {+ recipe[field] = input[field];+ }+ }+ return createAgentScene(recipe, { maxMaterials: Math.max(256, materials.length) }).exportRecipe();+}++function poseBuffers(sourceParts) {+ const buffers = new Set();+ for (const part of sourceParts) {+ buffers.add(part.matrix);+ if (part.skin) {+ buffers.add(part.skin.jointMatrices);+ if (part.skin.jointWorldMatrices) {+ buffers.add(part.skin.jointWorldMatrices);+ }+ }+ if (part.morph) {+ buffers.add(part.morph.weights);+ }+ }+ return [...buffers].map(array => ({ array, length: array.length }));+}++function snapshotPose(buffers) {+ return buffers.map(({ array, length }) => {+ if (!(array instanceof Float32Array) || array.length !== length || array.byteLength !== length * 4) {+ throw new RangeError('Decoded pose buffers must retain their identities and must not detach.');+ }+ return { array, values: new Float32Array(array) };+ });+}++function restorePose(snapshot) {+ for (const { array, values } of snapshot) {+ Float32Array.prototype.set.call(array, values);+ }+}++function geometryMaxima(geometry) {+ const maximum = [0, 0, 0];+ for (let offset = 0; offset < geometry.positions.length; offset += 3) {+ for (let axis = 0; axis < 3; axis++) {+ maximum[axis] = Math.max(maximum[axis], Math.abs(geometry.positions[offset + axis]));+ }+ }+ return maximum;+}++function localBounds(geometry) {+ const minimum = [Infinity, Infinity, Infinity];+ const maximum = [-Infinity, -Infinity, -Infinity];+ for (let offset = 0; offset < geometry.positions.length; offset += 3) {+ for (let axis = 0; axis < 3; axis++) {+ minimum[axis] = Math.min(minimum[axis], geometry.positions[offset + axis]);+ maximum[axis] = Math.max(maximum[axis], geometry.positions[offset + axis]);+ }+ }+ return { min: minimum, max: maximum };+}++function framingBounds(records, matrices) {+ const minimum = [Infinity, Infinity, Infinity];+ const maximum = [-Infinity, -Infinity, -Infinity];+ for (let index = 0; index < records.length; index++) {+ const bounds = records[index].geometry.bounds;+ const matrix = matrices[index];+ for (let corner = 0; corner < 8; corner++) {+ const point = bounds.min.map((component, axis) => corner & (1 << axis) ? bounds.max[axis] : component);+ for (let axis = 0; axis < 3; axis++) {+ const value = matrix[axis] * point[0] + matrix[axis + 4] * point[1] ++ matrix[axis + 8] * point[2] + matrix[axis + 12];+ minimum[axis] = Math.min(minimum[axis], value);+ maximum[axis] = Math.max(maximum[axis], value);+ }+ }+ }+ return { min: minimum, max: maximum };+}++function validatePositionBounds(maxima, world, skin) {+ for (let row = 0; row < 4; row++) {+ let coordinateBound = 0;+ for (let column = 0; column < 4; column++) {+ let coefficient = Math.abs(world[column * 4 + row]);+ if (skin) {+ coefficient = 0;+ for (let axis = 0; axis < 4; axis++) {+ let paletteBound = 0;+ for (let offset = column * 4 + axis; offset < skin.jointMatrices.length; offset += 16) {+ paletteBound = Math.max(paletteBound, Math.abs(skin.jointMatrices[offset]));+ }+ coefficient += Math.abs(world[axis * 4 + row]) * paletteBound * (1 + 2 ** -21);+ if (!Number.isFinite(Math.fround(coefficient))) {+ throw new RangeError('Asset world/skin matrix products exceed Float32 range.');+ }+ }+ }+ coordinateBound += coefficient * (column === 3 ? 1 : maxima[column]);+ if (!Number.isFinite(Math.fround(coordinateBound))) {+ throw new RangeError('Asset world geometry bounds exceed Float32 range.');+ }+ }+ }+}++function baseBounds(records, matrices) {+ const minimum = [Infinity, Infinity, Infinity];+ const maximum = [-Infinity, -Infinity, -Infinity];+ for (let index = 0; index < records.length; index++) {+ const positions = records[index].source.geometry.positions;+ const matrix = matrices[index];+ for (let offset = 0; offset < positions.length; offset += 3) {+ for (let axis = 0; axis < 3; axis++) {+ const value = matrix[axis] * positions[offset] + matrix[4 + axis] * positions[offset + 1] ++ matrix[8 + axis] * positions[offset + 2] + matrix[12 + axis];+ minimum[axis] = Math.min(minimum[axis], value);+ maximum[axis] = Math.max(maximum[axis], value);+ }+ }+ }+ return { min: minimum, max: maximum };+}++function framedCamera(bounds) {+ const target = bounds.min.map((component, axis) => (component + bounds.max[axis]) / 2);+ const radius = Math.hypot(...bounds.max.map((component, axis) => (component - bounds.min[axis]) / 2));+ const near = Math.max(0.001, radius * 0.001);+ const far = Math.max(10, radius * 10);+ const probeDistance = Math.max(1, radius);+ const directionLength = Math.hypot(4, 3, 5);+ const direction = [4, 3, 5].map(component => component / directionLength);+ const camera = {+ target, eye: target.map((component, axis) => component + direction[axis] * probeDistance),+ up: [0, 1, 0], fov: 45, near, far,+ };+ const distance = fitPerspectiveDistance({ minimum: bounds.min, maximum: bounds.max }, camera, 1, 1.2);+ camera.eye = target.map((component, axis) => component + direction[axis] * distance);+ return camera;+}++/** Own authoring state around one exclusively owned, decoded parseGltf asset. */+export function createAgentAssetScene(asset, inputRecipe) {+ if (!asset || !Array.isArray(asset.parts) || !asset.parts.length || !Array.isArray(asset.animations) ||+ typeof asset.applyAnimation !== 'function') {+ throw new TypeError('createAgentAssetScene requires a decoded parseGltf asset.');+ }+ if (asset.parts.length > 4096 || asset.animations.length > 256 ||+ new Set(asset.parts.map(part => part.material)).size > 4096) {+ throw new RangeError('Asset budgets allow 4096 parts, 4096 materials, and 256 animation clips.');+ }+ const sourceParts = [...asset.parts];+ const materials = new Map();+ const geometries = new Map();+ const morphMetadata = new Map();+ const records = sourceParts.map((source, index) => {+ if (!materials.has(source.material)) {+ const id = `material-${materials.size}`;+ const baseline = {};+ for (const field of MATERIAL_FIELDS) {+ const value = source.material[field];+ if (value !== undefined) {+ baseline[field] = Array.isArray(value) ? [...value] : value;+ }+ }+ materials.set(source.material, { id, baseline });+ }+ if (!geometries.has(source.geometry)) {+ const metadata = validateMorphGeometry(source.geometry, source.morph);+ if (metadata) {+ morphMetadata.set(source.geometry, metadata);+ }+ geometries.set(source.geometry, {+ id: `geometry-${geometries.size}`, maxima: geometryMaxima(source.geometry), bounds: localBounds(source.geometry),+ });+ }+ validateSkinGeometry(source.geometry, source.skin);+ return {+ id: `mesh-${index}`, label: String(source.name ?? `Mesh ${index}`).slice(0, 256), source,+ geometry: geometries.get(source.geometry), material: materials.get(source.material),+ sourceMatrix: source.matrix, jointMatrices: source.skin?.jointMatrices,+ jointWorldMatrices: source.skin?.jointWorldMatrices, morphWeights: source.morph?.weights,+ };+ });+ const materialRecords = new Map([...materials.values()].map(record => [record.id, record]));+ const buffers = poseBuffers(sourceParts);+ const initialPose = snapshotPose(buffers);+ const initialRecipe = copiedJson(inputRecipe);+ const assetId = initialRecipe?.assetId;+ if (typeof assetId !== 'string' || !/^[a-f0-9]{64}$/i.test(assetId)) {+ throw new TypeError('assetId must contain 64 SHA256 hexadecimal characters.');+ }+ const canonicalAssetId = assetId.toLowerCase();+ const cameraOmitted = !Object.hasOwn(initialRecipe, 'camera');+ let recipe;+ let materialSnapshots = new Map();+ let matrices = [];+ let revision = 0;+ const checkpoints = new Map();+ const materialOutputs = new Map([...materials].map(([source, record]) => {+ const output = {};+ for (const [field, value] of Object.entries(source)) {+ if (!MATERIAL_FIELDS.includes(field)) {+ output[field] = Array.isArray(value) ? Object.freeze([...value]) : value;+ }+ }+ for (const field of MATERIAL_FIELDS) {+ Object.defineProperty(output, field, {+ enumerable: true,+ get() {+ return materialSnapshots.get(record.id)[field];+ },+ });+ }+ return [record.id, Object.freeze(output)];+ }));+ const parts = Object.freeze(records.map(record => {+ const part = {+ name: record.id, geometry: record.source.geometry,+ matrix: new Float32Array(record.source.matrix), material: materialOutputs.get(record.material.id),+ };+ if (record.source.skin) {+ part.skin = record.source.skin;+ }+ if (record.source.morph) {+ part.morph = record.source.morph;+ }+ if (record.source.castShadow !== undefined) {+ part.castShadow = record.source.castShadow;+ }+ return Object.freeze(part);+ }));+ const capabilities = Object.freeze({+ ...AGENT_ASSET_CAPABILITIES,+ animations: asset.animations.length,+ skinning: parts.some(part => Boolean(part.skin)),+ morphTargets: parts.some(part => Boolean(part.morph)),+ textures: [...materialOutputs.values()].some(material => Boolean(material.map || material.normalMap ||+ material.metallicRoughnessMap || material.occlusionMap || material.emissiveMap)),+ });++ function normalize(input) {+ const candidate = copiedJson(input);+ knownKeys(candidate, ['format', 'schemaVersion', 'assetId', 'camera', ...LOOK_FIELDS, 'root', 'animation', 'materialOverrides'], 'asset recipe');+ if (candidate.format !== '67js.asset' || candidate.schemaVersion !== 1 ||+ typeof candidate.assetId !== 'string' || candidate.assetId.toLowerCase() !== canonicalAssetId) {+ throw new RangeError('Expected the bound 67js.asset schemaVersion 1 assetId.');+ }+ const overrides = candidate.materialOverrides === undefined ? [] : candidate.materialOverrides;+ if (!Array.isArray(overrides) || overrides.length > materialRecords.size) {+ throw new RangeError('materialOverrides must be an array within the decoded material count.');+ }+ const seen = new Set();+ const definitions = overrides.map(override => {+ knownKeys(override, ['id', ...MATERIAL_FIELDS], 'material override');+ const original = materialRecords.get(override.id);+ if (!original || seen.has(override.id)) {+ throw new RangeError('Material override IDs must exist and be distinct.');+ }+ seen.add(override.id);+ return { id: override.id, ...original.baseline, ...override };+ });+ const view = viewRecipe(candidate, definitions);+ const normalizedOverrides = view.materials.map(material => {+ const result = { id: material.id };+ for (const field of MATERIAL_FIELDS) {+ if (material[field] !== undefined) {+ result[field] = material[field];+ }+ }+ return result;+ });+ const animation = candidate.animation === undefined ? null : candidate.animation;+ if (animation !== null) {+ knownKeys(animation, ['clip', 'time'], 'animation');+ const clip = asset.animations[animation.clip];+ if (!Number.isInteger(animation.clip) || !clip || !Number.isFinite(animation.time) ||+ animation.time < 0 || animation.time > clip.duration) {+ throw new RangeError('Animation needs an existing clip and time within its duration.');+ }+ }+ return copiedJson({+ format: '67js.asset', schemaVersion: 1, assetId: canonicalAssetId,+ camera: view.camera, environment: view.environment, effects: view.effects, shadow: view.shadow,+ root: rootFrom(candidate.root), animation, materialOverrides: normalizedOverrides,+ });+ }++ function publish(input, autoFrame = false, increment = true) {+ let candidate = normalize(input);+ if (asset.parts.length !== records.length) {+ throw new RangeError('Decoded part membership must remain fixed.');+ }+ for (let index = 0; index < records.length; index++) {+ const record = records[index];+ const source = record.source;+ if (asset.parts[index] !== source || source.geometry !== parts[index].geometry ||+ source.skin !== parts[index].skin || source.morph !== parts[index].morph ||+ source.matrix !== record.sourceMatrix || source.skin?.jointMatrices !== record.jointMatrices ||+ source.skin?.jointWorldMatrices !== record.jointWorldMatrices || source.morph?.weights !== record.morphWeights ||+ parts[index].matrix.length !== 16 || parts[index].matrix.byteLength !== 64) {+ throw new RangeError('Decoded resources and retained adapter matrices must not change identity or detach.');+ }+ }+ const previousPose = snapshotPose(buffers);+ try {+ if (candidate.animation === null) {+ restorePose(initialPose);+ } else {+ asset.applyAnimation(candidate.animation.time, candidate.animation.clip);+ }+ const rootMatrix = mat4.fromRotationTranslationScale(mat4.create(), candidate.root.rotation, candidate.root.translation, candidate.root.scale);+ const normal = mat3.create();+ const stagedMatrices = records.map(record => {+ const world = mat4.multiply(mat4.create(), rootMatrix, record.source.matrix);+ const determinant = mat4.determinant(world);+ if (!world.every(Number.isFinite) || !Number.isFinite(determinant) || determinant === 0 ||+ !mat3.normalFromMat4(normal, world) || !normal.every(Number.isFinite)) {+ throw new RangeError('Asset root/world matrices must remain finite and nonsingular at Float32 precision.');+ }+ if (record.source.skin) {+ validateSkinPose(record.source.skin, record.source.geometry, world);+ }+ if (record.source.morph) {+ validateMorphTransform(record.source.morph, morphMetadata.get(record.source.geometry), world, record.source.skin);+ } else {+ validatePositionBounds(record.geometry.maxima, world, record.source.skin);+ }+ return world;+ });+ if (autoFrame) {+ candidate.camera = framedCamera(framingBounds(records, stagedMatrices));+ candidate = normalize(candidate);+ }+ const stagedMaterials = new Map([...materialRecords].map(([id, record]) => [id, { ...record.baseline }]));+ for (const override of candidate.materialOverrides) {+ stagedMaterials.set(override.id, { ...stagedMaterials.get(override.id), ...override });+ }+ for (const snapshot of stagedMaterials.values()) {+ for (const field of ['color', 'emissiveColor']) {+ if (snapshot[field]) {+ Object.freeze(snapshot[field]);+ }+ }+ Object.freeze(snapshot);+ }+ for (let index = 0; index < parts.length; index++) {+ Float32Array.prototype.set.call(parts[index].matrix, stagedMatrices[index]);+ }+ recipe = candidate;+ materialSnapshots = stagedMaterials;+ matrices = stagedMatrices;+ if (increment) {+ revision++;+ }+ return revision;+ } catch (error) {+ if (recipe?.animation) {+ try {+ asset.applyAnimation(recipe.animation.time, recipe.animation.clip);+ } catch {+ // Accessible pose arrays below remain the authoritative rollback snapshot.+ }+ }+ restorePose(previousPose);+ throw error;+ }+ }++ function expected(options) {+ knownKeys(options, ['expectedRevision'], 'transaction options');+ if (!Number.isSafeInteger(options.expectedRevision) || options.expectedRevision !== revision) {+ throw new RangeError('expectedRevision must match the current revision.');+ }+ }++ publish(initialRecipe, cameraOmitted, false);+ return Object.freeze({+ parts, capabilities,+ get revision() {+ return revision;+ },+ get topologyRevision() {+ return 0;+ },+ get camera() {+ return structuredClone(recipe.camera);+ },+ get environment() {+ return structuredClone(recipe.environment);+ },+ get effects() {+ return structuredClone(recipe.effects);+ },+ get shadow() {+ return structuredClone(recipe.shadow);+ },+ exportRecipe() {+ return structuredClone(recipe);+ },+ apply(inputOperations, options = {}) {+ expected(options);+ if (!Array.isArray(inputOperations) || !inputOperations.length || inputOperations.length > MAX_OPERATIONS) {+ throw new RangeError('Asset operations must contain 1 to 256 commands.');+ }+ const operations = copiedJson(inputOperations);+ const candidate = structuredClone(recipe);+ for (const operation of operations) {+ const lookField = Object.hasOwn(LOOK_OPERATIONS, operation.type) ? LOOK_OPERATIONS[operation.type] : null;+ if (lookField) {+ knownKeys(operation, ['type', lookField], 'operation');+ const patch = operation[lookField];+ knownKeys(patch, Object.keys(candidate[lookField]), lookField);+ const nested = lookField === 'environment' ? 'volumeFog' : lookField === 'effects' ? 'bloom' : null;+ const merged = { ...candidate[lookField], ...patch };+ if (nested && Object.hasOwn(patch, nested)) {+ knownKeys(patch[nested], Object.keys(candidate[lookField][nested]), nested);+ merged[nested] = { ...candidate[lookField][nested], ...patch[nested] };+ }+ candidate[lookField] = merged;+ } else if (operation.type === 'set-camera') {+ knownKeys(operation, ['type', ...Object.keys(candidate.camera)], 'operation');+ for (const field of Object.keys(candidate.camera)) {+ if (Object.hasOwn(operation, field)) {+ candidate.camera[field] = operation[field];+ }+ }+ } else if (operation.type === 'set-root') {+ knownKeys(operation, ['type', ...ROOT_FIELDS], 'operation');+ for (const field of ROOT_FIELDS) {+ if (Object.hasOwn(operation, field)) {+ candidate.root[field] = operation[field];+ }+ }+ } else if (operation.type === 'set-animation') {+ knownKeys(operation, ['type', 'clip', 'time'], 'operation');+ if (operation.clip === null) {+ if (Object.hasOwn(operation, 'time')) {+ throw new TypeError('Returning to the initial pose requires clip:null with time omitted.');+ }+ candidate.animation = null;+ } else {+ const clip = operation.clip === undefined ? candidate.animation?.clip : operation.clip;+ const sameClip = candidate.animation !== null && clip === candidate.animation.clip;+ const time = operation.time === undefined ? (sameClip ? candidate.animation.time : 0) : operation.time;+ candidate.animation = { clip, time };+ }+ } else if (operation.type === 'set-material') {+ knownKeys(operation, ['type', 'id', ...MATERIAL_FIELDS], 'operation');+ if (!materialRecords.has(operation.id)) {+ throw new RangeError(`Unknown material ID: ${operation.id}.`);+ }+ let override = candidate.materialOverrides.find(value => value.id === operation.id);+ if (!override) {+ override = { id: operation.id };+ candidate.materialOverrides.push(override);+ }+ for (const field of MATERIAL_FIELDS) {+ if (Object.hasOwn(operation, field)) {+ override[field] = operation[field];+ }+ }+ } else {+ throw new TypeError('Unsupported asset operation. Geometry and topology editing are unavailable.');+ }+ }+ return publish(candidate);+ },+ inspect(inputOptions = {}) {+ const options = copiedJson(inputOptions);+ knownKeys(options, ['ids', 'limit', 'includeBounds'], 'inspection');+ const limit = options.limit === undefined ? 64 : options.limit;+ if (!Number.isInteger(limit) || limit < 1 || limit > 256 ||+ (options.includeBounds !== undefined && typeof options.includeBounds !== 'boolean')) {+ throw new RangeError('Inspection needs limit from 1 to 256 and boolean includeBounds.');+ }+ if (options.ids !== undefined && (!Array.isArray(options.ids) || options.ids.length > records.length)) {+ throw new RangeError('Inspection IDs must be an array within the decoded part count.');+ }+ 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}.`);+ }+ return record;+ });+ const visible = selected.slice(0, limit);+ if (options.includeBounds && visible.reduce((total, record) => total + record.source.geometry.positions.length / 3, 0) > MAX_INSPECTION_VERTICES) {+ throw new RangeError('Bounds inspection exceeds two million authored base vertices. Select fewer meshes.');+ }+ const nodes = visible.map(record => {+ const index = Number(record.id.slice(5));+ const node = {+ id: record.id, label: record.label, geometry: record.geometry.id, material: record.material.id,+ vertices: record.source.geometry.positions.length / 3,+ triangles: record.source.geometry.indices.length / 3,+ skinned: Boolean(record.source.skin), morphTargets: record.source.geometry.morphTargets?.length ?? 0,+ };+ if (options.includeBounds) {+ node.bounds = baseBounds([record], [matrices[index]]);+ node.boundsKind = AGENT_ASSET_CAPABILITIES.boundsKind;+ }+ return node;+ });+ let geometryBytes = 0;+ let vertices = 0;+ for (const geometry of geometries.keys()) {+ vertices += geometry.positions.length / 3;+ for (const value of Object.values(geometry)) {+ if (ArrayBuffer.isView(value)) {+ geometryBytes += value.byteLength;+ }+ }+ for (const target of geometry.morphTargets ?? []) {+ geometryBytes += (target.positions?.byteLength ?? 0) + (target.normals?.byteLength ?? 0);+ }+ }+ return {+ revision, topologyRevision: 0, assetId: canonicalAssetId,+ counts: { nodes: parts.length, parts: parts.length, geometries: geometries.size, materials: materials.size, vertices },+ geometryBytes, animation: structuredClone(recipe.animation),+ animations: asset.animations.map((clip, index) => ({ id: index, label: String(clip.name ?? `Clip ${index}`).slice(0, 256), duration: clip.duration })),+ nodes, truncated: selected.length > nodes.length,+ };+ },+ checkpoint() {+ if (checkpoints.size >= MAX_CHECKPOINTS) {+ throw new RangeError('Asset checkpoint budget exhausted. Release a checkpoint.');+ }+ const handle = Object.freeze({});+ checkpoints.set(handle, structuredClone(recipe));+ return handle;+ },+ restore(handle, options = {}) {+ expected(options);+ if (!checkpoints.has(handle)) {+ throw new RangeError('Unknown or released asset checkpoint.');+ }+ return publish(checkpoints.get(handle));+ },+ releaseCheckpoint(handle) {+ if (!checkpoints.delete(handle)) {+ throw new RangeError('Unknown or released asset checkpoint.');+ }+ },+ });+}diff --git a/tests/agent-asset-catalog.test.js b/tests/agent-asset-catalog.test.jsnew file mode 100644index 00000000..ee38eda6--- /dev/null+++ b/tests/agent-asset-catalog.test.js@@ -0,0 +1,93 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { mkdtemp, writeFile, rm, symlink } 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';++async function fixture(context) {+ const directory = await mkdtemp(join(tmpdir(), '67js-catalog-'));+ context.after(async () => {+ assert.equal(dirname(directory), tmpdir());+ await rm(directory, { recursive: true, force: true });+ });+ const bytes = Buffer.from(exportGlb([{ name: 'Cube', geometry: box(0), matrix: mat4.create(), material: { color: [0.2, 0.5, 0.7], roughness: 0.5, metallic: 0 } }]));+ await writeFile(join(directory, 'cube.glb'), bytes);+ return { directory, bytes };+}++function withDocument(bytes, edit) {+ const document = JSON.parse(bytes.subarray(20, 20 + bytes.readUInt32LE(12)).toString('utf8'));+ edit(document);+ const json = Buffer.from(JSON.stringify(document));+ const length = Math.ceil(json.length / 4) * 4;+ const binary = bytes.subarray(20 + bytes.readUInt32LE(12));+ const result = Buffer.alloc(20 + length + binary.length, 32);+ bytes.copy(result, 0, 0, 20);+ result.writeUInt32LE(result.length, 8);+ result.writeUInt32LE(length, 12);+ json.copy(result, 20);+ binary.copy(result, 20 + length);+ return result;+}++test('catalog IDs bind self-contained GLB content and metadata stays detached without paths', async context => {+ const { directory, bytes } = await fixture(context);+ await writeFile(join(directory, 'duplicate.glb'), bytes);+ await writeFile(join(directory, 'ignored.txt'), 'not an asset');+ const catalog = await createAgentAssetCatalog(directory);+ const listing = catalog.list();+ assert.equal(listing.assets.length, 1);+ assert.match(listing.assets[0].assetId, /^[a-f0-9]{64}$/);+ assert.equal(listing.assets[0].meshes, 1);+ assert.doesNotMatch(JSON.stringify(listing), /67js-catalog-/);+ const id = listing.assets[0].assetId;+ listing.assets[0].name = 'changed';+ assert.equal(catalog.list().assets[0].name, 'cube.glb');+ assert.deepEqual(await catalog.read(id), bytes);+ await assert.rejects(catalog.read('../cube.glb'), /Unknown asset/);+});++test('changed bytes cannot silently reuse a catalog digest', async context => {+ const { directory, bytes } = await fixture(context);+ const catalog = await createAgentAssetCatalog(directory);+ const id = catalog.list().assets[0].assetId;+ const changed = Buffer.from(bytes);+ changed[changed.length - 1] ^= 1;+ await writeFile(join(directory, 'cube.glb'), changed);+ await assert.rejects(catalog.read(id), /bytes changed/);+});++test('catalog rejects external resources and malformed or over-budget GLBs before browser loading', async context => {+ const { 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(28));+ await assert.rejects(createAgentAssetCatalog(directory), /complete glTF/);+});++test('declared clip metadata stays bounded even when a GLB contains many animation declarations', async context => {+ const { directory, bytes } = await fixture(context);+ await writeFile(join(directory, 'cube.glb'), withDocument(bytes, document => {+ document.animations = Array.from({ length: 100000 }, () => ({ name: 'x'.repeat(100) }));+ }));+ const catalog = await createAgentAssetCatalog(directory);+ const listing = catalog.list();+ assert.equal(listing.assets[0].animationCount, 100000);+ assert.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/);+});++test('catalog rejects linked assets and requires an explicitly absolute directory', async context => {+ const { directory } = await fixture(context);+ await assert.rejects(createAgentAssetCatalog('relative-assets'), /absolute/);+ await symlink(join(directory, 'cube.glb'), join(directory, 'linked.glb'), 'file');+ await assert.rejects(createAgentAssetCatalog(directory), /without links/);+});diff --git a/tests/agent-asset.test.js b/tests/agent-asset.test.jsnew file mode 100644index 00000000..b9392fd5--- /dev/null+++ b/tests/agent-asset.test.js@@ -0,0 +1,232 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { parseGltf } from '../src/gltf.js';+import { createAgentAssetScene } from '../src/agent-asset.js';+import { skinnedStripAsset } from './fixtures/skinned-strip.js';++const recipe = () => ({ format: '67js.asset', schemaVersion: 1, assetId: 'ab'.repeat(32) });++async function fixture(edit) {+ return parseGltf(skinnedStripAsset(edit));+}++function pose(asset) {+ return asset.parts.map(part => ({+ matrix: Array.from(part.matrix), joints: Array.from(part.skin?.jointMatrices ?? []),+ weights: Array.from(part.morph?.weights ?? []),+ }));+}++test('decoded resources and retained identities survive root, look, and material edits', async () => {+ const asset = await fixture();+ const descriptor = { data: new Uint8Array([1, 2, 3, 4]), width: 1, height: 1 };+ asset.parts[0].material.map = descriptor;+ const scene = createAgentAssetScene(asset, recipe());+ const part = scene.parts[0];+ const matrix = part.matrix;+ const initialCamera = scene.camera;+ assert.deepEqual(initialCamera.target, [1, 3, 0]);+ assert.equal(part.geometry, asset.parts[0].geometry);+ assert.equal(part.skin, asset.parts[0].skin);+ assert.equal(part.material.map, descriptor);+ scene.apply([+ { type: 'set-root', translation: [4, 0, 0] },+ { type: 'set-material', id: 'material-0', color: [0.2, 0.3, 0.4] },+ { type: 'set-effects', effects: { bloom: { strength: 0.25 } } },+ ], { expectedRevision: 0 });+ assert.equal(scene.parts[0], part);+ assert.equal(part.matrix, matrix);+ assert.equal(part.matrix[12], 5);+ assert.deepEqual(part.material.color, [0.2, 0.3, 0.4]);+ assert.equal(scene.effects.bloom.strength, 0.25);+ assert.deepEqual(scene.camera, initialCamera);+ assert.equal(scene.topologyRevision, 0);+ assert.equal(scene.inspect().counts.materials, 1);+ assert.equal(scene.inspect().nodes[0].id, 'mesh-0');+ const bounds = scene.inspect({ includeBounds: true }).nodes[0];+ assert.equal(bounds.boundsKind, 'authored-base-world');+ assert.ok(Math.abs(bounds.bounds.min[0] - 4.7) < 1e-6);+ asset.dispose();+});++test('absolute animation reverse seeks and initial-pose reset are deterministic', async () => {+ const asset = await fixture();+ const initialPose = pose(asset);+ const scene = createAgentAssetScene(asset, recipe());+ scene.apply([{ type: 'set-animation', clip: 0, time: 0.5 }], { expectedRevision: 0 });+ const halfPose = pose(asset);+ scene.apply([{ type: 'set-animation', time: 1.5 }], { expectedRevision: 1 });+ assert.notDeepEqual(pose(asset), halfPose);+ scene.apply([{ type: 'set-animation', time: 0.5 }], { expectedRevision: 2 });+ assert.deepEqual(pose(asset), halfPose);+ scene.apply([{ type: 'set-animation', clip: 1 }], { expectedRevision: 3 });+ assert.deepEqual(scene.exportRecipe().animation, { clip: 1, time: 0 });+ scene.apply([{ type: 'set-animation', clip: null }], { expectedRevision: 4 });+ assert.deepEqual(pose(asset), initialPose);+ assert.equal(scene.exportRecipe().animation, null);+ asset.dispose();+});++test('failed commands and Float32 root staging leave pose, recipe, materials, and revision atomic', async () => {+ const asset = await fixture();+ const scene = createAgentAssetScene(asset, { ...recipe(), animation: { clip: 0, time: 0.75 } });+ const checkpointRecipe = scene.exportRecipe();+ const checkpointPose = pose(asset);+ const matrix = Array.from(scene.parts[0].matrix);+ assert.throws(() => scene.apply([+ { type: 'set-material', id: 'material-0', color: [1, 0, 0] },+ { type: 'set-animation', time: 1.5 },+ { type: 'set-root', scale: [1e-40, 1e-40, 1e-40] },+ ], { expectedRevision: 0 }), /nonsingular/);+ assert.deepEqual(scene.exportRecipe(), checkpointRecipe);+ assert.deepEqual(pose(asset), checkpointPose);+ assert.deepEqual(Array.from(scene.parts[0].matrix), matrix);+ assert.equal(scene.revision, 0);+ assert.throws(() => scene.apply([{ type: 'set-root', translation: [2, 0, 0] }, { type: 'add-node', node: {} }], { expectedRevision: 0 }), /Unsupported/);+ assert.deepEqual(scene.exportRecipe(), checkpointRecipe);+ scene.apply([{ type: 'set-animation', time: 0.25 }], { expectedRevision: 0 });+ assert.equal(scene.revision, 1);+ asset.dispose();+});++test('real decoded morph weights retain identity and restore alongside animation', async () => {+ const asset = await fixture((document, append) => {+ const positions = append(new Float32Array(Array.from({ length: 6 }, () => [0, 0, 0.5]).flat()), 'VEC3');+ document.accessors[positions].min = [0, 0, 0.5];+ document.accessors[positions].max = [0, 0, 0.5];+ document.meshes[0].primitives[0].targets = [{ POSITION: positions }];+ document.meshes[0].weights = [0];+ const times = append(new Float32Array([0, 2]), 'SCALAR');+ const weights = append(new Float32Array([0, 1]), 'SCALAR');+ document.animations.push({+ name: 'Morph', samplers: [{ input: times, output: weights }],+ channels: [{ sampler: 0, target: { node: 1, path: 'weights' } }],+ });+ });+ const scene = createAgentAssetScene(asset, recipe());+ const weights = scene.parts[0].morph.weights;+ const checkpoint = scene.checkpoint();+ scene.apply([{ type: 'set-animation', clip: 2, time: 1 }], { expectedRevision: 0 });+ assert.equal(weights[0], 0.5);+ assert.equal(scene.parts[0].morph, asset.parts[0].morph);+ scene.restore(checkpoint, { expectedRevision: 1 });+ assert.equal(scene.parts[0].morph.weights, weights);+ assert.equal(weights[0], 0);+ assert.equal(scene.inspect().nodes[0].morphTargets, 1);+ asset.dispose();+});++test('checkpoint handles are private, bounded, revision checked, and restore identities', async () => {+ const asset = await fixture();+ const scene = createAgentAssetScene(asset, recipe());+ const handles = Array.from({ length: 8 }, () => scene.checkpoint());+ assert.throws(() => scene.checkpoint(), /budget/);+ assert.throws(() => scene.restore({}, { expectedRevision: 0 }), /Unknown/);+ const parts = scene.parts;+ scene.apply([{ type: 'set-root', scale: [2, 2, 2] }], { expectedRevision: 0 });+ assert.throws(() => scene.restore(handles[0], { expectedRevision: 0 }), /expectedRevision/);+ scene.restore(handles[0], { expectedRevision: 1 });+ assert.equal(scene.parts, parts);+ assert.equal(scene.revision, 2);+ assert.deepEqual(scene.exportRecipe().root.scale, [1, 1, 1]);+ scene.releaseCheckpoint(handles[0]);+ assert.throws(() => scene.releaseCheckpoint(handles[0]), /Unknown/);+ assert.throws(() => scene.restore(handles[0], { expectedRevision: 2 }), /Unknown/);+ scene.checkpoint();+ asset.dispose();+});++test('ordinary JSON, strict schemas, numeric domains, budgets, and stale revisions reject', async () => {+ const asset = await fixture();+ for (const invalid of [+ { ...recipe(), unknown: 1 }, { ...recipe(), root: { scale: [0, 1, 1] } },+ { ...recipe(), root: { rotation: [0, 0, 0, 0] } },+ { ...recipe(), animation: { clip: 0, time: 3 } },+ { ...recipe(), materialOverrides: [{ id: 'material-9', color: [1, 1, 1] }] },+ { ...recipe(), effects: { bloom: { unknown: 1 } } },+ { ...recipe(), assetId: 'x'.repeat(64) },+ ]) {+ assert.throws(() => createAgentAssetScene(asset, invalid));+ }+ let accessorRead = false;+ const accessor = recipe();+ Object.defineProperty(accessor, 'root', { enumerable: true, get() { accessorRead = true; return {}; } });+ assert.throws(() => createAgentAssetScene(asset, accessor), /accessors/);+ assert.equal(accessorRead, false);+ assert.throws(() => createAgentAssetScene(asset, { ...recipe(), root: { translation: [1, , 3] } }), /dense/);+ assert.throws(() => createAgentAssetScene(asset, { ...recipe(), extra: 'x'.repeat(1024 * 1024) }), /1 MiB/);+ const scene = createAgentAssetScene(asset, recipe());+ assert.throws(() => scene.apply([{ type: 'set-root', scale: [2, 2, 2] }]), /expectedRevision/);+ assert.throws(() => scene.apply([{ type: 'set-animation', clip: null, time: 0 }], { expectedRevision: 0 }), /omitted/);+ assert.throws(() => scene.inspect({ ids: ['mesh-9'] }), /Unknown/);+ assert.throws(() => createAgentAssetScene({ ...asset, animations: Array(257).fill(asset.animations[0]) }, recipe()), /budgets/);+ assert.throws(() => createAgentAssetScene({ ...asset, parts: Array(4097).fill(asset.parts[0]) }, recipe()), /budgets/);+ asset.dispose();+});++test('detached matrices and replaced pose buffers fail before publishing canonical state', async () => {+ const asset = await fixture();+ const scene = createAgentAssetScene(asset, recipe());+ const before = scene.exportRecipe();+ const palette = asset.parts[0].skin.jointMatrices;+ asset.parts[0].skin.jointMatrices = new Float32Array(palette);+ assert.throws(() => scene.apply([{ type: 'set-root', translation: [1, 0, 0] }], { expectedRevision: 0 }), /identity/);+ asset.parts[0].skin.jointMatrices = palette;+ structuredClone(scene.parts[0].matrix, { transfer: [scene.parts[0].matrix.buffer] });+ assert.throws(() => scene.apply([{ type: 'set-root', translation: [1, 0, 0] }], { expectedRevision: 0 }), /detach/);+ assert.equal(scene.revision, 0);+ assert.deepEqual(scene.exportRecipe(), before);+ asset.dispose();+});++test('nonanimated assets support root edits and detached exports while clips reject', async () => {+ const asset = await fixture(document => { document.animations = []; });+ const scene = createAgentAssetScene(asset, recipe());+ assert.throws(() => scene.apply([{ type: 'set-animation', clip: 0 }], { expectedRevision: 0 }), /existing clip/);+ const exported = scene.exportRecipe();+ exported.root.translation[0] = 100;+ const camera = scene.camera;+ camera.eye[0] = 100;+ assert.deepEqual(scene.exportRecipe().root.translation, [0, 0, 0]);+ assert.notEqual(scene.camera.eye[0], 100);+ assert.throws(() => { scene.parts[0].material.color[0] = 100; }, TypeError);+ scene.apply([{ type: 'set-root', rotation: [0, 0, 0, 2] }], { expectedRevision: 0 });+ assert.deepEqual(scene.exportRecipe().root.rotation, [0, 0, 0, 1]);+ asset.dispose();+});++test('decoder animation validation failure rolls back and permits later valid seeks', async () => {+ const asset = await fixture((document, append) => {+ const times = append(new Float32Array([0, 2]), 'SCALAR');+ const scales = append(new Float32Array([1, 1, 1, 0, 0, 0]), 'VEC3');+ document.animations.push({+ name: 'Collapse', samplers: [{ input: times, output: scales }],+ channels: [{ sampler: 0, target: { node: 0, path: 'scale' } }],+ });+ });+ const scene = createAgentAssetScene(asset, { ...recipe(), animation: { clip: 0, time: 0.5 } });+ const previousPose = pose(asset);+ const previousRecipe = scene.exportRecipe();+ assert.throws(() => scene.apply([{ type: 'set-animation', clip: 2, time: 2 }], { expectedRevision: 0 }));+ assert.deepEqual(pose(asset), previousPose);+ assert.deepEqual(scene.exportRecipe(), previousRecipe);+ assert.equal(scene.revision, 0);+ scene.apply([{ type: 'set-animation', clip: 0, time: 0.25 }], { expectedRevision: 0 });+ assert.equal(scene.revision, 1);+ asset.dispose();+});++test('decoded instances share original geometry and material wrappers', async () => {+ const asset = await fixture(document => {+ document.nodes.push({ name: 'Second strip', mesh: 0, skin: 0, translation: [3, 0, 0] });+ document.nodes[0].children.push(4);+ });+ const scene = createAgentAssetScene(asset, recipe());+ assert.equal(scene.parts.length, 2);+ assert.equal(scene.parts[0].geometry, scene.parts[1].geometry);+ assert.equal(scene.parts[0].material, scene.parts[1].material);+ assert.equal(scene.inspect().counts.geometries, 1);+ scene.apply([{ type: 'set-material', id: 'material-0', roughness: 0.2 }], { expectedRevision: 0 });+ assert.equal(scene.parts[1].material.roughness, 0.2);+ asset.dispose();+});diff --git a/tests/agent-runtime.test.js b/tests/agent-runtime.test.jsindex 02d2b25b..0a6a0d2e 100644--- a/tests/agent-runtime.test.js+++ b/tests/agent-runtime.test.js@@ -23,6 +23,7 @@ test('invalid preview configuration rejects before any browser or renderer allocassert.throws(() => createAgentRuntime({ memory }), /memory/);}assert.throws(() => createAgentRuntime({ browser: 'does-not-exist-browser.exe' }), /browser/);+ assert.throws(() => createAgentRuntime({ assets: 'relative-path' }), /absolute/);});test('requests cannot address an absent session or enter a closing runtime', async () => {diff --git a/tests/mcp-tools.test.js b/tests/mcp-tools.test.jsindex 0ccb09bf..9a0cb06e 100644--- a/tests/mcp-tools.test.js+++ b/tests/mcp-tools.test.js@@ -95,7 +95,7 @@ test('SDK advertises the complete strict JSON contract and truthful annotations'const { client } = await connect(context);const { tools } = await client.listTools();assert.deepEqual(tools.map(tool => tool.name).sort(), [- 'scene_apply', 'scene_capabilities', 'scene_checkpoint', 'scene_create', 'scene_dispose',+ 'scene_apply', 'scene_asset_catalog', 'scene_capabilities', 'scene_checkpoint', 'scene_create', 'scene_create_asset', 'scene_dispose','scene_export_recipe', 'scene_inspect', 'scene_look', 'scene_release_checkpoint', 'scene_restore',]);for (const tool of tools) {@@ -132,6 +132,9 @@ test('SDK rejects unknown fields, missing revisions, invalid vectors and oversizawait rejected(client, 'scene_capabilities', { javascript: 'process.exit()' });await rejected(client, 'scene_inspect', { sessionId: 'not-a-uuid' });await rejected(client, 'scene_look', { sessionId, width: 1025 });+ await rejected(client, 'scene_asset_catalog', { path: 'C:/private/file.glb' });+ await rejected(client, 'scene_create_asset', { recipe: { format: '67js.asset', schemaVersion: 1, assetId: '../file.glb' } });+ await rejected(client, 'scene_create_asset', { recipe: { format: '67js.asset', schemaVersion: 1, assetId: 'a'.repeat(64), root: { javascript: 'run' } } });await rejected(client, 'scene_look', { sessionId, file: 'out.png' });await rejected(client, 'scene_restore', { sessionId, checkpointId: randomUUID() });await rejected(client, 'scene_apply', { sessionId, operations: [{ type: 'set-camera' }] });diff --git a/vite.lib.config.js b/vite.lib.config.jsindex 26078c01..2dbbd098 100644--- a/vite.lib.config.js+++ b/vite.lib.config.js@@ -26,6 +26,7 @@ export default defineConfig({'surface-attachment': 'src/surface-attachment.js',physics: 'src/physics.js','agent-scene': 'src/agent-scene.js',+ 'agent-asset': 'src/agent-asset.js',},formats: ['es'],fileName: (_, entry) => entry === 'core' ? '67.module.js' : `${entry}.js`,