Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add data-only packs (#984)

Nguyen Xuan An4fecc2b27170
diff --git a/bin/67js-mcp.mjs b/bin/67js-mcp.mjs
index 48f6104a..995131c3 100644
--- a/bin/67js-mcp.mjs
+++ b/bin/67js-mcp.mjs
@@ -12,6 +12,7 @@ if (argumentsValue.length === 1 && argumentsValue[0] === '--version') {
console.log(`67js-mcp ${packageMetadata.version}
Usage: 67js-mcp [--backend gpu|cpu] [--memory 32..384]
[--browser <Chrome/Chromium executable>] [--assets <absolute GLB directory>]
+ [--packs <absolute folder of data-only packs>]
[--jobs <absolute private output directory>] [--ffmpeg <absolute executable>]
67js-mcp --version | --check-update
diff --git a/changes/984.md b/changes/984.md
new file mode 100644
index 00000000..8d6c12ef
--- /dev/null
+++ b/changes/984.md
@@ -0,0 +1 @@
+- `67js-mcp --packs <folder>` loads data-only packs of materials, recipes, looks, HDRIs and GLBs from a `67js-pack.json` manifest, checked at load, listed and read through `scene_asset_catalog`, with `npm run pack:check` for authors (#984).
diff --git a/changes/984.size.md b/changes/984.size.md
new file mode 100644
index 00000000..3055bc2a
--- /dev/null
+++ b/changes/984.size.md
@@ -0,0 +1,3 @@
+- tool:scene_asset_catalog: pack, recipe and material arguments (295 bytes) let an agent read one installed pack recipe or material without a new tool; a separate tool would cost more.
+- tool-total: the same fields.
+- result:scene_capabilities: the new packs topic adds 8 bytes to the index.
diff --git a/docs/packs.md b/docs/packs.md
new file mode 100644
index 00000000..467dc08f
--- /dev/null
+++ b/docs/packs.md
@@ -0,0 +1,80 @@
+# Data-only packs
+
+A pack is a folder of material sets, recipes, looks, HDRIs and GLB models with a manifest and no code. Someone shares it as a zip, you unzip it into a local folder, and 67js checks it when the MCP server starts. Nothing in a pack runs, and nothing is downloaded by a tool call.
+
+## Make a pack
+
+```
+my-pack/
+ 67js-pack.json
+ models/crate.glb
+ textures/brick.png
+ looks/warm.cube
+ hdri/studio.hdr
+ materials/rusty-metal.json
+ recipes/workshop.json
+ previews/workshop.png
+```
+
+`67js-pack.json` at the root:
+
+```json
+{
+ "format": "67js.pack", "schemaVersion": 1,
+ "name": "my-pack", "version": "1.0.0", "engines": { "67js": ">=0.19.0" },
+ "license": "CC0-1.0", "author": "Your Name", "description": "One line about the pack.",
+ "contents": {
+ "assets": [{ "id": "crate", "file": "models/crate.glb" }],
+ "images": [{ "id": "brick-albedo", "file": "textures/brick.png" }],
+ "looks": [{ "id": "warm", "file": "looks/warm.cube" }],
+ "environments": [{ "id": "studio", "file": "hdri/studio.hdr" }],
+ "materials": [{ "id": "rusty-metal", "file": "materials/rusty-metal.json" }],
+ "recipes": [{ "id": "workshop", "file": "recipes/workshop.json", "preview": "previews/workshop.png" }]
+ }
+}
+```
+
+| Kind | Files | What it is |
+| --- | --- | --- |
+| `assets` | `.glb` | Self-contained GLB, the same files `--assets` takes |
+| `images` | `.png` `.jpg` `.jpeg` `.webp` | Map images and sequence frames |
+| `looks` | `.cube` | 3D colour look (`LUT_3D_SIZE`) |
+| `environments` | `.hdr` | Radiance HDRI |
+| `materials` | `.json` | One material object, the fields of a `materials` entry in a recipe |
+| `recipes` | `.json` | A full recipe, as `scene_create` takes it; `preview` is an optional image |
+
+Rules, all checked at load:
+
+- Keys are known ones only. `name` and ids are kebab-case; ids are unique per kind. `version` is three numbers. `engines["67js"]` is a range of space-separated comparators (`>=`, `>`, `<`, `<=`, `=`, `^`, `~`, such as `>=0.19.0 <1`) that the installed 67js satisfies.
+- Paths are relative, with forward slashes, inside the pack: no `..`, no absolute or drive paths, no backslashes, only letters, digits, `.`, `_` and `-` in each part. Every listed file must exist and have the extension of its kind.
+- No symbolic links, and no script or program file anywhere in the pack, listed or not (`.js`, `.mjs`, `.html`, `.svg`, `.wasm`, `.exe`, `.sh`, `.bat`, `.ps1`, `.py` and similar). One such file refuses the whole pack.
+- Limits (`src/pack-manifest.js`): 256 files, 256 MiB in total, 64 MiB per file, 1 MiB per JSON file, 64 items per kind; at most 32 packs load at once.
+- Recipes and materials contain no remote URL (`http:`, `https:`, `ftp:`, `//host`, a `data:` URL that is not a PNG, JPEG or WebP image). A recipe has `"format": "67js.scene"`. `npm run pack:check` also runs the validator `scene_create` uses (a material is checked as the only material of an empty scene); the server leaves that to `scene_create` and `scene_apply`, which run it when the agent uses the item.
+
+An error names the pack, the file and the field, and says what to pass instead.
+
+## Validate
+
+```sh
+npm run pack:check -- path/to/my-pack
+```
+
+It runs the same checks as the server and prints `ok` or `FAIL` with the error. The repository ships `packs/example-starter/` (CC0) as a template to copy.
+
+## Install
+
+Unzip each pack into its own subfolder of one packs folder and start the server with that folder:
+
+```sh
+67js-mcp --packs /absolute/path/to/packs
+```
+
+A pack that fails the checks is skipped and listed with its error under `packs.rejected` in `scene_asset_catalog`; the others still load. Changed files need a server restart, like `--assets`.
+
+## Use from an agent
+
+`scene_asset_catalog` lists each pack's name, version, license, author, description and item ids. GLBs, images, looks and HDRIs carry the same SHA-256 `assetId` as `--assets` files (they also appear in the main `assets` list), so `scene_create_asset`, the `look` and `hdri` fields and texture sequences use them unchanged. For a material or recipe, call `scene_asset_catalog` with `{ "pack": "my-pack", "recipe": "workshop" }` or `{ "pack": "my-pack", "material": "rusty-metal" }` to read its JSON, then pass it to `scene_create` or use it as a `materials` entry. `scene_capabilities` topic `packs` has the limits.
+
+## Publish
+
+Zip the pack folder with `67js-pack.json` at the top of the archive, name the zip `name-version.zip` and host it anywhere, such as a GitHub release. State the license of every file in `license` and in a `LICENSE` file; 67js does not check licenses. Run `npm run pack:check` first, and say which 67js versions you tested.
diff --git a/package.json b/package.json
index c9d4bcd7..e6f9f50c 100644
--- a/package.json
+++ b/package.json
@@ -41,6 +41,7 @@
"docs/mcp.md",
"docs/mesh.md",
"docs/modeling.md",
+ "docs/packs.md",
"docs/physics.md",
"docs/runtime.md",
"docs/streaming.md",
@@ -148,6 +149,7 @@
"scripts": {
"prepare": "node scripts/install-git-hooks.mjs",
"dev": "vite --host 127.0.0.1",
+ "pack:check": "node scripts/pack-check.mjs",
"build": "node scripts/prepare-release.mjs && vite build",
"build:lib": "vite build --config vite.lib.config.js && vite build --config vite.browser.config.js",
"prepare:release": "node scripts/prepare-release.mjs",
diff --git a/packs/example-starter/67js-pack.json b/packs/example-starter/67js-pack.json
new file mode 100644
index 00000000..888d5438
--- /dev/null
+++ b/packs/example-starter/67js-pack.json
@@ -0,0 +1,37 @@
+{
+ "format": "67js.pack",
+ "schemaVersion": 1,
+ "name": "example-starter",
+ "version": "1.0.0",
+ "engines": {
+ "67js": ">=0.19.0"
+ },
+ "license": "CC0-1.0",
+ "author": "67js contributors",
+ "description": "Two materials, a warm look and a small crate recipe to copy from.",
+ "contents": {
+ "looks": [
+ {
+ "id": "warm",
+ "file": "looks/warm.cube"
+ }
+ ],
+ "materials": [
+ {
+ "id": "rusty-metal",
+ "file": "materials/rusty-metal.json"
+ },
+ {
+ "id": "warm-plaster",
+ "file": "materials/warm-plaster.json"
+ }
+ ],
+ "recipes": [
+ {
+ "id": "crates",
+ "file": "recipes/crates.json",
+ "preview": "previews/crates.png"
+ }
+ ]
+ }
+}
diff --git a/packs/example-starter/looks/warm.cube b/packs/example-starter/looks/warm.cube
new file mode 100644
index 00000000..0f630de2
--- /dev/null
+++ b/packs/example-starter/looks/warm.cube
@@ -0,0 +1,11 @@
+# warm: made for 67js, CC0.
+TITLE "warm"
+LUT_3D_SIZE 2
+0.04000 0.02000 0.00000
+1.00000 0.02000 0.00000
+0.04000 0.99000 0.00000
+1.00000 0.99000 0.00000
+0.04000 0.02000 0.88000
+1.00000 0.02000 0.88000
+0.04000 0.99000 0.88000
+1.00000 0.99000 0.88000
diff --git a/packs/example-starter/materials/rusty-metal.json b/packs/example-starter/materials/rusty-metal.json
new file mode 100644
index 00000000..2d779647
--- /dev/null
+++ b/packs/example-starter/materials/rusty-metal.json
@@ -0,0 +1,9 @@
+{
+ "color": [
+ 0.45,
+ 0.27,
+ 0.18
+ ],
+ "metallic": 0.85,
+ "roughness": 0.62
+}
diff --git a/packs/example-starter/materials/warm-plaster.json b/packs/example-starter/materials/warm-plaster.json
new file mode 100644
index 00000000..862fee5c
--- /dev/null
+++ b/packs/example-starter/materials/warm-plaster.json
@@ -0,0 +1,9 @@
+{
+ "color": [
+ 0.85,
+ 0.76,
+ 0.66
+ ],
+ "metallic": 0,
+ "roughness": 0.9
+}
diff --git a/packs/example-starter/previews/crates.png b/packs/example-starter/previews/crates.png
new file mode 100644
index 00000000..25d1af22
Binary files /dev/null and b/packs/example-starter/previews/crates.png differ
diff --git a/packs/example-starter/recipes/crates.json b/packs/example-starter/recipes/crates.json
new file mode 100644
index 00000000..a6649742
--- /dev/null
+++ b/packs/example-starter/recipes/crates.json
@@ -0,0 +1,78 @@
+{
+ "format": "67js.scene",
+ "schemaVersion": 1,
+ "geometries": [
+ {
+ "id": "crate",
+ "type": "box",
+ "bevel": 0.02
+ },
+ {
+ "id": "floor",
+ "type": "box"
+ }
+ ],
+ "materials": [
+ {
+ "id": "rusty-metal",
+ "color": [
+ 0.45,
+ 0.27,
+ 0.18
+ ],
+ "metallic": 0.85,
+ "roughness": 0.62
+ },
+ {
+ "id": "warm-plaster",
+ "color": [
+ 0.85,
+ 0.76,
+ 0.66
+ ],
+ "roughness": 0.9
+ }
+ ],
+ "nodes": [
+ {
+ "id": "floor",
+ "geometry": "floor",
+ "material": "warm-plaster",
+ "translation": [
+ 0,
+ -0.05,
+ 0
+ ],
+ "scale": [
+ 6,
+ 0.1,
+ 6
+ ]
+ },
+ {
+ "id": "crate-a",
+ "geometry": "crate",
+ "material": "rusty-metal",
+ "translation": [
+ 0,
+ 0.5,
+ 0
+ ]
+ },
+ {
+ "id": "crate-b",
+ "geometry": "crate",
+ "material": "rusty-metal",
+ "translation": [
+ 1.2,
+ 0.5,
+ 0.4
+ ],
+ "scale": [
+ 0.8,
+ 0.8,
+ 0.8
+ ]
+ }
+ ]
+}
diff --git a/scripts/agent-asset-catalog.mjs b/scripts/agent-asset-catalog.mjs
index 71d2305e..ef0fc957 100644
--- a/scripts/agent-asset-catalog.mjs
+++ b/scripts/agent-asset-catalog.mjs
@@ -1,6 +1,6 @@
import { createHash } from 'node:crypto';
import { open, readdir, realpath, lstat } from 'node:fs/promises';
-import { basename, isAbsolute, join, relative, sep } from 'node:path';
+import { isAbsolute, join, relative, sep } from 'node:path';
import { AGENT_ASSET_LIMITS, assetBytesLimitMessage } from '../src/agent-asset-limits.js';
import { MAXIMUM_CATALOG_LOOK_BYTES } from '../src/look-catalog.js';
@@ -57,88 +57,93 @@ function selfContainedGlb(bytes) {
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.');
+/** Reads one catalog file (GLB, image, .hdr or .cube) inside a real directory: its bytes, kind and content ID. `filename` may be a relative path with forward slashes. */
+export async function readCatalogFile(directory, 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 directory = await realpath(root);
- if (!(await lstat(directory)).isDirectory()) {
- throw new TypeError('Asset root must be a directory.');
+ const resolved = await realpath(path);
+ const offset = relative(directory, resolved);
+ if (offset.startsWith(`..${sep}`) || offset === '..' || isAbsolute(offset) || offset.split(sep).join('/') !== filename) {
+ throw new Error('Asset must remain inside its configured 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 handle = await open(resolved, 'r');
+ try {
+ const current = await handle.stat();
+ if (current.isFile() && current.size > MAXIMUM_BYTES) {
+ throw new RangeError(`${filename}: ${assetBytesLimitMessage(current.size)}`);
}
- 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.');
+ if (!current.isFile() || current.dev !== original.dev || current.ino !== original.ino || current.size < 20) {
+ throw new Error('Asset changed during opening or is too small to be a GLB.');
}
- const handle = await open(resolved, 'r');
- try {
- const current = await handle.stat();
- if (current.isFile() && current.size > MAXIMUM_BYTES) {
- throw new RangeError(`${filename}: ${assetBytesLimitMessage(current.size)}`);
- }
- if (!current.isFile() || current.dev !== original.dev || current.ino !== original.ino || current.size < 20) {
- throw new Error('Asset changed during opening or is too small to be a GLB.');
- }
- const bytes = Buffer.alloc(current.size);
- let position = 0;
- 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 lookKind = lookFileKind(filename, bytes);
- const imageFormat = lookKind ? null : imageKind(bytes);
- if (imageFormat && !IMAGE_EXTENSIONS[imageFormat].test(filename)) throw new Error('Image extension must match its PNG, JPEG or WebP content.');
- if (!imageFormat && !lookKind && !/\.glb$/i.test(filename)) throw new Error('Catalog files must be GLB, PNG, JPEG, WebP, HDR or CUBE, with a matching extension.');
- const document = imageFormat || lookKind ? null : selfContainedGlb(bytes);
- const assetId = createHash('sha256').update(bytes).digest('hex');
- return { bytes, document, assetId, imageFormat, lookKind };
- } finally {
- await handle.close();
+ 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 lookKind = lookFileKind(filename, bytes);
+ const imageFormat = lookKind ? null : imageKind(bytes);
+ if (imageFormat && !IMAGE_EXTENSIONS[imageFormat].test(filename)) throw new Error('Image extension must match its PNG, JPEG or WebP content.');
+ if (!imageFormat && !lookKind && !/\.glb$/i.test(filename)) throw new Error('Catalog files must be GLB, PNG, JPEG, WebP, HDR or CUBE, with a matching extension.');
+ const document = imageFormat || lookKind ? null : selfContainedGlb(bytes);
+ const assetId = createHash('sha256').update(bytes).digest('hex');
+ return { bytes, document, assetId, imageFormat, lookKind, kind: lookKind ?? (imageFormat ? 'image' : 'glb') };
+ } finally {
+ await handle.close();
}
+}
- const files = (await readdir(directory, { withFileTypes: true }))
- .filter(entry => /\.(glb|png|jpe?g|webp|hdr|cube)$/i.test(entry.name)).sort((left, right) => left.name.localeCompare(right.name));
- if (files.length > MAXIMUM_ASSETS) throw new RangeError(`Asset catalog has ${files.length} files, over its maxAssets ${MAXIMUM_ASSETS}. Remove files from the --assets directory.`);
- for (const file of files) {
- const { bytes, document, assetId, imageFormat, lookKind } = await readFile(file.name);
- if (entries.has(assetId)) continue;
- if (lookKind) {
- entries.set(assetId, { filename: file.name, metadata: Object.freeze({ assetId, name: file.name, bytes: bytes.length, kind: lookKind }) });
- continue;
+/** The catalog record of a file read by readCatalogFile; `name` is what the agent sees. */
+export function describeCatalogFile(name, { bytes, document, assetId, imageFormat, lookKind }) {
+ if (lookKind) return Object.freeze({ assetId, name, bytes: bytes.length, kind: lookKind });
+ if (imageFormat) return Object.freeze({ assetId, name, bytes: bytes.length, kind: 'image', mimeType: IMAGE_MIME[imageFormat] });
+ const animations = document.animations ?? [];
+ if (!Array.isArray(animations)) throw new Error('GLB animations must be an array.');
+ return Object.freeze({
+ assetId, name, bytes: bytes.length, kind: 'glb',
+ 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) })),
+ });
+}
+
+/**
+ * Explicit local directory catalog. IDs bind bytes, rather than agent-supplied file paths.
+ * `packFiles` adds the validated GLB, image, .hdr and .cube files of installed packs (scripts/agent-packs.mjs),
+ * each `{ directory, filename, assetId, metadata }`. With a null root only pack files are listed.
+ */
+export async function createAgentAssetCatalog(root, packFiles = []) {
+ const entries = new Map();
+ if (root !== null) {
+ 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.');
}
- if (imageFormat) {
- entries.set(assetId, { filename: file.name, metadata: Object.freeze({ assetId, name: file.name, bytes: bytes.length, kind: 'image', mimeType: IMAGE_MIME[imageFormat] }) });
- continue;
+ const files = (await readdir(directory, { withFileTypes: true }))
+ .filter(entry => /\.(glb|png|jpe?g|webp|hdr|cube)$/i.test(entry.name)).sort((left, right) => left.name.localeCompare(right.name));
+ if (files.length > MAXIMUM_ASSETS) throw new RangeError(`Asset catalog has ${files.length} files, over its maxAssets ${MAXIMUM_ASSETS}. Remove files from the --assets directory.`);
+ for (const file of files) {
+ const result = await readCatalogFile(directory, file.name);
+ if (entries.has(result.assetId)) continue;
+ entries.set(result.assetId, { directory, filename: file.name, metadata: describeCatalogFile(file.name, result) });
}
- 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, kind: 'glb',
- 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) })),
- }),
- });
+ }
+ for (const file of packFiles) {
+ if (!entries.has(file.assetId)) entries.set(file.assetId, { directory: file.directory, filename: file.filename, metadata: file.metadata });
}
return Object.freeze({
list() {
@@ -147,7 +152,7 @@ export async function createAgentAssetCatalog(root) {
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);
+ const result = await readCatalogFile(entry.directory, entry.filename);
if (result.assetId !== assetId) throw new Error('Asset bytes changed since catalog creation. Restart the runtime to refresh the catalog.');
const clipCount = result.document?.animations?.length ?? 0;
if (clipCount > AGENT_ASSET_LIMITS.maxClips) throw new RangeError(`Asset has ${clipCount} animation clips, over the catalog maxClips ${AGENT_ASSET_LIMITS.maxClips}. Remove clips from the file.`);
diff --git a/scripts/agent-packs.mjs b/scripts/agent-packs.mjs
new file mode 100644
index 00000000..1bfb106c
--- /dev/null
+++ b/scripts/agent-packs.mjs
@@ -0,0 +1,166 @@
+// Installed data-only packs: reads each subfolder of the --packs directory, checks it against src/pack-manifest.js and the
+// catalog's own file checks, and hands the MCP runtime its GLB, image, look and environment files (content-hash IDs, like
+// --assets) plus its material and recipe JSON. Nothing is fetched and no caller-supplied path is read.
+import { lstat, readdir, readFile, realpath } from 'node:fs/promises';
+import { basename, isAbsolute, join } from 'node:path';
+
+import { invalidField } from '../src/field-error.js';
+import {
+ MAXIMUM_INSTALLED_PACKS, MAXIMUM_PACK_BYTES, MAXIMUM_PACK_FILES, MAXIMUM_PACK_FILE_BYTES, MAXIMUM_PACK_JSON_BYTES,
+ PACK_MANIFEST_FILE, findRemoteUrl, isExecutableLookingName, validatePackManifest,
+} from '../src/pack-manifest.js';
+import { describeCatalogFile, readCatalogFile } from './agent-asset-catalog.mjs';
+
+const MAXIMUM_FOLDER_DEPTH = 8;
+// The catalog kind each manifest list must hold.
+const CATALOG_KIND = { assets: 'glb', images: 'image', looks: 'look', environments: 'environment' };
+
+function packError(label, detail) {
+ return new Error(`pack "${label}": ${detail}`);
+}
+
+/** Lists every file of the pack as `Map(relative path -> bytes)`, refusing links, odd entries, code files and oversize packs. */
+async function listPackFiles(directory, label) {
+ const files = new Map();
+ let totalBytes = 0;
+ async function visit(folder, prefix, depth) {
+ if (depth > MAXIMUM_FOLDER_DEPTH) throw packError(label, `${prefix || '.'} is nested deeper than ${MAXIMUM_FOLDER_DEPTH} folders. Flatten the pack.`);
+ for (const entry of await readdir(folder, { withFileTypes: true })) {
+ const relativePath = prefix + entry.name;
+ const details = await lstat(join(folder, entry.name));
+ if (details.isSymbolicLink()) throw invalidField(`pack "${label}" ${relativePath}`, 'a symbolic link', 'a regular file or folder; remove the link and copy the real file into the pack');
+ if (details.isDirectory()) {
+ await visit(join(folder, entry.name), `${relativePath}/`, depth + 1);
+ continue;
+ }
+ if (!details.isFile()) throw invalidField(`pack "${label}" ${relativePath}`, 'a special file', 'a regular file or folder');
+ if (isExecutableLookingName(entry.name)) throw invalidField(`pack "${label}" ${relativePath}`, 'a script, page or program file', 'data only: remove every .js, .html, .wasm, .exe, .sh, .bat, .ps1, .py and similar file from the pack');
+ if (details.size > MAXIMUM_PACK_FILE_BYTES) throw invalidField(`pack "${label}" ${relativePath}`, `${details.size} bytes`, `at most ${MAXIMUM_PACK_FILE_BYTES} bytes (64 MiB) per file; shrink or remove it`);
+ totalBytes += details.size;
+ if (files.size + 1 > MAXIMUM_PACK_FILES) throw invalidField(`pack "${label}"`, `over ${MAXIMUM_PACK_FILES} files`, `at most ${MAXIMUM_PACK_FILES} files; remove unused ones or split the pack`);
+ if (totalBytes > MAXIMUM_PACK_BYTES) throw invalidField(`pack "${label}"`, `over ${totalBytes} bytes`, `at most ${MAXIMUM_PACK_BYTES} bytes (256 MiB) in total; split the pack`);
+ files.set(relativePath, details.size);
+ }
+ }
+ await visit(directory, '', 0);
+ return files;
+}
+
+async function readJsonFile(directory, file, label, field) {
+ const text = (await readFile(join(directory, file), 'utf8')).replace(/^/, '');
+ if (Buffer.byteLength(text) > MAXIMUM_PACK_JSON_BYTES) throw invalidField(`pack "${label}" ${field}`, `${file} over ${MAXIMUM_PACK_JSON_BYTES} bytes`, 'a JSON file of at most 1 MiB; split it or drop data you do not need');
+ try {
+ return JSON.parse(text);
+ } catch (error) {
+ throw invalidField(`pack "${label}" ${file}`, 'text that is not JSON', `valid JSON (${error.message})`, SyntaxError);
+ }
+}
+
+/**
+ * `validateScene(kind, id, json)` is the scene validator (scripts/pack-scene-validator.mjs). The MCP server does not carry the
+ * scene engine, so it passes none and scene_create checks a recipe when the agent uses it; `npm run pack:check` passes it.
+ */
+async function validateJsonContent(kind, id, json, label, file, validateScene) {
+ const remote = findRemoteUrl(json);
+ if (remote) throw invalidField(`pack "${label}" ${file} ${remote.path}`, remote.value, 'no remote URL: a pack is data only. Reference pack files by their catalog ID, and use data:image/png|jpeg|webp;base64 only for small images');
+ if (!json || typeof json !== 'object' || Array.isArray(json)) throw invalidField(`pack "${label}" ${file}`, json, 'one JSON object');
+ if (kind === 'recipes' && json.format !== '67js.scene') throw invalidField(`pack "${label}" ${file} format`, json.format, '"67js.scene", the recipe format scene_create takes');
+ if (!validateScene) return;
+ try {
+ await validateScene(kind, id, json);
+ } catch (error) {
+ error.message = `pack "${label}" ${file}: ${error.message}`;
+ throw error;
+ }
+}
+
+/** Loads and fully validates one pack folder. Throws an error that names the pack, file and field. */
+export async function loadPack(folder, { packageVersion, label = basename(String(folder)), validateScene }) {
+ if (typeof folder !== 'string' || !isAbsolute(folder)) throw packError(label, 'pass the pack folder as an absolute path.');
+ const folderDetails = await lstat(folder);
+ if (folderDetails.isSymbolicLink() || !folderDetails.isDirectory()) throw packError(label, 'the pack must be a real folder, not a link or a file.');
+ const directory = await realpath(folder);
+ const files = await listPackFiles(directory, label);
+ if (!files.has(PACK_MANIFEST_FILE)) throw invalidField(`pack "${label}"`, `no ${PACK_MANIFEST_FILE}`, `a ${PACK_MANIFEST_FILE} file at the pack root`);
+ const manifest = validatePackManifest(await readJsonFile(directory, PACK_MANIFEST_FILE, label, PACK_MANIFEST_FILE), { label, packageVersion });
+ const packFiles = [];
+ const json = { materials: new Map(), recipes: new Map() };
+ const items = {};
+ for (const [kind, list] of Object.entries(manifest.contents)) {
+ items[kind] = [];
+ for (const [index, item] of list.entries()) {
+ const field = `contents.${kind}[${index}]`;
+ for (const [key, file] of [['file', item.file], ['preview', item.preview]]) {
+ if (file !== undefined && !files.has(file)) throw invalidField(`pack "${label}" ${PACK_MANIFEST_FILE} ${field}.${key}`, file, 'a file that exists in the pack; check the spelling and capitals');
+ }
+ if (kind === 'materials' || kind === 'recipes') {
+ const content = await readJsonFile(directory, item.file, label, `${field}.file`);
+ await validateJsonContent(kind, item.id, content, label, item.file, validateScene);
+ json[kind].set(item.id, content);
+ items[kind].push({ id: item.id, ...(item.preview && { preview: item.preview }) });
+ } else {
+ const result = await readFileForKind(directory, item.file, label, `${field}.file`, kind);
+ packFiles.push({ directory, filename: item.file, assetId: result.assetId, metadata: describeCatalogFile(`${manifest.name}/${item.file}`, result) });
+ items[kind].push({ id: item.id, assetId: result.assetId });
+ }
+ if (item.preview) await readFileForKind(directory, item.preview, label, `${field}.preview`, 'images');
+ }
+ }
+ return Object.freeze({ name: manifest.name, folder: basename(directory), version: manifest.version, license: manifest.license, author: manifest.author, description: manifest.description, items, json, files: packFiles });
+}
+
+async function readFileForKind(directory, file, label, field, kind) {
+ let result;
+ try {
+ result = await readCatalogFile(directory, file);
+ } catch (error) {
+ throw invalidField(`pack "${label}" ${file}`, `${field}: ${error.message}`, 'a valid file of the listed kind (self-contained GLB, PNG/JPEG/WebP, Radiance .hdr, 3D .cube)');
+ }
+ if (result.kind !== CATALOG_KIND[kind]) throw invalidField(`pack "${label}" ${file}`, `a ${result.kind} file`, `a ${CATALOG_KIND[kind]} file for contents.${kind}`);
+ return result;
+}
+
+/** Loads every subfolder of `root` as a pack. A bad pack is reported in `rejected` and skipped. */
+export async function loadPacks(root, { packageVersion, validateScene }) {
+ if (typeof root !== 'string' || !isAbsolute(root)) throw new TypeError('Pack root must be an explicit absolute directory path.');
+ const directory = await realpath(root);
+ if (!(await lstat(directory)).isDirectory()) throw new TypeError('Pack root must be a directory.');
+ const folders = (await readdir(directory, { withFileTypes: true }))
+ .filter(entry => (entry.isDirectory() || entry.isSymbolicLink()) && !entry.name.startsWith('.'))
+ .map(entry => entry.name).sort();
+ const packs = [];
+ const rejected = [];
+ for (const folder of folders) {
+ try {
+ if (packs.length >= MAXIMUM_INSTALLED_PACKS) throw packError(folder, `skipped: at most ${MAXIMUM_INSTALLED_PACKS} packs load at once. Remove packs from the --packs folder.`);
+ const pack = await loadPack(join(directory, folder), { packageVersion, label: folder, validateScene });
+ if (packs.some(other => other.name === pack.name)) throw packError(folder, `another installed pack already uses the name "${pack.name}". Rename one in its ${PACK_MANIFEST_FILE}.`);
+ packs.push(pack);
+ } catch (error) {
+ rejected.push({ folder, error: error.message });
+ }
+ }
+ return { packs, rejected };
+}
+
+/** The runtime's view of the installed packs: a listing, the catalog files, and read-only access to material and recipe JSON. */
+export async function createPackRegistry(root, { packageVersion }) {
+ const { packs, rejected } = await loadPacks(root, { packageVersion });
+ return Object.freeze({
+ files: packs.flatMap(pack => pack.files),
+ list() {
+ return {
+ packs: packs.map(({ name, version, license, author, description, items }) => structuredClone({ name, version, license, author, description, items })),
+ rejected: structuredClone(rejected),
+ };
+ },
+ /** A copy of one material or recipe JSON, by pack name and id. */
+ read(kind, packName, id) {
+ const pack = packs.find(candidate => candidate.name === packName);
+ if (!pack) throw invalidField('pack', packName, `an installed pack name: ${packs.map(candidate => candidate.name).join(', ') || 'none installed'}`);
+ const content = pack.json[kind].get(id);
+ if (content === undefined) throw invalidField(kind === 'recipes' ? 'recipe' : 'material', id, `an id of this pack's ${kind}: ${pack.items[kind].map(item => item.id).join(', ') || 'none'}`);
+ return structuredClone(content);
+ },
+ });
+}
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
index 0669abd8..8b33734d 100644
--- a/scripts/agent-runtime.mjs
+++ b/scripts/agent-runtime.mjs
@@ -19,6 +19,8 @@ import { chooseDenoiser, finishWithOidn } from './agent-path-trace-denoise.mjs';
import { createNativeSequence } from './agent-native-sequence.mjs';
import { chooseNativeInstancing, chooseNativeKernel, chooseTraceBackend, createNativeTracerLocator, isNativeTimeLimitError, traceFrameNative, traceTexelsNative } from './agent-native-trace.mjs';
import { createAgentAssetCatalog } from './agent-asset-catalog.mjs';
+import { createPackRegistry } from './agent-packs.mjs';
+import { MAXIMUM_INSTALLED_PACKS, MAXIMUM_PACK_BYTES, MAXIMUM_PACK_FILES, MAXIMUM_PACK_FILE_BYTES, MAXIMUM_PACK_JSON_BYTES, MAXIMUM_PACK_ITEMS_PER_KIND, PACK_CONTENT_KINDS } from '../src/pack-manifest.js';
import { geometryOnlyGlb } from './agent-query-asset.mjs';
import { AGENT_ASSET_LIMITS, assertCombinedAssetBytes } from '../src/agent-asset-limits.js';
import { recipeAssetNeeds } from '../src/agent-scene-assets.js';
@@ -84,7 +86,7 @@ const VENDOR_FILES = Object.freeze({
'/vendor/rapier.js': { resolve: require => join(dirname(require.resolve('@dimforge/rapier3d-compat')), 'rapier.mjs'), type: 'application/javascript; charset=utf-8' },
});
-export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', browser: browserPath, memory = 192, assets: assetRoot,
+export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', browser: browserPath, memory = 192, assets: assetRoot, packs: packsRoot,
jobs: jobRoot, ffmpeg = 'ffmpeg', audio: audioRoot, openPage = openInDefaultBrowser,
previewUrl = new URL(/* @vite-ignore */ '../build/mcp/preview.js', import.meta.url) } = {}) {
if (!['gpu', 'cpu'].includes(backend)) {
@@ -100,6 +102,9 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
if (assetRoot !== undefined && (typeof assetRoot !== 'string' || !isAbsolute(assetRoot))) {
throw new TypeError('Asset root must be an explicit absolute directory path.');
}
+ if (packsRoot !== undefined && (typeof packsRoot !== 'string' || !isAbsolute(packsRoot))) {
+ throw new TypeError('Packs root must be an explicit absolute directory path.');
+ }
if (jobRoot !== undefined && (typeof jobRoot !== 'string' || !isAbsolute(jobRoot))) {
throw new TypeError('Job root must be an explicit absolute directory path.');
}
@@ -125,6 +130,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
let queue = Promise.resolve();
let closing;
let catalogPromise;
+ let packsPromise;
let jobsPromise;
const savedGlbPaths = [];
const savedWebBuildPaths = [];
@@ -158,10 +164,16 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
phase = 'ready';
}
function catalog() {
- if (!assetRoot) throw new Error('Configure --assets with an absolute directory before importing GLB assets.');
- catalogPromise ??= createAgentAssetCatalog(assetRoot);
+ if (!assetRoot && !packsRoot) throw new Error('Configure --assets or --packs with an absolute directory before importing GLB assets.');
+ catalogPromise ??= packs().then(registry => createAgentAssetCatalog(assetRoot ?? null, registry?.files));
return catalogPromise;
}
+ // Installed data-only packs (docs/packs.md): checked once per runtime; their GLB, image, look and HDRI files join the catalog.
+ function packs() {
+ if (!packsRoot) return Promise.resolve(null);
+ packsPromise ??= createPackRegistry(packsRoot, { packageVersion: packageMetadata.version });
+ return packsPromise;
+ }
/** Bytes of the catalog assets a recipe or edit list places, base64 by asset id, for the page that decodes them. */
async function placedAssetData(value) {
@@ -805,6 +817,12 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
maximumJoints: AGENT_ASSET_LIMITS.maxJoints, maximumClips: AGENT_ASSET_LIMITS.maxClips,
commands: ['set-root', 'set-asset-node', 'set-motion', 'set-animation', 'set-material', 'set-camera', 'set-environment', 'set-effects', 'set-shadow'],
},
+ packs: {
+ configured: Boolean(packsRoot), format: '67js.pack', manifest: '67js-pack.json', contentKinds: Object.keys(PACK_CONTENT_KINDS),
+ extensions: PACK_CONTENT_KINDS, maximumPacks: MAXIMUM_INSTALLED_PACKS, maximumFiles: MAXIMUM_PACK_FILES, maximumBytes: MAXIMUM_PACK_BYTES,
+ maximumFileBytes: MAXIMUM_PACK_FILE_BYTES, maximumJsonBytes: MAXIMUM_PACK_JSON_BYTES, maximumItemsPerKind: MAXIMUM_PACK_ITEMS_PER_KIND,
+ use: 'scene_asset_catalog lists packs: name, version, license, author, description and item ids. GLBs, images, looks and environments carry assetId values that work in scene_create_asset, look, hdri and texture fields. Materials and recipes are read with scene_asset_catalog { pack, material } or { pack, recipe }: pass a recipe to scene_create, and a material as a materials entry or a scene_apply set-material. Packs are installed by the user (unzip into the --packs folder); a tool call never downloads one. Invalid packs are skipped and listed under packs.rejected with the reason.',
+ },
jobs: { configured: Boolean(jobRoot), kinds: ['image', 'stills', 'video'], passes: RENDER_PASS_NAMES, pathTracer: PATH_TRACER_CAPABILITIES, maximumActiveJobs: 1,
maximumWidth: MAXIMUM_JOB_SIDE, maximumHeight: MAXIMUM_JOB_SIDE, maximumPixels: MAXIMUM_JOB_PIXELS,
maximumDuration: MAXIMUM_VIDEO_SECONDS, maximumFps: 30, maximumFrames: 900, maximumStills: 8,
@@ -825,8 +843,20 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
return result;
});
},
- assetCatalog() {
- return enqueue(async () => assetRoot ? { configured: true, ...(await catalog()).list() } : { configured: false, assets: [] });
+ /** The catalog with the installed packs; `{ pack, recipe }` or `{ pack, material }` reads one pack item's JSON instead. */
+ assetCatalog({ pack, recipe, material } = {}) {
+ return enqueue(async () => {
+ if (pack !== undefined || recipe !== undefined || material !== undefined) {
+ if (!packsRoot) throw new Error('Configure --packs with an absolute directory to read pack items.');
+ if (pack === undefined || (recipe === undefined) === (material === undefined)) {
+ throw new RangeError('Pass pack with exactly one of recipe or material, such as { "pack": "example-starter", "recipe": "workshop" }; scene_asset_catalog without arguments lists them.');
+ }
+ const kind = recipe === undefined ? 'materials' : 'recipes';
+ return { pack, [kind === 'recipes' ? 'recipe' : 'material']: recipe ?? material, json: (await packs()).read(kind, pack, recipe ?? material) };
+ }
+ if (!assetRoot && !packsRoot) return { configured: false, assets: [] };
+ return { configured: true, ...(await catalog()).list(), ...(packsRoot && { packs: (await packs()).list() }) };
+ });
},
createAsset({ recipe }) {
return enqueue(async () => {
diff --git a/scripts/capabilities-topics.mjs b/scripts/capabilities-topics.mjs
index 667cc8b0..95439c59 100644
--- a/scripts/capabilities-topics.mjs
+++ b/scripts/capabilities-topics.mjs
@@ -5,7 +5,7 @@ import * as z from 'zod/v4';
import { outlineSchema, unionBranches } from './schema-outline.mjs';
import { AGENT_TOOL_EXAMPLES } from './tool-examples.mjs';
-const RUNTIME_SECTIONS = ['sceneLimits', 'preview', 'review', 'assets', 'jobs', 'unsupported'];
+const RUNTIME_SECTIONS = ['sceneLimits', 'preview', 'review', 'assets', 'packs', 'jobs', 'unsupported'];
const SUMMARY_LENGTH = 110;
// Scalars (booleans and numbers) of the scene capabilities share one topic instead of one each.
const FLAGS_TOPIC = 'flags';
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index bd94ae3d..733ef257 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -653,6 +653,7 @@ const cloth = z.strictObject({
}).describe('Baked at 60 fps, seeked by motionTime. Units, defaults: scene_capabilities cloth.');
// The full motion schema (tracks, ik, constraints, drivers) is in scene_create's recipe. scene_apply and asset recipes
// take the same object, validated by the backend, without repeating about 35 KB of schema in each tool.
+const packName = z.string().regex(/^[a-z0-9]+(-[a-z0-9]+)*$/).max(64);
const recipeMotionReference = z.record(z.string(), z.unknown()).describe('The same object as recipe.motion in scene_create: duration, loop, tracks, ik, constraints, drivers. Read that tool for the fields. On an imported asset it also takes layers, up to 8 clips played at motion time before tracks and ik: { clip (scene_inspect animations id), mask: { joints, descendants, exclude } of node IDs, weight, speed, offset, loop, additive, reference, bones: { clip node: asset node } to retarget by name, morph } or from: { asset, clip } for a clip of another catalog asset retargeted onto this humanoid (scale, rootMotion). motion also takes drive (a car along a path, see scene_capabilities motionDrive) and footLock (true or { contactHeight, contactSpeed, blend, ground }) and { kind: "morph", id: target name, property: "weight" } tracks. A masked layer waves while another walks.');
const boneRecord = z.strictObject({
name: z.string().min(1).max(64).describe('Unique within the armature. Humanoid rigs use the canonical names (hips, spine, chest, neck, head, leftUpperArm, leftLowerArm, leftHand, leftUpperLeg, leftLowerLeg, leftFoot, leftToes, and right...) so retarget works.'),
@@ -922,7 +923,7 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versio
return jsonResult(pendingUpdate === null ? shown : { ...shown, updateAvailable: pendingUpdate });
});
register('scene_create', 'Create a render scene from a JSON recipe; the result has its sessionId. Several scenes stay open; past the cap the least recently used one is closed.', z.strictObject({ recipe: relations ? recipe : recipeWithoutRelations }), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.create(argumentsValue)));
- register('scene_asset_catalog', 'List content-bound GLB and PNG, JPEG or WebP image IDs from the configured local asset directory. No arbitrary paths or downloads.', z.strictObject({}), readOnly, async () => jsonResult(await runtime.assetCatalog()));
+ register('scene_asset_catalog', 'List content-bound GLB, image, HDRI and look IDs from the asset directory and installed packs. pack with recipe or material reads that item. No paths or downloads; scene_capabilities packs.', z.strictObject({ pack: packName.optional(), recipe: packName.optional(), material: packName.optional() }), readOnly, async argumentsValue => jsonResult(await runtime.assetCatalog(argumentsValue)));
register('scene_create_asset', 'Create the active scene from a catalog GLB and editable asset recipe. Preserves supported maps, skins, morphs and clips. The result has its sessionId.', z.strictObject({ recipe: assetRecipe }), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.createAsset(argumentsValue)));
register('scene_inspect', 'Read revision, counts and selected nodes. For a recipe with physics, the result lists body final positions, resting times, contacts and sensor enter/leave events. Bounds describe authored geometry rather than shader displacement.', z.strictObject({ ...sessionFields, ids: z.array(identifier).max(4096).optional().describe('Selected node IDs; an imported node means its parts and those below. Omit to inspect scene order.'), kind: z.enum(['meshes', 'hierarchy']).optional().describe('Imported assets only: hierarchy exposes stable source-node IDs and joints.'), offset: z.number().int().min(0).max(4096).optional().describe('Imported assets only: pagination offset.'), 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.'), path: z.record(z.string(), z.unknown()).optional().describe('Walking route over a ground node, around holes: fields in scene_capabilities navigation.') }), readOnly, async argumentsValue => jsonResult(await runtime.inspect(argumentsValue)));
register('scene_walkmap', 'Walkable map on a grid: rows of . walkable, x blocked, # no surface. keepOut (m) avoids obstacles. assetId: query a big catalog GLB, no render.', z.strictObject({ ...sessionFields, assetId: z.string().regex(/^[a-f0-9]{64}$/).optional(), min: z.tuple([z.number(), z.number()]), max: z.tuple([z.number(), z.number()]), cellSize: z.number().min(0.05).default(1), clearance: z.number().min(0).default(2), keepOut: z.number().min(0).optional(), streetY: z.number().optional(), includeCells: z.boolean().optional() }), readOnly, async argumentsValue => jsonResult(await runtime.walkMap(argumentsValue)));
@@ -988,8 +989,8 @@ export async function runMcpCli({ argumentsValue = process.argv.slice(2),
for (let index = 0; index < argumentsValue.length; index += 2) {
const name = argumentsValue[index];
const value = argumentsValue[index + 1];
- if (!['--backend', '--browser', '--memory', '--assets', '--jobs', '--ffmpeg', '--audio', '--branches', '--relations'].includes(name) || value === undefined) {
- throw new Error(`Use --backend cpu|gpu, --browser <local executable path>, --memory <32..${MAXIMUM_MEMORY_MIB} MiB>, --assets <absolute GLB directory>, --jobs <absolute private output directory>, --ffmpeg <absolute executable>, --audio <absolute folder of .wav, .mp3, .ogg or .flac files for video jobs>, --branches on|off and --relations on|off (both default on).`);
+ if (!['--backend', '--browser', '--memory', '--assets', '--packs', '--jobs', '--ffmpeg', '--audio', '--branches', '--relations'].includes(name) || value === undefined) {
+ throw new Error(`Use --backend cpu|gpu, --browser <local executable path>, --memory <32..${MAXIMUM_MEMORY_MIB} MiB>, --assets <absolute GLB directory>, --packs <absolute folder of data-only packs>, --jobs <absolute private output directory>, --ffmpeg <absolute executable>, --audio <absolute folder of .wav, .mp3, .ogg or .flac files for video jobs>, --branches on|off and --relations on|off (both default on).`);
}
options[name.slice(2)] = name === '--memory' ? Number(value) : value;
}
diff --git a/scripts/pack-check.mjs b/scripts/pack-check.mjs
new file mode 100644
index 00000000..40fd08bb
--- /dev/null
+++ b/scripts/pack-check.mjs
@@ -0,0 +1,26 @@
+#!/usr/bin/env node
+// Checks data-only packs before you publish them: `npm run pack:check -- <pack folder> [<pack folder> ...]`.
+// Runs the checks the MCP server runs when it loads --packs, plus the scene validator for recipes and materials.
+import { resolve } from 'node:path';
+import packageMetadata from '../package.json' with { type: 'json' };
+import { loadPack } from './agent-packs.mjs';
+import { validatePackScene } from './pack-scene-validator.mjs';
+
+const folders = process.argv.slice(2);
+if (folders.length === 0) {
+ console.error('Usage: npm run pack:check -- <absolute or relative pack folder> [more folders]');
+ process.exit(2);
+}
+
+let failed = false;
+for (const folder of folders) {
+ try {
+ const pack = await loadPack(resolve(folder), { packageVersion: packageMetadata.version, validateScene: validatePackScene });
+ const counts = Object.entries(pack.items).filter(([, items]) => items.length > 0).map(([kind, items]) => `${items.length} ${kind}`).join(', ');
+ console.log(`ok ${pack.name} ${pack.version} (${counts || 'no items'})`);
+ } catch (error) {
+ failed = true;
+ console.error(`FAIL ${error.message}`);
+ }
+}
+process.exit(failed ? 1 : 0);
diff --git a/scripts/pack-scene-validator.mjs b/scripts/pack-scene-validator.mjs
new file mode 100644
index 00000000..e5812067
--- /dev/null
+++ b/scripts/pack-scene-validator.mjs
@@ -0,0 +1,13 @@
+// The scene validator for pack recipes and materials. It runs in `npm run pack:check` and in tests, never in the MCP server:
+// the server does not carry the scene engine (scripts/build-mcp.mjs), and scene_create and scene_apply run these same
+// checks on a recipe or material when an agent uses it.
+import { createAgentScene, loadAgentSceneModules } from '../src/agent-scene.js';
+
+/** Throws the error scene_create would throw for this recipe; a material is checked as the only material of an empty scene. */
+export async function validatePackScene(kind, id, json) {
+ const recipe = kind === 'recipes'
+ ? json
+ : { format: '67js.scene', schemaVersion: 1, geometries: [], materials: [{ ...json, id: json?.id ?? id }], nodes: [] };
+ await loadAgentSceneModules(recipe);
+ createAgentScene(recipe);
+}
diff --git a/src/pack-manifest.js b/src/pack-manifest.js
new file mode 100644
index 00000000..f4c80f6b
--- /dev/null
+++ b/src/pack-manifest.js
@@ -0,0 +1,206 @@
+// Data-only packs: a folder with a 67js-pack.json manifest and the files it lists (GLB models, images, .cube looks, .hdr
+// environments, material and recipe JSON). The checks here are pure; scripts/agent-packs.mjs reads the folder and applies them.
+// A pack never carries code, and nothing in it is fetched: every file is local and listed by a relative path.
+import { invalidField } from './field-error.js';
+
+export const PACK_MANIFEST_FILE = '67js-pack.json';
+export const PACK_FORMAT = '67js.pack';
+export const PACK_SCHEMA_VERSION = 1;
+export const MAXIMUM_PACK_FILES = 256;
+export const MAXIMUM_PACK_BYTES = 256 * 1024 * 1024;
+export const MAXIMUM_PACK_FILE_BYTES = 64 * 1024 * 1024;
+export const MAXIMUM_PACK_JSON_BYTES = 1024 * 1024;
+export const MAXIMUM_PACK_ITEMS_PER_KIND = 64;
+export const MAXIMUM_INSTALLED_PACKS = 32;
+
+const MAXIMUM_PATH_CHARACTERS = 200;
+const MAXIMUM_NAME_CHARACTERS = 64;
+const MAXIMUM_RANGE_CHARACTERS = 64;
+const MAXIMUM_RANGE_COMPARATORS = 8;
+const MAXIMUM_JSON_DEPTH = 64;
+
+/** The kinds of content a pack lists, with the file extensions each accepts. */
+export const PACK_CONTENT_KINDS = Object.freeze({
+ assets: Object.freeze(['.glb']),
+ images: Object.freeze(['.png', '.jpg', '.jpeg', '.webp']),
+ looks: Object.freeze(['.cube']),
+ environments: Object.freeze(['.hdr']),
+ materials: Object.freeze(['.json']),
+ recipes: Object.freeze(['.json']),
+});
+export const PACK_PREVIEW_EXTENSIONS = Object.freeze(['.png', '.jpg', '.jpeg', '.webp']);
+
+// Anything a browser, shell or loader could run. A pack holding one anywhere is refused whole, listed or not.
+const EXECUTABLE_EXTENSIONS = new Set([
+ '.js', '.mjs', '.cjs', '.jsx', '.ts', '.mts', '.cts', '.tsx', '.html', '.htm', '.xhtml', '.svg', '.wasm',
+ '.exe', '.dll', '.com', '.scr', '.msi', '.sh', '.bash', '.zsh', '.bat', '.cmd', '.ps1', '.psm1', '.vbs', '.wsf',
+ '.py', '.pyc', '.rb', '.pl', '.php', '.jar', '.so', '.dylib', '.node', '.lnk', '.app', '.command', '.appimage',
+]);
+
+const NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
+const VERSION_PATTERN = /^(\d+)\.(\d+)\.(\d+)$/;
+const COMPARATOR_PATTERN = /^(>=|<=|>|<|=|\^|~)?(\d+)(?:\.(\d+))?(?:\.(\d+))?$/;
+const PATH_SEGMENT_PATTERN = /^[A-Za-z0-9._-]+$/;
+const REMOTE_URL_PATTERN = /(?:^|[\s"'(=])(?:https?|ftp|wss?|file|blob|javascript):/i;
+const PROTOCOL_RELATIVE_PATTERN = /^\s*\/\/[^\s/]/;
+const REMOTE_HOST_PATTERN = /(?:https?|ftp|wss?):\/\//i;
+const IMAGE_DATA_URL_PATTERN = /^data:image\/(?:png|jpeg|webp);base64,/i;
+
+/** True for a file name a pack must never hold, whatever the manifest lists. */
+export function isExecutableLookingName(filename) {
+ const lower = String(filename).toLowerCase();
+ const dot = lower.lastIndexOf('.');
+ return dot >= 0 && EXECUTABLE_EXTENSIONS.has(lower.slice(dot));
+}
+
+export function fileExtension(filename) {
+ const lower = String(filename).toLowerCase();
+ const dot = lower.lastIndexOf('.');
+ return dot >= 0 ? lower.slice(dot) : '';
+}
+
+function parseVersion(text) {
+ const match = VERSION_PATTERN.exec(text);
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
+}
+
+function compareVersions(left, right) {
+ for (let index = 0; index < 3; index++) {
+ if (left[index] !== right[index]) return left[index] < right[index] ? -1 : 1;
+ }
+ return 0;
+}
+
+function comparatorBounds(comparator) {
+ const match = COMPARATOR_PATTERN.exec(comparator);
+ if (!match) return null;
+ const operator = match[1] ?? '=';
+ const parts = [match[2], match[3], match[4]];
+ const specified = parts.filter(part => part !== undefined).length;
+ const base = parts.map(part => Number(part ?? 0));
+ const bumpAt = index => base.map((part, position) => (position < index ? part : position === index ? part + 1 : 0));
+ switch (operator) {
+ case '>=': return { lower: base };
+ case '>': return specified === 3 ? { lowerExclusive: base } : { lower: bumpAt(specified - 1) };
+ case '<': return { upper: base };
+ case '<=': return specified === 3 ? { upperInclusive: base } : { upper: bumpAt(specified - 1) };
+ case '=': return specified === 3 ? { lower: base, upperInclusive: base } : { lower: base, upper: bumpAt(specified - 1) };
+ case '~': return { lower: base, upper: bumpAt(specified === 1 ? 0 : 1) };
+ default: {
+ // ^ keeps the left-most non-zero part among those written.
+ const firstNonZero = base.slice(0, specified).findIndex(part => part > 0);
+ return { lower: base, upper: bumpAt(firstNonZero === -1 ? specified - 1 : firstNonZero) };
+ }
+ }
+}
+
+/**
+ * True when `version` ("1.2.3") satisfies `range`: space-separated comparators, all of which must hold. Each is >=, >, <, <=, =,
+ * ^ or ~ with 1 to 3 numeric parts, such as ">=0.19.0 <1" or "^0.19". No pre-release tags, no ||.
+ * Returns null for a range that cannot be read, so the caller can say what to pass.
+ */
+export function semverSatisfies(version, range) {
+ const current = parseVersion(version);
+ if (!current || typeof range !== 'string' || range.length === 0 || range.length > MAXIMUM_RANGE_CHARACTERS) return null;
+ const comparators = range.trim().split(/\s+/);
+ if (comparators.length > MAXIMUM_RANGE_COMPARATORS) return null;
+ const allBounds = comparators.map(comparatorBounds);
+ if (allBounds.includes(null)) return null;
+ return allBounds.every(bounds => (!bounds.lower || compareVersions(current, bounds.lower) >= 0)
+ && (!bounds.lowerExclusive || compareVersions(current, bounds.lowerExclusive) > 0)
+ && (!bounds.upper || compareVersions(current, bounds.upper) < 0)
+ && (!bounds.upperInclusive || compareVersions(current, bounds.upperInclusive) <= 0));
+}
+
+/** The first string in parsed JSON that is a remote URL (http, https, ftp, ws, //host, file, blob, javascript, or a data URL that is not an image), as `{ path, value }`; else null. */
+export function findRemoteUrl(value, path = '$') {
+ if (typeof value === 'string') {
+ const dataUrl = /^\s*data:/i.test(value);
+ const remote = dataUrl ? !IMAGE_DATA_URL_PATTERN.test(value.trim()) : REMOTE_URL_PATTERN.test(value) || PROTOCOL_RELATIVE_PATTERN.test(value) || REMOTE_HOST_PATTERN.test(value);
+ return remote ? { path, value } : null;
+ }
+ if (!value || typeof value !== 'object') return null;
+ if (path.split('.').length > MAXIMUM_JSON_DEPTH) return { path, value: '(nested too deeply)' };
+ const entries = Array.isArray(value) ? value.map((item, index) => [`${path}[${index}]`, item]) : Object.entries(value).map(([key, item]) => [`${path}.${key}`, item]);
+ for (const [childPath, child] of entries) {
+ const found = findRemoteUrl(child, childPath);
+ if (found) return found;
+ }
+ return null;
+}
+
+/** Throws unless `value` is a forward-slash relative path of safe segments inside the pack: no "..", no absolute or drive paths, no backslashes. */
+export function assertPackFilePath(value, fieldPath) {
+ const expected = 'a relative path inside the pack with forward slashes and only letters, digits, . _ - in each part, such as "models/crate.glb"';
+ if (typeof value !== 'string' || value.length === 0 || value.length > MAXIMUM_PATH_CHARACTERS) throw invalidField(fieldPath, value, expected);
+ if (value.startsWith('/') || value.includes('\\') || /^[A-Za-z]:/.test(value)) throw invalidField(fieldPath, value, expected);
+ for (const segment of value.split('/')) {
+ if (segment === '' || segment === '.' || segment === '..' || !PATH_SEGMENT_PATTERN.test(segment)) throw invalidField(fieldPath, value, expected);
+ }
+ return value;
+}
+
+function assertKnownKeys(object, allowed, fieldPath) {
+ if (!object || typeof object !== 'object' || Array.isArray(object)) throw invalidField(fieldPath, object, `an object with only the keys ${allowed.join(', ')}`, TypeError);
+ for (const key of Object.keys(object)) {
+ if (!allowed.includes(key)) throw invalidField(`${fieldPath}.${key}`, object[key], `no such key; allowed keys are ${allowed.join(', ')}`, TypeError);
+ }
+}
+
+function assertText(value, fieldPath, maximum, example) {
+ if (typeof value !== 'string' || value.trim().length === 0 || value.length > maximum) throw invalidField(fieldPath, value, `a non-empty string of at most ${maximum} characters, such as ${example}`);
+ return value;
+}
+
+function assertIdentifier(value, fieldPath) {
+ if (typeof value !== 'string' || value.length > MAXIMUM_NAME_CHARACTERS || !NAME_PATTERN.test(value)) throw invalidField(fieldPath, value, 'a kebab-case id of at most 64 characters, such as "rusty-metal"');
+ return value;
+}
+
+function normalizeItems(kind, items, label, prefix) {
+ const fieldPath = `${prefix}.contents.${kind}`;
+ if (!Array.isArray(items) || items.length > MAXIMUM_PACK_ITEMS_PER_KIND) throw invalidField(fieldPath, items, `an array of at most ${MAXIMUM_PACK_ITEMS_PER_KIND} items, such as [{ "id": "name", "file": "folder/name${PACK_CONTENT_KINDS[kind][0]}" }]`);
+ const seen = new Set();
+ return items.map((item, index) => {
+ const itemPath = `${fieldPath}[${index}]`;
+ assertKnownKeys(item, kind === 'recipes' ? ['id', 'file', 'preview'] : ['id', 'file'], itemPath);
+ const id = assertIdentifier(item.id, `${itemPath}.id`);
+ if (seen.has(id)) throw invalidField(`${itemPath}.id`, id, `an id used once in contents.${kind}; rename one of the duplicates`);
+ seen.add(id);
+ const file = assertPackFilePath(item.file, `${itemPath}.file`);
+ if (!PACK_CONTENT_KINDS[kind].includes(fileExtension(file))) throw invalidField(`${itemPath}.file`, file, `a file ending in ${PACK_CONTENT_KINDS[kind].join(', ')} for ${kind}`);
+ const result = { id, file };
+ if (kind === 'recipes' && item.preview !== undefined) {
+ result.preview = assertPackFilePath(item.preview, `${itemPath}.preview`);
+ if (!PACK_PREVIEW_EXTENSIONS.includes(fileExtension(result.preview))) throw invalidField(`${itemPath}.preview`, result.preview, `an image ending in ${PACK_PREVIEW_EXTENSIONS.join(', ')}`);
+ }
+ return result;
+ });
+}
+
+/**
+ * Checks a parsed 67js-pack.json and returns a clean copy. `label` names the pack in errors (its folder name) and
+ * `packageVersion` is the running 67js version that engines["67js"] must admit.
+ */
+export function validatePackManifest(manifest, { label, packageVersion }) {
+ const prefix = `pack "${label}" ${PACK_MANIFEST_FILE}`;
+ assertKnownKeys(manifest, ['format', 'schemaVersion', 'name', 'version', 'engines', 'license', 'author', 'description', 'contents'], prefix);
+ if (manifest.format !== PACK_FORMAT) throw invalidField(`${prefix}.format`, manifest.format, `"${PACK_FORMAT}"`);
+ if (manifest.schemaVersion !== PACK_SCHEMA_VERSION) throw invalidField(`${prefix}.schemaVersion`, manifest.schemaVersion, String(PACK_SCHEMA_VERSION));
+ const name = assertIdentifier(manifest.name, `${prefix}.name`);
+ if (typeof manifest.version !== 'string' || !parseVersion(manifest.version)) throw invalidField(`${prefix}.version`, manifest.version, 'a version of three numbers, such as "1.0.0"');
+ assertKnownKeys(manifest.engines, ['67js'], `${prefix}.engines`);
+ const range = manifest.engines['67js'];
+ const admitted = semverSatisfies(packageVersion, range);
+ if (admitted === null) throw invalidField(`${prefix}.engines.67js`, range, 'a range of space-separated comparators >=, >, <, <=, =, ^ or ~ with numbers, such as ">=0.19.0"');
+ if (!admitted) throw invalidField(`${prefix}.engines.67js`, range, `a range that admits the installed 67js ${packageVersion}, such as ">=${packageVersion}"; this pack needs another 67js version`);
+ const license = assertText(manifest.license, `${prefix}.license`, 64, '"CC0-1.0"');
+ const author = assertText(manifest.author, `${prefix}.author`, 120, '"Your Name"');
+ const description = assertText(manifest.description, `${prefix}.description`, 200, '"Brick and metal materials"');
+ assertKnownKeys(manifest.contents, Object.keys(PACK_CONTENT_KINDS), `${prefix}.contents`);
+ const contents = {};
+ for (const kind of Object.keys(PACK_CONTENT_KINDS)) {
+ contents[kind] = manifest.contents[kind] === undefined ? [] : normalizeItems(kind, manifest.contents[kind], label, prefix);
+ }
+ return { format: PACK_FORMAT, schemaVersion: PACK_SCHEMA_VERSION, name, version: manifest.version, engines: { '67js': range }, license, author, description, contents };
+}
diff --git a/tests/packs.test.js b/tests/packs.test.js
new file mode 100644
index 00000000..75252daa
--- /dev/null
+++ b/tests/packs.test.js
@@ -0,0 +1,232 @@
+import './support/load-agent-scene-modules.mjs';
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, truncateSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { Client } from '@modelcontextprotocol/client';
+import { InMemoryTransport } from '@modelcontextprotocol/server';
+import { createAgentMcpServer } from '../scripts/mcp-server.mjs';
+import { createAgentRuntime } from '../scripts/agent-runtime.mjs';
+import { loadPack, loadPacks } from '../scripts/agent-packs.mjs';
+import { validatePackScene } from '../scripts/pack-scene-validator.mjs';
+import { MAXIMUM_PACK_ITEMS_PER_KIND, semverSatisfies, validatePackManifest } from '../src/pack-manifest.js';
+import packageMetadata from '../package.json' with { type: 'json' };
+
+const packageVersion = packageMetadata.version;
+const EXAMPLE = new URL('../packs/example-starter', import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1');
+const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=', 'base64');
+
+function tinyGlb() {
+ const json = Buffer.from(JSON.stringify({ asset: { version: '2.0' } }).padEnd(32, ' '));
+ const header = Buffer.alloc(20);
+ header.writeUInt32LE(0x46546c67, 0);
+ header.writeUInt32LE(2, 4);
+ header.writeUInt32LE(20 + json.length, 8);
+ header.writeUInt32LE(json.length, 12);
+ header.writeUInt32LE(0x4e4f534a, 16);
+ return Buffer.concat([header, json]);
+}
+
+function temporaryFolder(context) {
+ const folder = mkdtempSync(join(tmpdir(), '67js-packs-'));
+ context.after(() => rmSync(folder, { recursive: true, force: true }));
+ return folder;
+}
+
+/** A copy of the example pack in `parent/name`, with `change(manifest, folder)` applied to its manifest. */
+function installPack(parent, name, change = () => {}) {
+ const folder = join(parent, name);
+ cpSync(EXAMPLE, folder, { recursive: true });
+ const manifestPath = join(folder, '67js-pack.json');
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
+ change(manifest, folder);
+ writeFileSync(manifestPath, JSON.stringify(manifest));
+ return folder;
+}
+
+function loadFrom(folder) {
+ return loadPack(folder, { packageVersion, validateScene: validatePackScene });
+}
+
+test('the example pack loads and lists its items', async () => {
+ const pack = await loadFrom(EXAMPLE);
+ assert.equal(pack.name, 'example-starter');
+ assert.deepEqual(pack.items.materials.map(item => item.id), ['rusty-metal', 'warm-plaster']);
+ assert.deepEqual(pack.items.recipes, [{ id: 'crates', preview: 'previews/crates.png' }]);
+ assert.equal(pack.items.looks[0].assetId, createHash('sha256').update(readFileSync(join(EXAMPLE, 'looks/warm.cube'))).digest('hex'));
+});
+
+test('a pack with a model, image and HDRI gives each a content-hash ID', async context => {
+ const folder = installPack(temporaryFolder(context), 'full', (manifest, root) => {
+ mkdirSync(join(root, 'models'));
+ writeFileSync(join(root, 'models/crate.glb'), tinyGlb());
+ writeFileSync(join(root, 'models/bg.png'), PNG);
+ writeFileSync(join(root, 'models/studio.hdr'), '#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n\n-Y 1 +X 1\n\u0080\u0080\u0080\u0081');
+ manifest.contents.assets = [{ id: 'crate', file: 'models/crate.glb' }];
+ manifest.contents.images = [{ id: 'bg', file: 'models/bg.png' }];
+ manifest.contents.environments = [{ id: 'studio', file: 'models/studio.hdr' }];
+ });
+ const pack = await loadFrom(folder);
+ assert.equal(pack.items.assets[0].assetId, createHash('sha256').update(tinyGlb()).digest('hex'));
+ assert.equal(pack.files.length, 4);
+ assert.match(pack.items.environments[0].assetId, /^[a-f0-9]{64}$/);
+});
+
+async function assertRefused(context, change, pattern, prepare) {
+ const parent = temporaryFolder(context);
+ const folder = installPack(parent, 'bad-pack', (manifest, root) => {
+ prepare?.(root);
+ change(manifest, root);
+ });
+ await assert.rejects(() => loadFrom(folder), pattern);
+}
+
+test('a script file anywhere in the pack refuses the whole pack', async context => {
+ await assertRefused(context, () => {}, /pack "bad-pack" extras\/run\.js: got "a script, page or program file"; expected data only/, root => {
+ mkdirSync(join(root, 'extras'));
+ writeFileSync(join(root, 'extras/run.js'), 'console.log(1)');
+ });
+});
+
+test('a remote URL inside a recipe is refused with its location', async context => {
+ await assertRefused(context, () => {}, /pack "bad-pack" recipes\/crates\.json \$\.nodes\[0\]\.note: got "https:\/\/example\.test\/x"; expected no remote URL/, root => {
+ const path = join(root, 'recipes/crates.json');
+ const recipe = JSON.parse(readFileSync(path, 'utf8'));
+ recipe.nodes[0].note = 'https://example.test/x';
+ writeFileSync(path, JSON.stringify(recipe));
+ });
+});
+
+test('a recipe or material the scene validator rejects is refused', async context => {
+ await assertRefused(context, () => {}, /pack "bad-pack" materials\/rusty-metal\.json: .*sparkle/, root => {
+ writeFileSync(join(root, 'materials/rusty-metal.json'), JSON.stringify({ sparkle: 3 }));
+ });
+});
+
+test('a file over 64 MiB is refused with the limit', async context => {
+ await assertRefused(context, () => {}, /pack "bad-pack" big\.bin: got "67108865 bytes"; expected at most 67108864 bytes/, root => {
+ writeFileSync(join(root, 'big.bin'), '');
+ truncateSync(join(root, 'big.bin'), 64 * 1024 * 1024 + 1);
+ });
+});
+
+test('JSON over 1 MiB is refused', async context => {
+ await assertRefused(context, () => {}, /over 1048576 bytes|1 MiB/, root => {
+ writeFileSync(join(root, 'materials/rusty-metal.json'), JSON.stringify({ color: [1, 1, 1], pad: 'x'.repeat(1024 * 1024) }));
+ });
+});
+
+test('an engines range that excludes this version is refused', async context => {
+ await assertRefused(context, manifest => { manifest.engines['67js'] = '>=99.0.0'; }, /engines\.67js: got ">=99\.0\.0"; expected a range that admits the installed 67js/);
+ await assertRefused(context, manifest => { manifest.engines['67js'] = 'latest'; }, /engines\.67js: got "latest"; expected a range of space-separated comparators/);
+});
+
+test('paths that leave the pack are refused', async context => {
+ for (const file of ['../outside.json', '/etc/passwd', 'C:/Windows/x.json', 'materials\\rusty-metal.json', 'materials/../materials/rusty-metal.json', 'a//b.json']) {
+ await assertRefused(context, manifest => { manifest.contents.materials[0].file = file; }, /materials\[0\]\.file: got .*; expected a relative path inside the pack/);
+ }
+});
+
+test('a symbolic link in the pack is refused', async context => {
+ const parent = temporaryFolder(context);
+ const folder = installPack(parent, 'linked');
+ try {
+ symlinkSync(join(folder, 'materials/rusty-metal.json'), join(folder, 'materials/link.json'));
+ } catch (error) {
+ context.skip(`cannot create symbolic links here: ${error.code}`);
+ return;
+ }
+ await assert.rejects(() => loadFrom(folder), /pack "linked" materials\/link\.json: got "a symbolic link"; expected a regular file/);
+});
+
+test('duplicate ids and unknown keys are refused', async context => {
+ await assertRefused(context, manifest => { manifest.contents.materials[1].id = 'rusty-metal'; }, /materials\[1\]\.id: got "rusty-metal"; expected an id used once/);
+ await assertRefused(context, manifest => { manifest.scripts = { build: 'x' }; }, /67js-pack\.json\.scripts: got \{"build":"x"\}; expected no such key/);
+ await assertRefused(context, manifest => { manifest.contents.materials[0].url = 'x'; }, /materials\[0\]\.url: got "x"; expected no such key/);
+ await assertRefused(context, manifest => { manifest.contents.recipes[0].id = 'Not Kebab'; }, /recipes\[0\]\.id: got "Not Kebab"; expected a kebab-case id/);
+ await assertRefused(context, manifest => { manifest.contents.materials[0].file = 'previews/crates.png'; }, /materials\[0\]\.file: got "previews\/crates\.png"; expected a file ending in \.json/);
+});
+
+test('a listed file that is missing, and a kind mismatch, are refused', async context => {
+ await assertRefused(context, manifest => { manifest.contents.looks[0].file = 'looks/missing.cube'; }, /looks\[0\]\.file: got "looks\/missing\.cube"; expected a file that exists/);
+ await assertRefused(context, manifest => { manifest.contents.images = [{ id: 'warm-image', file: 'looks/warm.cube' }]; }, /images\[0\]\.file: got "looks\/warm\.cube"; expected a file ending in \.png/);
+ await assertRefused(context, manifest => { manifest.contents.looks = Array.from({ length: MAXIMUM_PACK_ITEMS_PER_KIND + 1 }, (_, index) => ({ id: `look-${index}`, file: 'looks/warm.cube' })); }, /contents\.looks: .*at most 64 items/);
+});
+
+test('semver ranges cover >=, >, <, <=, =, ^, ~ and space-AND', () => {
+ const cases = [
+ ['0.19.0', '>=0.19.0', true], ['0.19.0', '>0.19.0', false], ['0.19.1', '>0.19.0', true], ['0.19.0', '<0.20', true],
+ ['0.20.0', '<0.20', false], ['0.19.0', '<=0.19.0', true], ['0.19.0', '<=0.18', false], ['0.19.5', '^0.19.0', true],
+ ['0.20.0', '^0.19.0', false], ['1.4.0', '^1.2', true], ['2.0.0', '^1.2', false], ['0.19.9', '~0.19.1', true],
+ ['0.20.0', '~0.19.1', false], ['1.9.0', '~1', true], ['0.19.0', '>=0.18.0 <1.0.0', true], ['1.0.0', '>=0.18.0 <1.0.0', false],
+ ['0.19.0', '=0.19.0', true], ['0.19.1', '0.19.0', false], ['0.19.0', '0.19', true],
+ ];
+ for (const [version, range, expected] of cases) assert.equal(semverSatisfies(version, range), expected, `${version} ${range}`);
+ for (const range of ['', 'abc', '>=1.0.0 ||2', '>=', '1.2.3.4', 'x'.repeat(65), '>=1 '.repeat(9)]) assert.equal(semverSatisfies('1.0.0', range), null, range);
+});
+
+test('manifest checks name the pack, the field and what to pass', () => {
+ const valid = JSON.parse(readFileSync(join(EXAMPLE, '67js-pack.json'), 'utf8'));
+ assert.equal(validatePackManifest(valid, { label: 'x', packageVersion }).name, 'example-starter');
+ assert.throws(() => validatePackManifest({ ...valid, version: '1.0' }, { label: 'x', packageVersion }), /pack "x" 67js-pack\.json\.version: got "1\.0"; expected a version of three numbers/);
+ assert.throws(() => validatePackManifest({ ...valid, format: 'other' }, { label: 'x', packageVersion }), /\.format: got "other"; expected "67js\.pack"/);
+});
+
+test('loadPacks skips a bad pack, reports why, and rejects a repeated name', async context => {
+ const parent = temporaryFolder(context);
+ installPack(parent, 'good');
+ installPack(parent, 'copy-of-good');
+ installPack(parent, 'broken', manifest => { manifest.engines['67js'] = '>=99'; });
+ const { packs, rejected } = await loadPacks(parent, { packageVersion });
+ assert.deepEqual(packs.map(pack => pack.folder), ['copy-of-good']);
+ assert.equal(rejected.length, 2);
+ assert.match(rejected.find(entry => entry.folder === 'broken').error, /engines\.67js/);
+ assert.match(rejected.find(entry => entry.folder === 'good').error, /another installed pack already uses the name "example-starter"/);
+});
+
+async function connect(context, runtime) {
+ const server = createAgentMcpServer(runtime);
+ const client = new Client({ name: 'packs-test', version: '1' });
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ await server.connect(serverTransport);
+ await client.connect(clientTransport);
+ context.after(async () => {
+ await client.close();
+ await server.close();
+ });
+ return client;
+}
+
+test('scene_asset_catalog lists installed packs and reads a recipe and a material from one', async context => {
+ const parent = temporaryFolder(context);
+ installPack(parent, 'example-starter', (manifest, root) => {
+ mkdirSync(join(root, 'models'));
+ writeFileSync(join(root, 'models/crate.glb'), tinyGlb());
+ manifest.contents.assets = [{ id: 'crate', file: 'models/crate.glb' }];
+ });
+ installPack(parent, 'old-pack', manifest => { manifest.engines['67js'] = '<0.1.0'; });
+ const runtime = createAgentRuntime({ packs: parent, previewUrl: new URL('file:///unused.js') });
+ context.after(() => runtime.close());
+ const client = await connect(context, runtime);
+ const listing = JSON.parse((await client.callTool({ name: 'scene_asset_catalog', arguments: {} })).content[0].text);
+ assert.equal(listing.configured, true);
+ const [pack] = listing.packs.packs;
+ assert.equal(pack.name, 'example-starter');
+ assert.equal(pack.license, 'CC0-1.0');
+ assert.deepEqual(pack.items.materials.map(item => item.id), ['rusty-metal', 'warm-plaster']);
+ assert.equal(listing.packs.rejected[0].folder, 'old-pack');
+ const crateId = pack.items.assets[0].assetId;
+ assert.ok(listing.assets.some(asset => asset.assetId === crateId && asset.kind === 'glb'), 'pack GLBs join the catalog under the same IDs');
+ const recipe = JSON.parse((await client.callTool({ name: 'scene_asset_catalog', arguments: { pack: 'example-starter', recipe: 'crates' } })).content[0].text);
+ assert.equal(recipe.json.format, '67js.scene');
+ const material = JSON.parse((await client.callTool({ name: 'scene_asset_catalog', arguments: { pack: 'example-starter', material: 'rusty-metal' } })).content[0].text);
+ assert.equal(material.json.metallic, 0.85);
+ for (const argumentsValue of [{ recipe: 'crates' }, { pack: 'example-starter' }, { pack: 'example-starter', recipe: 'crates', material: 'rusty-metal' }, { pack: 'example-starter', recipe: 'nope' }, { pack: '../x', recipe: 'crates' }, { path: '/etc' }, { url: 'https://example.test/pack.zip' }]) {
+ const rejected = await client.callTool({ name: 'scene_asset_catalog', arguments: argumentsValue }).catch(error => ({ isError: true, message: error.message }));
+ assert.equal(rejected.isError, true, JSON.stringify(argumentsValue));
+ }
+ const topic = JSON.parse((await client.callTool({ name: 'scene_capabilities', arguments: { topic: 'packs' } })).content[0].text);
+ assert.equal(JSON.stringify(topic).includes('67js.pack'), true);
+});