@bendyline/molen-tooling 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/README.md +22 -4
  2. package/dist/capture/harness.js +216 -216
  3. package/dist/capture/worldgen-preview.js +288 -288
  4. package/dist/cli.mjs +134 -12
  5. package/dist/docs-src/guide/3d-art-guidelines.md +2 -2
  6. package/dist/docs-src/guide/3d-model-assets.md +49 -13
  7. package/dist/docs-src/guide/adaptive-performance.md +4 -0
  8. package/dist/docs-src/guide/agent-loop.md +6 -6
  9. package/dist/docs-src/guide/aircraft.md +25 -17
  10. package/dist/docs-src/guide/audio.md +247 -0
  11. package/dist/docs-src/guide/browser-mount.md +17 -1
  12. package/dist/docs-src/guide/building-interiors.md +7 -5
  13. package/dist/docs-src/guide/determinism.md +27 -22
  14. package/dist/docs-src/guide/earth-view.md +444 -0
  15. package/dist/docs-src/guide/entities.md +17 -6
  16. package/dist/docs-src/guide/examples.md +39 -23
  17. package/dist/docs-src/guide/experience-playback.md +2 -3
  18. package/dist/docs-src/guide/game-samples.md +50 -21
  19. package/dist/docs-src/guide/graphics-performance.md +40 -8
  20. package/dist/docs-src/guide/input.md +9 -0
  21. package/dist/docs-src/guide/markers.md +52 -0
  22. package/dist/docs-src/guide/materials.md +10 -3
  23. package/dist/docs-src/guide/navigation.md +144 -0
  24. package/dist/docs-src/guide/project.md +23 -3
  25. package/dist/docs-src/guide/quickstart.md +39 -30
  26. package/dist/docs-src/guide/recognizable-places.md +24 -17
  27. package/dist/docs-src/guide/rendering-backends.md +5 -4
  28. package/dist/docs-src/guide/scripting.md +8 -4
  29. package/dist/docs-src/guide/sky.md +26 -9
  30. package/dist/docs-src/guide/source-bundles.md +0 -1
  31. package/dist/docs-src/guide/structure-library.md +20 -10
  32. package/dist/docs-src/guide/terrain.md +51 -6
  33. package/dist/docs-src/guide/vehicles.md +27 -14
  34. package/dist/docs-src/guide/worldgen.md +34 -24
  35. package/dist/docs-src/llms.txt +35 -18
  36. package/dist/docs-src/schemas/README.md +4 -1
  37. package/dist/docs-src/schemas/archive-set.md +175 -0
  38. package/dist/docs-src/schemas/components.md +1104 -1
  39. package/dist/docs-src/schemas/matgraph.md +6 -0
  40. package/dist/docs-src/schemas/soundbank.md +251 -0
  41. package/dist/docs-src/schemas/structure-placements.md +496 -0
  42. package/dist/docs-src/schemas/terrain-package.md +120 -0
  43. package/dist/index.d.mts +31 -3
  44. package/dist/index.mjs +2 -2
  45. package/dist/{mcp-BFnCWrg0.mjs → mcp-BTVwVKFb.mjs} +78 -4
  46. package/dist/{ops-BGxhSP6w.mjs → ops-BPdHodFR.mjs} +1181 -61
  47. package/dist/templates/city-courier/README.md +66 -0
  48. package/dist/templates/city-courier/checks.json +20 -0
  49. package/dist/templates/city-courier/commands.json +32 -0
  50. package/dist/templates/city-courier/delivery-run.replay.json +214 -0
  51. package/dist/templates/city-courier/gen/molen-types.ts +1016 -0
  52. package/dist/templates/city-courier/index.html +2 -0
  53. package/dist/templates/city-courier/package.json +26 -0
  54. package/dist/templates/city-courier/project.json +8 -0
  55. package/dist/templates/city-courier/scene.json +3474 -0
  56. package/dist/templates/city-courier/scripts/game.ts +131 -0
  57. package/dist/templates/city-courier/scripts/molen-scripts.d.ts +1288 -0
  58. package/dist/templates/city-courier/scripts/tsconfig.json +16 -0
  59. package/dist/templates/city-courier/src/audio.ts +96 -0
  60. package/dist/templates/city-courier/src/game-shell.css +317 -0
  61. package/dist/templates/city-courier/src/main.ts +84 -0
  62. package/dist/templates/city-courier/src/scene.ts +17 -0
  63. package/dist/templates/city-courier/src/vite-env.d.ts +1 -0
  64. package/dist/templates/city-courier/src/worker.ts +5 -0
  65. package/dist/templates/city-courier/test/headless.test.ts +95 -0
  66. package/dist/templates/city-courier/test/playthrough.test.js +52 -0
  67. package/dist/templates/city-courier/test/replay.test.ts +22 -0
  68. package/dist/templates/city-courier/tsconfig.json +17 -0
  69. package/dist/templates/city-courier/vite.config.ts +19 -0
  70. package/dist/templates/cubes/README.md +51 -0
  71. package/dist/templates/cubes/index.html +16 -0
  72. package/dist/templates/cubes/package.json +24 -0
  73. package/dist/templates/cubes/scene.json +15 -0
  74. package/dist/templates/cubes/src/cubes.ts +100 -0
  75. package/dist/templates/cubes/src/main.ts +21 -0
  76. package/dist/templates/cubes/src/worker.ts +15 -0
  77. package/dist/templates/cubes/test/headless.test.ts +98 -0
  78. package/dist/templates/cubes/tsconfig.json +17 -0
  79. package/dist/templates/cubes/vite.config.ts +17 -0
  80. package/dist/templates/data-viz/README.md +47 -0
  81. package/dist/templates/data-viz/camera-track.json +12 -0
  82. package/dist/templates/data-viz/data.json +9 -0
  83. package/dist/templates/data-viz/index.html +16 -0
  84. package/dist/templates/data-viz/package.json +25 -0
  85. package/dist/templates/data-viz/scene.json +7 -0
  86. package/dist/templates/data-viz/src/main.ts +39 -0
  87. package/dist/templates/data-viz/src/viz.ts +91 -0
  88. package/dist/templates/data-viz/src/worker.ts +12 -0
  89. package/dist/templates/data-viz/test/headless.test.ts +75 -0
  90. package/dist/templates/data-viz/tsconfig.json +17 -0
  91. package/dist/templates/data-viz/vite.config.ts +16 -0
  92. package/dist/templates/figures-gallery/README.md +46 -0
  93. package/dist/templates/figures-gallery/index.html +16 -0
  94. package/dist/templates/figures-gallery/package.json +25 -0
  95. package/dist/templates/figures-gallery/scene.json +276 -0
  96. package/dist/templates/figures-gallery/src/main.ts +44 -0
  97. package/dist/templates/figures-gallery/src/worker.ts +17 -0
  98. package/dist/templates/figures-gallery/test/headless.test.ts +90 -0
  99. package/dist/templates/figures-gallery/tsconfig.json +17 -0
  100. package/dist/templates/figures-gallery/vite.config.ts +17 -0
  101. package/dist/templates/index.json +191 -0
  102. package/dist/templates/skybound/README.md +66 -0
  103. package/dist/templates/skybound/checks.json +24 -0
  104. package/dist/templates/skybound/commands.json +32 -0
  105. package/dist/templates/skybound/first-leap.replay.json +224 -0
  106. package/dist/templates/skybound/gen/molen-types.ts +1016 -0
  107. package/dist/templates/skybound/index.html +2 -0
  108. package/dist/templates/skybound/package.json +26 -0
  109. package/dist/templates/skybound/project.json +8 -0
  110. package/dist/templates/skybound/scene.json +1777 -0
  111. package/dist/templates/skybound/scripts/game.ts +122 -0
  112. package/dist/templates/skybound/scripts/molen-scripts.d.ts +1288 -0
  113. package/dist/templates/skybound/scripts/tsconfig.json +16 -0
  114. package/dist/templates/skybound/src/audio.ts +96 -0
  115. package/dist/templates/skybound/src/game-shell.css +317 -0
  116. package/dist/templates/skybound/src/main.ts +63 -0
  117. package/dist/templates/skybound/src/scene.ts +17 -0
  118. package/dist/templates/skybound/src/vite-env.d.ts +1 -0
  119. package/dist/templates/skybound/src/worker.ts +5 -0
  120. package/dist/templates/skybound/test/headless.test.ts +124 -0
  121. package/dist/templates/skybound/test/playthrough.test.js +38 -0
  122. package/dist/templates/skybound/test/replay.test.ts +22 -0
  123. package/dist/templates/skybound/tsconfig.json +17 -0
  124. package/dist/templates/skybound/vite.config.ts +19 -0
  125. package/dist/templates/terrain-flyover/README.md +46 -0
  126. package/dist/templates/terrain-flyover/index.html +16 -0
  127. package/dist/templates/terrain-flyover/package.json +26 -0
  128. package/dist/templates/terrain-flyover/src/flyover.ts +23 -0
  129. package/dist/templates/terrain-flyover/src/main.ts +93 -0
  130. package/dist/templates/terrain-flyover/terrain.json +15 -0
  131. package/dist/templates/terrain-flyover/test/headless.test.ts +72 -0
  132. package/dist/templates/terrain-flyover/tsconfig.json +17 -0
  133. package/dist/templates/terrain-flyover/vite.config.ts +15 -0
  134. package/dist/templates/top-down-arena/README.md +65 -0
  135. package/dist/templates/top-down-arena/arena-skirmish.replay.json +204 -0
  136. package/dist/templates/top-down-arena/index.html +16 -0
  137. package/dist/templates/top-down-arena/package.json +26 -0
  138. package/dist/templates/top-down-arena/project.json +10 -0
  139. package/dist/templates/top-down-arena/scene.json +182 -0
  140. package/dist/templates/top-down-arena/scripts/chase.ts +17 -0
  141. package/dist/templates/top-down-arena/scripts/combat.ts +13 -0
  142. package/dist/templates/top-down-arena/scripts/control.ts +8 -0
  143. package/dist/templates/top-down-arena/scripts/molen-scripts.d.ts +1258 -0
  144. package/dist/templates/top-down-arena/scripts/spawner.ts +11 -0
  145. package/dist/templates/top-down-arena/scripts/tsconfig.json +16 -0
  146. package/dist/templates/top-down-arena/src/arena.ts +8 -0
  147. package/dist/templates/top-down-arena/src/audio.ts +96 -0
  148. package/dist/templates/top-down-arena/src/gen/molen-types.ts +1020 -0
  149. package/dist/templates/top-down-arena/src/main.ts +34 -0
  150. package/dist/templates/top-down-arena/src/scene.ts +24 -0
  151. package/dist/templates/top-down-arena/src/vite-env.d.ts +1 -0
  152. package/dist/templates/top-down-arena/src/worker.ts +7 -0
  153. package/dist/templates/top-down-arena/test/headless.test.ts +87 -0
  154. package/dist/templates/top-down-arena/test/replay.test.ts +22 -0
  155. package/dist/templates/top-down-arena/tsconfig.json +17 -0
  156. package/dist/templates/top-down-arena/types/arena.types.json +54 -0
  157. package/dist/templates/top-down-arena/vite.config.ts +21 -0
  158. package/package.json +14 -14
@@ -10,20 +10,21 @@ import { createPlacesContent, createRegionResolver, semanticTileToBatch, tileGro
10
10
  import { evaluateCameraTrack, registerCameraTrackSchema } from "@bendyline/molen-client/camera-track";
11
11
  import { createReadStream, watch } from "node:fs";
12
12
  import { createServer } from "node:http";
13
- import { buildTypeIndex, checkTypes, componentMapIssues, componentNames, createComponentRegistry, decodeCollisionTrimesh, detectKind, encodeCollisionTrimesh, formatIssues, getComponent, getSchema, listComponents, listSchemas, namespaceCovers, registerSchema, resolveAllTypes, sceneTypeRefIssues, schemaKinds, validate, validateByKind } from "@bendyline/molen-schema";
13
+ import { audioSignalIssues, audioSignalRefs, audioSoundRefs, buildTypeIndex, checkTypes, componentMapIssues, componentNames, createComponentRegistry, decodeCollisionTrimesh, detectKind, encodeCollisionTrimesh, formatIssues, getComponent, getSchema, listComponents, listSchemas, namespaceCovers, nearestWithDistance, registerSchema, resolveAllTypes, sceneTypeRefIssues, schemaKinds, validate, validateByKind, weatherProfile } from "@bendyline/molen-schema";
14
14
  import { z } from "zod";
15
15
  import { createHash, randomUUID } from "node:crypto";
16
16
  import { Node, NodeIO, getBounds } from "@gltf-transform/core";
17
17
  import { ALL_EXTENSIONS, KHRTextureBasisu } from "@gltf-transform/extensions";
18
- import { dedup, getTextureColorSpace, listTextureSlots, prune, quantize, weld } from "@gltf-transform/functions";
18
+ import { dedup, getTextureColorSpace, listTextureInfoByMaterial, listTextureSlots, prune, quantize, weld } from "@gltf-transform/functions";
19
19
  import { fileURLToPath, pathToFileURL } from "node:url";
20
20
  import { stripScriptTypes } from "@bendyline/molen-client/vite";
21
- import { ENGINE_VERSION, STATE_FORMAT, World, applyKeyframeTo, buildWorld, contentDrift, dmath, installGameplay, isExperience, keyframeStateFormat, stateHash, takeKeyframe, worldFromKeyframe } from "@bendyline/molen-kernel";
21
+ import { ENGINE_VERSION, STATE_FORMAT, World, applyKeyframeTo, buildWorld, contentDrift, dmath, installGameplay, isExperience, keyframeStateFormat, quatRotateVec3, stateHash, takeKeyframe, worldFromKeyframe } from "@bendyline/molen-kernel";
22
22
  import { homedir, tmpdir } from "node:os";
23
23
  import { createTypeLibrary } from "@bendyline/molen-kernel/content";
24
24
  import { createPackSet, openPack, sha256 } from "@bendyline/molen-pack";
25
- import { PACK_SOURCE_FILE, buildPack, extractPack, openPackAt } from "@bendyline/molen-pack/node";
25
+ import { PACK_SOURCE_FILE, buildPack, extractPack, openPackAt, recordInPackIndex } from "@bendyline/molen-pack/node";
26
26
  import { installTerrain, terrainScriptApi } from "@bendyline/molen-kernel/terrain";
27
+ import { AudioDirector, entitySourceFromWorld, mergeSoundbanks } from "@bendyline/molen-client/audio";
27
28
  import { diffKeyframes, firstDivergentTick, formatAssertionResults, perTickHashes, runAssertions, runHeadless } from "@bendyline/molen-kernel/testing";
28
29
  import { hashJson } from "@bendyline/molen-kernel/determinism";
29
30
  import { PMTiles } from "pmtiles";
@@ -1061,6 +1062,67 @@ function buildStats(doc, sizeBytes) {
1061
1062
  };
1062
1063
  }
1063
1064
  const NODE_CAP = 128;
1065
+ /** Only the explicit, supported extras contract makes unused UV0 meaningful at runtime. */
1066
+ function sharedSurfaceRef(material) {
1067
+ const value = material?.getExtras().molenSurface;
1068
+ if (value === null || typeof value !== "object") return void 0;
1069
+ const surface = value;
1070
+ return surface.uv === "repeats" && typeof surface.ref === "string" && surface.ref.trim().length > 0 && typeof surface.slot === "string" && [
1071
+ "wall",
1072
+ "roof",
1073
+ "trim",
1074
+ "foundation",
1075
+ "window",
1076
+ "door"
1077
+ ].includes(surface.slot) ? surface.ref : void 0;
1078
+ }
1079
+ /** Keep opted-in UV0 across pruning without retaining unused attributes on other primitives. */
1080
+ async function prunePreservingSharedSurfaceUvs(doc) {
1081
+ const saved = /* @__PURE__ */ new Map();
1082
+ for (const mesh of doc.getRoot().listMeshes()) for (const primitive of mesh.listPrimitives()) {
1083
+ const uv = primitive.getAttribute("TEXCOORD_0");
1084
+ if (sharedSurfaceRef(primitive.getMaterial()) === void 0 || uv === null) continue;
1085
+ let semantic = "_MOLEN_SHARED_UV0";
1086
+ while (primitive.getAttribute(semantic) !== null) semantic += "_";
1087
+ primitive.setAttribute(semantic, uv);
1088
+ saved.set(primitive, semantic);
1089
+ }
1090
+ await doc.transform(prune());
1091
+ const groups = /* @__PURE__ */ new Map();
1092
+ for (const mesh of doc.getRoot().listMeshes()) for (const primitive of mesh.listPrimitives()) {
1093
+ const material = primitive.getMaterial();
1094
+ if (material === null || sharedSurfaceRef(material) === void 0) continue;
1095
+ const group = groups.get(material) ?? [];
1096
+ group.push(primitive);
1097
+ groups.set(material, group);
1098
+ }
1099
+ for (const [material, primitives] of groups) {
1100
+ if (primitives.some((primitive) => {
1101
+ const semantic = saved.get(primitive);
1102
+ const uv = primitive.getAttribute("TEXCOORD_0");
1103
+ return uv !== null && (semantic === void 0 || uv !== primitive.getAttribute(semantic));
1104
+ })) {
1105
+ const shiftUvs = (primitive) => {
1106
+ const coordinates = primitive.listSemantics().filter((semantic) => /^TEXCOORD_\d+$/.test(semantic)).map((semantic) => Number(semantic.slice(9))).sort((a, b) => b - a);
1107
+ for (const index of coordinates) {
1108
+ primitive.setAttribute(`TEXCOORD_${index + 1}`, primitive.getAttribute(`TEXCOORD_${index}`));
1109
+ primitive.setAttribute(`TEXCOORD_${index}`, null);
1110
+ }
1111
+ };
1112
+ for (const primitive of primitives) {
1113
+ shiftUvs(primitive);
1114
+ for (const target of primitive.listTargets()) shiftUvs(target);
1115
+ }
1116
+ for (const info of listTextureInfoByMaterial(material)) info.setTexCoord(info.getTexCoord() + 1);
1117
+ }
1118
+ for (const primitive of primitives) {
1119
+ const semantic = saved.get(primitive);
1120
+ if (semantic === void 0) continue;
1121
+ primitive.setAttribute("TEXCOORD_0", primitive.getAttribute(semantic));
1122
+ primitive.setAttribute(semantic, null);
1123
+ }
1124
+ }
1125
+ }
1064
1126
  /**
1065
1127
  * Pick the project.json an import registers into. The source file's surrounding project is NOT a
1066
1128
  * safe default: `molen asset import ../otherproj/models/key.glb` used to write the asset into
@@ -1091,6 +1153,23 @@ async function resolveImportProject(input, sourcePath) {
1091
1153
  async function importAsset(input) {
1092
1154
  const warnings = [];
1093
1155
  try {
1156
+ if (input.assetDir !== void 0 && input.outDir !== void 0) return {
1157
+ ok: false,
1158
+ error: "assetDir and outDir are mutually exclusive; choose an exact bundle directory or an assets root"
1159
+ };
1160
+ if (input.assetDir !== void 0 && input.assetDir.trim().length === 0) return {
1161
+ ok: false,
1162
+ error: "assetDir must not be empty"
1163
+ };
1164
+ if (input.assetDir?.includes("\0")) return {
1165
+ ok: false,
1166
+ error: "assetDir must not contain a null byte"
1167
+ };
1168
+ const id = slug$2(input.id ?? basename(input.path, extname(input.path)));
1169
+ if (id.length === 0) return {
1170
+ ok: false,
1171
+ error: "asset id is empty after slugging"
1172
+ };
1094
1173
  const sourcePath = resolve(input.path);
1095
1174
  const resolved = await resolveImportProject(input, sourcePath);
1096
1175
  if (resolved.error !== void 0) return {
@@ -1099,6 +1178,47 @@ async function importAsset(input) {
1099
1178
  };
1100
1179
  const projectPath = resolved.projectPath;
1101
1180
  if (resolved.warning !== void 0) warnings.push(resolved.warning);
1181
+ let registeredAssets = {};
1182
+ if (projectPath !== void 0) {
1183
+ const project = validate("project", parseJson(await readFile(projectPath, "utf8")));
1184
+ if (!project.ok) return {
1185
+ ok: false,
1186
+ error: project.formatted
1187
+ };
1188
+ registeredAssets = project.value.assets;
1189
+ }
1190
+ const registeredSidecar = input.assetDir === void 0 && input.outDir === void 0 ? registeredAssets[id] : void 0;
1191
+ const assetsRoot = input.outDir ?? (projectPath !== void 0 ? join(dirname(projectPath), "assets") : resolve(input.cwd ?? process.cwd(), "assets"));
1192
+ const dir = input.assetDir !== void 0 ? resolve(input.cwd ?? process.cwd(), input.assetDir) : registeredSidecar !== void 0 && projectPath !== void 0 ? dirname(resolve(dirname(projectPath), registeredSidecar)) : join(assetsRoot, id.replaceAll(".", "/"));
1193
+ const sidecarPath = registeredSidecar !== void 0 && projectPath !== void 0 ? resolve(dirname(projectPath), registeredSidecar) : join(dir, "asset.json");
1194
+ if (projectPath !== void 0) {
1195
+ for (const [registeredId, path] of Object.entries(registeredAssets)) if (registeredId !== id && relative(resolve(dir), dirname(resolve(dirname(projectPath), path))) === "") return {
1196
+ ok: false,
1197
+ error: `${dir} belongs to asset "${registeredId}"; refusing to overwrite it with "${id}"`
1198
+ };
1199
+ }
1200
+ try {
1201
+ if (!(await stat(dir)).isDirectory()) return {
1202
+ ok: false,
1203
+ error: `${dir} is not a directory`
1204
+ };
1205
+ if (input.force !== true) return {
1206
+ ok: false,
1207
+ error: `${dir} already exists; choose another id or pass force: true to replace it`
1208
+ };
1209
+ let existing;
1210
+ try {
1211
+ existing = parseJson(await readFile(sidecarPath, "utf8"));
1212
+ } catch (error) {
1213
+ if (error.code !== "ENOENT" && !(error instanceof SyntaxError)) throw error;
1214
+ }
1215
+ if (existing !== null && typeof existing === "object" && "id" in existing && typeof existing.id === "string" && existing.id !== id) return {
1216
+ ok: false,
1217
+ error: `${dir} belongs to asset "${existing.id}"; refusing to overwrite it with "${id}"`
1218
+ };
1219
+ } catch (error) {
1220
+ if (error.code !== "ENOENT") throw error;
1221
+ }
1102
1222
  const sourceBytes = new Uint8Array(await readFile(sourcePath));
1103
1223
  const io = await createAssetIO();
1104
1224
  let doc;
@@ -1112,7 +1232,13 @@ async function importAsset(input) {
1112
1232
  };
1113
1233
  }
1114
1234
  doc.setLogger(gltfLogger);
1115
- if (input.optimize !== false) await doc.transform(dedup(), prune(), weld(), quantize());
1235
+ const sharedSurfaces = [...new Set(doc.getRoot().listMaterials().map(sharedSurfaceRef).filter((ref) => ref !== void 0))].sort();
1236
+ if (sharedSurfaces.length > 0) warnings.push(`shared surfaces are external runtime dependencies: ${sharedSurfaces.join(", ")}; hosts without these surfaces render the embedded PBR fallback`);
1237
+ if (input.optimize !== false) {
1238
+ await doc.transform(dedup());
1239
+ await prunePreservingSharedSurfaceUvs(doc);
1240
+ await doc.transform(weld(), quantize());
1241
+ }
1116
1242
  const root = doc.getRoot();
1117
1243
  const extensionsUsed = root.listExtensionsUsed().map((e) => e.extensionName);
1118
1244
  const nodeName = (node, i) => {
@@ -1202,21 +1328,6 @@ async function importAsset(input) {
1202
1328
  alphaMode: m.getAlphaMode()
1203
1329
  };
1204
1330
  });
1205
- const id = slug$2(input.id ?? basename(sourcePath, extname(sourcePath)));
1206
- if (id.length === 0) return {
1207
- ok: false,
1208
- error: "asset id is empty after slugging"
1209
- };
1210
- const dir = join(input.outDir ?? (projectPath !== void 0 ? join(dirname(projectPath), "assets") : resolve(input.cwd ?? process.cwd(), "assets")), id.replaceAll(".", "/"));
1211
- try {
1212
- await stat(dir);
1213
- if (input.force !== true) return {
1214
- ok: false,
1215
- error: `${dir} already exists; choose another id or pass force: true to replace it`
1216
- };
1217
- } catch (error) {
1218
- if (error.code !== "ENOENT") throw error;
1219
- }
1220
1331
  await mkdir(dir, { recursive: true });
1221
1332
  const glb = await io.writeBinary(doc);
1222
1333
  await writeFile(join(dir, "model.glb"), glb);
@@ -1279,7 +1390,6 @@ async function importAsset(input) {
1279
1390
  ok: false,
1280
1391
  error: `sidecar failed self-validation:\n${checked.formatted}`
1281
1392
  };
1282
- const sidecarPath = join(dir, "asset.json");
1283
1393
  await writeFile(sidecarPath, `${JSON.stringify(checked.value, null, 2)}\n`);
1284
1394
  try {
1285
1395
  await stat(sidecarPath);
@@ -2090,6 +2200,684 @@ async function stageAssetsImpl(input) {
2090
2200
  };
2091
2201
  }
2092
2202
  //#endregion
2203
+ //#region src/audio-probe.ts
2204
+ function ascii(b, at, len) {
2205
+ return String.fromCharCode(...b.subarray(at, at + len));
2206
+ }
2207
+ function probeWav(b, v) {
2208
+ let at = 12;
2209
+ let byteRate = 0;
2210
+ let sampleRate;
2211
+ let channels;
2212
+ while (at + 8 <= b.length) {
2213
+ const id = ascii(b, at, 4);
2214
+ const size = v.getUint32(at + 4, true);
2215
+ if (id === "fmt ") {
2216
+ channels = v.getUint16(at + 10, true);
2217
+ sampleRate = v.getUint32(at + 12, true);
2218
+ byteRate = v.getUint32(at + 16, true);
2219
+ } else if (id === "data" && byteRate > 0) return {
2220
+ format: "wav",
2221
+ durationS: Math.min(size, b.length - at - 8) / byteRate,
2222
+ ...sampleRate !== void 0 ? { sampleRate } : {},
2223
+ ...channels !== void 0 ? { channels } : {}
2224
+ };
2225
+ at += 8 + size + (size & 1);
2226
+ }
2227
+ return { format: "wav" };
2228
+ }
2229
+ function probeOgg(b, v) {
2230
+ let rate;
2231
+ let channels;
2232
+ let preSkip = 0;
2233
+ let opus = false;
2234
+ const head = ascii(b, 0, Math.min(b.length, 256));
2235
+ const vorbis = head.indexOf("vorbis");
2236
+ const opusHead = head.indexOf("OpusHead");
2237
+ if (vorbis >= 0) {
2238
+ channels = b[vorbis + 11];
2239
+ rate = v.getUint32(vorbis + 12, true);
2240
+ } else if (opusHead >= 0) {
2241
+ opus = true;
2242
+ channels = b[opusHead + 9];
2243
+ preSkip = v.getUint16(opusHead + 10, true);
2244
+ rate = 48e3;
2245
+ }
2246
+ for (let at = b.length - 27; at >= 0; at--) if (b[at] === 79 && ascii(b, at, 4) === "OggS") {
2247
+ const granule = Number(v.getBigUint64(at + 6, true));
2248
+ if (rate && granule > 0) return {
2249
+ format: "ogg",
2250
+ durationS: (granule - (opus ? preSkip : 0)) / rate,
2251
+ sampleRate: opus ? v.getUint32(opusHead + 12, true) || 48e3 : rate,
2252
+ ...channels !== void 0 ? { channels } : {}
2253
+ };
2254
+ break;
2255
+ }
2256
+ return { format: "ogg" };
2257
+ }
2258
+ const MP3_BITRATES_V1 = [
2259
+ 0,
2260
+ 32,
2261
+ 40,
2262
+ 48,
2263
+ 56,
2264
+ 64,
2265
+ 80,
2266
+ 96,
2267
+ 112,
2268
+ 128,
2269
+ 160,
2270
+ 192,
2271
+ 224,
2272
+ 256,
2273
+ 320
2274
+ ];
2275
+ const MP3_BITRATES_V2 = [
2276
+ 0,
2277
+ 8,
2278
+ 16,
2279
+ 24,
2280
+ 32,
2281
+ 40,
2282
+ 48,
2283
+ 56,
2284
+ 64,
2285
+ 80,
2286
+ 96,
2287
+ 112,
2288
+ 128,
2289
+ 144,
2290
+ 160
2291
+ ];
2292
+ const MP3_RATES = {
2293
+ 3: [
2294
+ 44100,
2295
+ 48e3,
2296
+ 32e3
2297
+ ],
2298
+ 2: [
2299
+ 22050,
2300
+ 24e3,
2301
+ 16e3
2302
+ ],
2303
+ 0: [
2304
+ 11025,
2305
+ 12e3,
2306
+ 8e3
2307
+ ]
2308
+ };
2309
+ function probeMp3(b, v) {
2310
+ let at = 0;
2311
+ if (ascii(b, 0, 3) === "ID3") at = 10 + ((b[6] ?? 0) << 21 | (b[7] ?? 0) << 14 | (b[8] ?? 0) << 7 | (b[9] ?? 0));
2312
+ for (; at + 4 < b.length; at++) {
2313
+ if (b[at] !== 255 || ((b[at + 1] ?? 0) & 224) !== 224) continue;
2314
+ const h = v.getUint32(at, false);
2315
+ const version = h >>> 19 & 3;
2316
+ const layer = h >>> 17 & 3;
2317
+ const bitrateIndex = h >>> 12 & 15;
2318
+ const rateIndex = h >>> 10 & 3;
2319
+ if (version === 1 || layer !== 1 || bitrateIndex === 0 || bitrateIndex === 15 || rateIndex === 3) continue;
2320
+ const sampleRate = MP3_RATES[version][rateIndex];
2321
+ const mono = (h >>> 6 & 3) === 3;
2322
+ const v1 = version === 3;
2323
+ const samplesPerFrame = v1 ? 1152 : 576;
2324
+ const sideInfo = v1 ? mono ? 17 : 32 : mono ? 9 : 17;
2325
+ const tag = ascii(b, at + 4 + sideInfo, 4);
2326
+ const channels = mono ? 1 : 2;
2327
+ if (tag === "Xing" || tag === "Info") {
2328
+ if (v.getUint32(at + 8 + sideInfo, false) & 1) return {
2329
+ format: "mp3",
2330
+ durationS: v.getUint32(at + 12 + sideInfo, false) * samplesPerFrame / sampleRate,
2331
+ sampleRate,
2332
+ channels
2333
+ };
2334
+ }
2335
+ const kbps = (v1 ? MP3_BITRATES_V1 : MP3_BITRATES_V2)[bitrateIndex] * 1e3;
2336
+ return {
2337
+ format: "mp3",
2338
+ durationS: (b.length - at) * 8 / kbps,
2339
+ sampleRate,
2340
+ channels
2341
+ };
2342
+ }
2343
+ return { format: "mp3" };
2344
+ }
2345
+ /** Probe a clip's header for duration, sample rate and channel count. */
2346
+ function probeAudio(bytes) {
2347
+ const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
2348
+ if (bytes.length >= 12 && ascii(bytes, 0, 4) === "RIFF" && ascii(bytes, 8, 4) === "WAVE") return probeWav(bytes, v);
2349
+ if (bytes.length >= 27 && ascii(bytes, 0, 4) === "OggS") return probeOgg(bytes, v);
2350
+ if (bytes.length >= 4 && (ascii(bytes, 0, 3) === "ID3" || bytes[0] === 255 && ((bytes[1] ?? 0) & 224) === 224)) return probeMp3(bytes, v);
2351
+ return { format: "unknown" };
2352
+ }
2353
+ //#endregion
2354
+ //#region src/ops/audio-check.ts
2355
+ const fail$3 = (error) => ({
2356
+ ok: false,
2357
+ sounds: 0,
2358
+ clips: 0,
2359
+ bytes: 0,
2360
+ licenses: {},
2361
+ issues: [],
2362
+ error
2363
+ });
2364
+ /** Validate a sound bank and every clip it names: present, hash, duration, loop points. */
2365
+ function checkSoundbank(input) {
2366
+ return guardOp(fail$3, () => checkSoundbankImpl(input));
2367
+ }
2368
+ async function checkSoundbankImpl(input) {
2369
+ const bankPath = resolve(input.bankPath);
2370
+ const v = validate("soundbank", parseJson(await readFile(bankPath, "utf8")));
2371
+ if (!v.ok) return fail$3(v.formatted);
2372
+ const bank = v.value;
2373
+ const dir = dirname(bankPath);
2374
+ const issues = [];
2375
+ const licenses = {};
2376
+ let clips = 0;
2377
+ let bytes = 0;
2378
+ for (const [id, entry] of Object.entries(bank.sounds)) {
2379
+ const at = `/sounds/${id}`;
2380
+ licenses[entry.source.license] = (licenses[entry.source.license] ?? 0) + 1;
2381
+ if (!entry.description) issues.push({
2382
+ path: at,
2383
+ message: "no description (agents choose sounds by it)",
2384
+ severity: "notice"
2385
+ });
2386
+ if (!entry.source.url && !entry.source.prompt && !entry.source.site) issues.push({
2387
+ path: `${at}/source`,
2388
+ message: "no origin: add url, site or prompt",
2389
+ severity: "notice"
2390
+ });
2391
+ for (const [i, clip] of entry.clips.entries()) {
2392
+ let data;
2393
+ try {
2394
+ data = new Uint8Array(await readFile(join(dir, clip)));
2395
+ } catch {
2396
+ issues.push({
2397
+ path: `${at}/clips/${i}`,
2398
+ message: `missing file ${clip}`,
2399
+ severity: "error"
2400
+ });
2401
+ continue;
2402
+ }
2403
+ clips++;
2404
+ bytes += data.length;
2405
+ if (i === 0 && entry.hash) {
2406
+ if (`sha256:${createHash("sha256").update(data).digest("hex")}` !== entry.hash) issues.push({
2407
+ path: `${at}/hash`,
2408
+ message: `${clip} changed since import`,
2409
+ severity: "error"
2410
+ });
2411
+ }
2412
+ const probe = probeAudio(data);
2413
+ if (i === 0 && entry.durationS !== void 0 && probe.durationS !== void 0) {
2414
+ if (Math.abs(probe.durationS - entry.durationS) > .1) issues.push({
2415
+ path: `${at}/durationS`,
2416
+ message: `durationS ${entry.durationS} but ${clip} is ${probe.durationS.toFixed(3)}s`,
2417
+ severity: "error"
2418
+ });
2419
+ }
2420
+ if (entry.loopEnd !== void 0 && probe.durationS !== void 0 && entry.loopEnd > probe.durationS + .01) issues.push({
2421
+ path: `${at}/loopEnd`,
2422
+ message: `loopEnd ${entry.loopEnd} is past the end of ${clip} (${probe.durationS.toFixed(3)}s)`,
2423
+ severity: "error"
2424
+ });
2425
+ }
2426
+ }
2427
+ return {
2428
+ ok: !issues.some((i) => i.severity === "error"),
2429
+ id: bank.id,
2430
+ sounds: Object.keys(bank.sounds).length,
2431
+ clips,
2432
+ bytes,
2433
+ licenses,
2434
+ issues
2435
+ };
2436
+ }
2437
+ //#endregion
2438
+ //#region src/ops/audio-import.ts
2439
+ const fail$2 = (error) => ({
2440
+ ok: false,
2441
+ bankPath: "",
2442
+ warnings: [],
2443
+ error
2444
+ });
2445
+ /** Add a clip to a sound bank: copy it beside the bank, hash and probe it, record provenance. */
2446
+ function importSound(input) {
2447
+ return guardOp(fail$2, () => importSoundImpl(input));
2448
+ }
2449
+ async function importSoundImpl(input) {
2450
+ const warnings = [];
2451
+ const bankPath = resolve(input.bankPath);
2452
+ const bankDir = dirname(bankPath);
2453
+ let bank;
2454
+ try {
2455
+ bank = parseJson(await readFile(bankPath, "utf8"));
2456
+ } catch (e) {
2457
+ if (e.code !== "ENOENT") throw e;
2458
+ bank = {
2459
+ format: "molen/soundbank@1",
2460
+ id: basename(bankDir),
2461
+ sounds: {}
2462
+ };
2463
+ warnings.push(`created ${bankPath}`);
2464
+ }
2465
+ const src = resolve(input.file);
2466
+ const bytes = new Uint8Array(await readFile(src));
2467
+ const inside = !relative(bankDir, src).startsWith("..") && !isAbsolute(relative(bankDir, src));
2468
+ let clip;
2469
+ if (inside) clip = relative(bankDir, src).split(sep).join("/");
2470
+ else {
2471
+ const dir = input.copyTo ?? "audio";
2472
+ clip = `${dir}/${basename(src)}`;
2473
+ await mkdir(join(bankDir, dir), { recursive: true });
2474
+ await copyFile(src, join(bankDir, clip));
2475
+ }
2476
+ const probe = probeAudio(bytes);
2477
+ if (probe.format === "unknown") warnings.push(`${basename(src)}: unrecognized audio format`);
2478
+ if (probe.format !== "mp3" && probe.format !== "unknown") warnings.push(`${basename(src)} is ${probe.format}; MP3 is the one format every browser decodes`);
2479
+ const durationS = input.durationS ?? probe.durationS;
2480
+ const hash = `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
2481
+ const previous = bank.sounds[input.id];
2482
+ const source = {
2483
+ license: input.license,
2484
+ ...input.site !== void 0 ? { site: input.site } : {},
2485
+ ...input.source !== void 0 ? { url: input.source } : {},
2486
+ ...input.author !== void 0 ? { author: input.author } : {},
2487
+ ...input.prompt !== void 0 ? { prompt: input.prompt } : {},
2488
+ ...input.generator !== void 0 ? { generator: input.generator } : {}
2489
+ };
2490
+ let entry;
2491
+ if (input.append && previous) {
2492
+ if (previous.clips.includes(clip)) return {
2493
+ ...fail$2(`${clip} is already a clip of ${input.id}`),
2494
+ bankPath
2495
+ };
2496
+ entry = {
2497
+ ...previous,
2498
+ clips: [...previous.clips, clip]
2499
+ };
2500
+ } else {
2501
+ entry = {
2502
+ clips: [clip],
2503
+ ...input.description !== void 0 ? { description: input.description } : {},
2504
+ ...input.loop !== void 0 ? { loop: input.loop } : {},
2505
+ ...input.loopStart !== void 0 ? { loopStart: input.loopStart } : {},
2506
+ ...input.loopEnd !== void 0 ? { loopEnd: input.loopEnd } : {},
2507
+ ...input.gain !== void 0 ? { gain: input.gain } : {},
2508
+ ...input.bus !== void 0 ? { bus: input.bus } : {},
2509
+ ...durationS !== void 0 ? { durationS: Math.round(durationS * 1e3) / 1e3 } : {},
2510
+ hash,
2511
+ source
2512
+ };
2513
+ if (previous) warnings.push(`replaced existing sound ${input.id}`);
2514
+ }
2515
+ if (durationS === void 0) warnings.push("duration unknown; pass --duration for music tracks");
2516
+ const next = {
2517
+ ...bank,
2518
+ sounds: {
2519
+ ...bank.sounds,
2520
+ [input.id]: entry
2521
+ }
2522
+ };
2523
+ const checked = validate("soundbank", next);
2524
+ if (!checked.ok) return {
2525
+ ...fail$2(checked.formatted),
2526
+ bankPath
2527
+ };
2528
+ await writeFile(bankPath, `${JSON.stringify(next, null, 2)}\n`);
2529
+ return {
2530
+ ok: true,
2531
+ bankPath,
2532
+ id: input.id,
2533
+ clip,
2534
+ entry,
2535
+ warnings
2536
+ };
2537
+ }
2538
+ //#endregion
2539
+ //#region src/ops/audio-plan.ts
2540
+ const fail$1 = (error) => ({
2541
+ ok: false,
2542
+ ticks: 0,
2543
+ tickRate: 0,
2544
+ banks: [],
2545
+ voices: [],
2546
+ oneShots: [],
2547
+ events: [],
2548
+ issues: [],
2549
+ warnings: [],
2550
+ timeline: "",
2551
+ error
2552
+ });
2553
+ /** Run a scene headlessly and report the sounds it would play, tick by tick. */
2554
+ function planAudio(input) {
2555
+ return guardOp(fail$1, () => planAudioImpl(input));
2556
+ }
2557
+ function vec(v) {
2558
+ return Array.isArray(v) && v.length === 3 && v.every((x) => typeof x === "number") ? v : void 0;
2559
+ }
2560
+ function towards(from, to) {
2561
+ if (!to) return [
2562
+ 0,
2563
+ 0,
2564
+ -1
2565
+ ];
2566
+ const d = [
2567
+ to[0] - from[0],
2568
+ to[1] - from[1],
2569
+ to[2] - from[2]
2570
+ ];
2571
+ const len = Math.hypot(...d);
2572
+ return len > 1e-9 ? [
2573
+ d[0] / len,
2574
+ d[1] / len,
2575
+ d[2] / len
2576
+ ] : [
2577
+ 0,
2578
+ 0,
2579
+ -1
2580
+ ];
2581
+ }
2582
+ function transformOf(world, id) {
2583
+ const t = world.get(id, { name: "transform" });
2584
+ return {
2585
+ ...vec(t?.pos) ? { pos: vec(t?.pos) } : {},
2586
+ ...Array.isArray(t?.rot) ? { rot: t?.rot } : {}
2587
+ };
2588
+ }
2589
+ /** Where the ears are for a headless run: a named entity, else the scene camera. */
2590
+ function listenerFor(world, manifest, entity) {
2591
+ if (entity !== void 0) {
2592
+ const { pos, rot } = transformOf(world, entity);
2593
+ if (!pos) return {};
2594
+ return {
2595
+ position: pos,
2596
+ forward: rot ? quatRotateVec3(rot, [
2597
+ 0,
2598
+ 0,
2599
+ -1
2600
+ ]) : [
2601
+ 0,
2602
+ 0,
2603
+ -1
2604
+ ],
2605
+ up: [
2606
+ 0,
2607
+ 1,
2608
+ 0
2609
+ ]
2610
+ };
2611
+ }
2612
+ const c = manifest.camera;
2613
+ if (!c) return { position: [
2614
+ 0,
2615
+ 0,
2616
+ 0
2617
+ ] };
2618
+ if (c.mode === "top-down-ortho") return {
2619
+ position: [
2620
+ c.center[0],
2621
+ c.cameraHeight ?? 50,
2622
+ c.center[1]
2623
+ ],
2624
+ forward: [
2625
+ 0,
2626
+ -1,
2627
+ 0
2628
+ ],
2629
+ up: [
2630
+ 0,
2631
+ 0,
2632
+ -1
2633
+ ]
2634
+ };
2635
+ if (c.mode === "follow") {
2636
+ const { pos } = transformOf(world, c.entity);
2637
+ if (!pos) return {};
2638
+ const eye = [
2639
+ pos[0] + c.offset[0],
2640
+ pos[1] + c.offset[1],
2641
+ pos[2] + c.offset[2]
2642
+ ];
2643
+ return {
2644
+ position: eye,
2645
+ forward: towards(eye, [
2646
+ pos[0] + c.lookOffset[0],
2647
+ pos[1] + c.lookOffset[1],
2648
+ pos[2] + c.lookOffset[2]
2649
+ ]),
2650
+ up: [
2651
+ 0,
2652
+ 1,
2653
+ 0
2654
+ ]
2655
+ };
2656
+ }
2657
+ return {
2658
+ position: c.position,
2659
+ forward: towards(c.position, c.lookAt),
2660
+ up: [
2661
+ 0,
2662
+ 1,
2663
+ 0
2664
+ ]
2665
+ };
2666
+ }
2667
+ async function loadBanks(paths, project) {
2668
+ const inputs = [];
2669
+ const labels = [];
2670
+ if (paths && paths.length > 0) {
2671
+ for (const path of paths) {
2672
+ const v = validate("soundbank", parseJson(await readFile(path, "utf8")));
2673
+ if (!v.ok) return `${path}:\n${v.formatted}`;
2674
+ inputs.push({
2675
+ doc: v.value,
2676
+ base: relative(process.cwd(), dirname(resolve(path)))
2677
+ });
2678
+ labels.push(path);
2679
+ }
2680
+ return {
2681
+ inputs,
2682
+ labels
2683
+ };
2684
+ }
2685
+ const set = project?.packs ?? await openProjectPacks(void 0);
2686
+ for (const { pack, path } of set.provided("soundbank")) {
2687
+ const v = validate("soundbank", await pack.readJson(path));
2688
+ if (!v.ok) return `${pack.manifest.id}/${path}:\n${v.formatted}`;
2689
+ const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/") + 1) : "";
2690
+ inputs.push({
2691
+ doc: v.value,
2692
+ base: `pack:${pack.manifest.id}/${dir}`
2693
+ });
2694
+ labels.push(`${pack.manifest.id}@${pack.manifest.version}:${path}`);
2695
+ }
2696
+ if (inputs.length === 0) return "no sound bank: pass --bank <file>, add a pack providing \"soundbank\" to project.json, or set MOLEN_PACKS";
2697
+ return {
2698
+ inputs,
2699
+ labels
2700
+ };
2701
+ }
2702
+ async function planAudioImpl(input) {
2703
+ let manifest;
2704
+ let types;
2705
+ let project;
2706
+ let buildOpts = {};
2707
+ if (input.scene !== void 0) {
2708
+ const v = validate("scene", input.scene);
2709
+ if (!v.ok) return fail$1(v.formatted);
2710
+ manifest = v.value;
2711
+ } else {
2712
+ if (input.scenePath === void 0) return fail$1("planAudio: provide scenePath or scene");
2713
+ const loaded = await loadSceneDocument(input.scenePath, { ...input.projectPath !== void 0 ? { projectPath: input.projectPath } : {} });
2714
+ manifest = loaded.manifest;
2715
+ types = loaded.project?.resolvedTypes;
2716
+ project = loaded.project;
2717
+ buildOpts = await sceneBuildOptionsFor(loaded);
2718
+ }
2719
+ let commands = input.commands ?? [];
2720
+ if (input.commandsPath !== void 0) {
2721
+ const raw = parseJson(await readFile(input.commandsPath, "utf8"));
2722
+ const list = Array.isArray(raw) ? raw : raw.commands;
2723
+ if (!Array.isArray(list)) return fail$1(`${input.commandsPath}: expected an array of commands`);
2724
+ commands = [];
2725
+ for (const [i, c] of list.entries()) {
2726
+ const v = validate("command", c);
2727
+ if (!v.ok) return fail$1(`command[${i}] invalid:\n${v.formatted}`);
2728
+ commands.push(v.value);
2729
+ }
2730
+ }
2731
+ let setup;
2732
+ const setupModule = resolveSetupModule(input.setupModule, project);
2733
+ if (setupModule !== void 0) setup = await loadSetupLike(setupModule);
2734
+ const banks = await loadBanks(input.bankPaths, project);
2735
+ if (typeof banks === "string") return fail$1(banks);
2736
+ const bank = mergeSoundbanks(banks.inputs);
2737
+ const warnings = [];
2738
+ const director = new AudioDirector({
2739
+ bank,
2740
+ onWarning: (m) => warnings.push(m)
2741
+ });
2742
+ const build = await prepareSceneBuilder(manifest, setup, {
2743
+ ...buildOpts,
2744
+ ...types !== void 0 ? { types } : {}
2745
+ });
2746
+ let weather = void 0;
2747
+ if (input.weather !== void 0) try {
2748
+ weather = weatherProfile(input.weather);
2749
+ } catch {
2750
+ return fail$1(`unknown weather profile "${input.weather}" (sunny, partly-cloudy, overcast, rain, snow, fog)`);
2751
+ }
2752
+ const issues = [];
2753
+ const voices = /* @__PURE__ */ new Map();
2754
+ const done = [];
2755
+ const oneShots = [];
2756
+ const events = [];
2757
+ let tickRate = 30;
2758
+ let detach;
2759
+ let lastTick = 0;
2760
+ const record = (cmds, tick) => {
2761
+ for (const cmd of cmds) if (cmd.op === "start") if (cmd.loop || cmd.voice.startsWith("music:")) {
2762
+ const entity = cmd.voice.startsWith("src:") ? cmd.voice.slice(4, cmd.voice.lastIndexOf("~")) : void 0;
2763
+ voices.set(cmd.voice, {
2764
+ voice: cmd.voice,
2765
+ sound: cmd.sound,
2766
+ bus: cmd.bus,
2767
+ startTick: tick,
2768
+ peakGain: cmd.gain,
2769
+ pitch: [cmd.pitch, cmd.pitch],
2770
+ ...entity !== void 0 ? { entity } : {}
2771
+ });
2772
+ } else oneShots.push({
2773
+ tick,
2774
+ sound: cmd.sound,
2775
+ bus: cmd.bus,
2776
+ ...cmd.spatial ? { position: cmd.spatial.position } : {}
2777
+ });
2778
+ else if (cmd.op === "set") {
2779
+ const v = voices.get(cmd.voice);
2780
+ if (v && cmd.gain !== void 0) v.peakGain = Math.max(v.peakGain, cmd.gain);
2781
+ if (v && cmd.pitch !== void 0) v.pitch = [Math.min(v.pitch[0], cmd.pitch), Math.max(v.pitch[1], cmd.pitch)];
2782
+ } else if (cmd.op === "stop") {
2783
+ const v = voices.get(cmd.voice);
2784
+ if (v) {
2785
+ voices.delete(cmd.voice);
2786
+ done.push({
2787
+ ...v,
2788
+ stopTick: tick
2789
+ });
2790
+ }
2791
+ }
2792
+ };
2793
+ const staticCheck = (world) => {
2794
+ const source = entitySourceFromWorld(world);
2795
+ for (const component of [
2796
+ "audioSource",
2797
+ "audioZone",
2798
+ "audioEnvironment"
2799
+ ]) for (const [id, data] of source.each(component)) {
2800
+ for (const ref of audioSoundRefs(component, data)) {
2801
+ if (bank.resolve(ref.sound)) continue;
2802
+ const near = nearestWithDistance(ref.sound, [...bank.ids()]);
2803
+ issues.push({
2804
+ path: `/entities/${id}/components/${component}${ref.path}`,
2805
+ message: `unknown sound "${ref.sound}"${near ? `; did you mean "${near.candidate}"?` : ""}`
2806
+ });
2807
+ }
2808
+ for (const ref of audioSignalRefs(component, data)) for (const issue of audioSignalIssues(ref.signal)) issues.push({
2809
+ path: `/entities/${id}/components/${component}${ref.path}`,
2810
+ message: `${issue.message}${issue.hint ? `; ${issue.hint}` : ""}`
2811
+ });
2812
+ }
2813
+ };
2814
+ runHeadless(build, {
2815
+ commands,
2816
+ ticks: input.ticks,
2817
+ onTick(world) {
2818
+ if (!detach) {
2819
+ tickRate = world.tickRate;
2820
+ const source = entitySourceFromWorld(world);
2821
+ director.setBank(bank);
2822
+ detach = source.onEvent?.((event, tick) => {
2823
+ director.handleEvent(event, tick);
2824
+ if (event.type.startsWith("audio.")) events.push({
2825
+ tick,
2826
+ type: event.type,
2827
+ payload: event.payload
2828
+ });
2829
+ });
2830
+ staticCheck(world);
2831
+ }
2832
+ lastTick = world.tick;
2833
+ const listener = listenerFor(world, manifest, input.listener);
2834
+ record(director.update({
2835
+ nowMs: world.tick * 1e3 / world.tickRate,
2836
+ listener: {
2837
+ ...listener,
2838
+ ...input.mode !== void 0 ? { mode: input.mode } : {}
2839
+ },
2840
+ source: entitySourceFromWorld(world),
2841
+ signals: {
2842
+ ...weather ? { weather } : {},
2843
+ ...input.daylight !== void 0 ? { sky: { daylight: input.daylight } } : {}
2844
+ }
2845
+ }), world.tick);
2846
+ }
2847
+ });
2848
+ detach?.();
2849
+ const all = [...done, ...voices.values()].sort((a, b) => a.startTick - b.startTick);
2850
+ const lines = [];
2851
+ lines.push(`${input.ticks} ticks at ${tickRate} Hz, banks: ${banks.labels.join(", ")}`);
2852
+ lines.push(all.length > 0 ? "loops:" : "loops: none");
2853
+ for (const v of all) {
2854
+ const span = `[${v.startTick} → ${v.stopTick ?? "end"}]`.padEnd(14);
2855
+ const at = v.entity !== void 0 ? ` @${v.entity}` : "";
2856
+ const pitch = v.pitch[0] === v.pitch[1] ? v.pitch[0].toFixed(2) : `${v.pitch[0].toFixed(2)}–${v.pitch[1].toFixed(2)}`;
2857
+ lines.push(` ${span} ${v.sound}${at} bus ${v.bus} peak ${v.peakGain.toFixed(2)} pitch ${pitch}`);
2858
+ }
2859
+ lines.push(oneShots.length > 0 ? `one-shots (${oneShots.length}):` : "one-shots: none");
2860
+ for (const s of oneShots.slice(0, 200)) {
2861
+ const at = s.position ? ` at [${s.position.map((x) => Math.round(x * 10) / 10).join(", ")}]` : "";
2862
+ lines.push(` t=${String(s.tick).padEnd(6)} ${s.sound}${at} (${s.bus})`);
2863
+ }
2864
+ if (oneShots.length > 200) lines.push(` … ${oneShots.length - 200} more`);
2865
+ for (const i of issues) lines.push(`✗ ${i.path}: ${i.message}`);
2866
+ for (const w of warnings) lines.push(`! ${w}`);
2867
+ return {
2868
+ ok: issues.length === 0 && !warnings.some((w) => w.startsWith("unknown sound")),
2869
+ ticks: lastTick,
2870
+ tickRate,
2871
+ banks: banks.labels,
2872
+ voices: all,
2873
+ oneShots,
2874
+ events,
2875
+ issues,
2876
+ warnings,
2877
+ timeline: lines.join("\n")
2878
+ };
2879
+ }
2880
+ //#endregion
2093
2881
  //#region src/ops/camera.ts
2094
2882
  /**
2095
2883
  * The camera a capture uses: an explicit override wins; otherwise the scene's own `camera`
@@ -2132,6 +2920,14 @@ function literal(value) {
2132
2920
  if (typeof value !== "string") return String(value);
2133
2921
  return `'${value.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
2134
2922
  }
2923
+ /** True when a node prints as a top-level `a | b` union. */
2924
+ function isUnion(node) {
2925
+ if (node === void 0 || node.const !== void 0) return false;
2926
+ if (node.enum !== void 0) return node.enum.length > 1;
2927
+ const union = node.anyOf ?? node.oneOf;
2928
+ if (union !== void 0) return union.length > 1;
2929
+ return Array.isArray(node.type) && node.type.length > 1;
2930
+ }
2135
2931
  /** Print a JSON Schema node as a TS type expression. Unknown constructs degrade to `unknown`. */
2136
2932
  function schemaToTsType(schema, indent = "") {
2137
2933
  const node = schema;
@@ -2155,7 +2951,7 @@ function schemaToTsType(schema, indent = "") {
2155
2951
  if (node.prefixItems !== void 0) return `[${node.prefixItems.map((p) => schemaToTsType(p, indent)).join(", ")}]`;
2156
2952
  const item = node.items !== void 0 ? schemaToTsType(node.items, indent) : "unknown";
2157
2953
  if (node.minItems !== void 0 && node.minItems === node.maxItems && node.minItems > 0 && node.minItems <= 8) return `[${Array.from({ length: node.minItems }, () => item).join(", ")}]`;
2158
- return `${item}[]`;
2954
+ return isUnion(node.items) ? `(${item})[]` : `${item}[]`;
2159
2955
  }
2160
2956
  case "object": {
2161
2957
  const props = node.properties ?? {};
@@ -2421,6 +3217,29 @@ function renderScriptTypes(input) {
2421
3217
  "",
2422
3218
  ...renderMath(),
2423
3219
  "",
3220
+ "/** Options for `molen.audio.play`. Omit entity and position for a non-positional sound. */",
3221
+ "interface MolenAudioPlayOptions {",
3222
+ " /** Play at (and follow) this entity's transform. */",
3223
+ " entity?: MolenEntityId;",
3224
+ " /** Play at a fixed world position. */",
3225
+ " position?: MolenVec3;",
3226
+ " gain?: number;",
3227
+ " pitch?: number;",
3228
+ " bus?: string;",
3229
+ " /** Loop until stopped; default the sound's own loop flag. */",
3230
+ " loop?: boolean;",
3231
+ "}",
3232
+ "",
3233
+ "/** `molen.audio`: each call emits an `audio.*` event the client plays (guide/audio.md). */",
3234
+ "interface MolenAudioApi {",
3235
+ " /** Play a sound-bank id; returns a handle for `stop`. */",
3236
+ " play(sound: string, opts?: MolenAudioPlayOptions): string;",
3237
+ " /** Stop by handle, or every voice matching an entity and/or sound. */",
3238
+ " stop(target: string | { entity?: MolenEntityId; sound?: string }, fadeS?: number): void;",
3239
+ " /** Switch background music to a track or playlist; null stops it. */",
3240
+ " music(playlist: string | string[] | null, opts?: { crossfadeS?: number }): void;",
3241
+ "}",
3242
+ "",
2424
3243
  "/** The verb set injected into every scene-data script as `molen`. */",
2425
3244
  "interface MolenApi {",
2426
3245
  " /** Spawn from a component map. */",
@@ -2477,6 +3296,8 @@ function renderScriptTypes(input) {
2477
3296
  " handler: (payload: MolenCommands[T], ctx: MolenTickContext, command: MolenCommand) => void,",
2478
3297
  " ): MolenUnsubscribe;",
2479
3298
  " emit(type: string, payload?: MolenJsonValue): void;",
3299
+ " /** Sound: play/stop one-shots and loops, switch music. Never affects the simulation. */",
3300
+ " readonly audio: MolenAudioApi;",
2480
3301
  " raycast(origin: MolenVec3, dir: MolenVec3, maxDist: number, mask?: number): MolenRayHit | null;",
2481
3302
  " overlapCircle(center: MolenVec3, radius: number, mask?: number): string[];",
2482
3303
  " /** Emit `event` after `ticks` ticks (snapshot-safe world timer). Returns the timer id. */",
@@ -2684,7 +3505,7 @@ async function loadTypeScript(projectDir) {
2684
3505
  */
2685
3506
  function typescriptNotFoundError(projectDir) {
2686
3507
  return [
2687
- "typescript not found — molen scripts check compiles with the project's own TypeScript",
3508
+ "typescript not found — molen scripts check compiles with the project's own TypeScript",
2688
3509
  ` install it in ${projectDir}:`,
2689
3510
  " npm install # the scaffold lists typescript as a devDependency",
2690
3511
  " or add it directly:",
@@ -2723,7 +3544,7 @@ function diagnosticsFor(ts, target, projectDir) {
2723
3544
  }
2724
3545
  const { line, character } = d.file.getLineAndCharacterOfPosition(d.start);
2725
3546
  out.push({
2726
- file: relative(projectDir, d.file.fileName),
3547
+ file: relative(projectDir, d.file.fileName).replaceAll("\\", "/"),
2727
3548
  line: line + 1,
2728
3549
  column: character + 1,
2729
3550
  code: `TS${d.code}`,
@@ -2758,7 +3579,7 @@ async function checkScripts(input) {
2758
3579
  ok: false,
2759
3580
  stale,
2760
3581
  ungenerated,
2761
- error: `script declarations are ${stale.length > 0 ? "stale" : "missing"} — run: molen types gen`
3582
+ error: `script declarations are ${stale.length > 0 ? "stale" : "missing"} — run: molen types gen`
2762
3583
  };
2763
3584
  const ts = await loadTypeScript(project.dir);
2764
3585
  if (ts === void 0) return {
@@ -2967,15 +3788,23 @@ const OPS_CATALOG = [
2967
3788
  },
2968
3789
  {
2969
3790
  name: "new_experience",
2970
- summary: "Scaffold a new experience (scene + scripts + commands + checks) ready for the loop.",
2971
- cli: "molen new <name> [--dir <path>] [--force]",
3791
+ summary: "Scaffold a new experience (scene + scripts + commands + checks + AGENTS.md) ready for the loop, or a standalone copy of a shipped sample with --template.",
3792
+ cli: "molen new <name> [--template <id>] [--dir <path>] [--force]",
2972
3793
  mcpTool: "new_experience",
2973
3794
  params: [
2974
3795
  p("name", "string", true, "Experience name (also the output folder name)."),
3796
+ p("template", "string", false, "Copy this sample instead of the built-in starter (list_templates / molen templates lists the ids)."),
2975
3797
  p("dir", "string", false, "Parent directory (default: cwd)."),
2976
3798
  p("force", "boolean", false, "Replace existing scaffold-owned files (default false).")
2977
3799
  ]
2978
3800
  },
3801
+ {
3802
+ name: "list_templates",
3803
+ summary: "List the sample templates new_experience can copy (id + one-line description); each scaffolds as a standalone npm project.",
3804
+ cli: "molen templates [--json]",
3805
+ mcpTool: "list_templates",
3806
+ params: []
3807
+ },
2979
3808
  {
2980
3809
  name: "drive_scene",
2981
3810
  summary: "PLAY a scene deterministically: commands in at chosen ticks, screenshot frames out — a repeatable scenario the agent can look at.",
@@ -3082,7 +3911,7 @@ const OPS_CATALOG = [
3082
3911
  },
3083
3912
  {
3084
3913
  name: "fetch_pack",
3085
- summary: "Download content packs (a pack URL, or a molen/pack-index@1 URL) into the project and pin them in project.json `packs` with their contentHash, so the project runs offline.",
3914
+ summary: "Download content packs (a pack URL, or a molen/pack-index@1 URL) into the project, list them in index.json in the download directory (so a page can open them), and pin them in project.json `packs` with their contentHash, so the project runs offline.",
3086
3915
  cli: "molen pack fetch <url> [ids…] [--out-dir <d>] [--project <path>]",
3087
3916
  mcpTool: "fetch_pack",
3088
3917
  params: [
@@ -3093,6 +3922,57 @@ const OPS_CATALOG = [
3093
3922
  cwdParam()
3094
3923
  ]
3095
3924
  },
3925
+ {
3926
+ name: "plan_audio",
3927
+ summary: "Run a scene headlessly and list the sounds it would play: looping voices with start/stop ticks, peak gain and pitch range, one-shots by tick, audio.* script events, and unknown sound ids or signals. Hear a scene's audio annotations without a browser.",
3928
+ cli: "molen audio plan <scene|name> --ticks <N> [--bank <bank.json,…>] [--commands <f>] [--setup <m>] [--listener <entity>] [--mode <walk|drive|fly>] [--weather <profile>] [--daylight <0..1>] [--project <project.json>] [--json]",
3929
+ mcpTool: "plan_audio",
3930
+ params: [
3931
+ p("scenePath", "string", true, "Scene file path or project scene name."),
3932
+ p("ticks", "int>0", true, "Ticks to simulate."),
3933
+ p("bankPaths", "string[]", false, "molen/soundbank@1 files (default: every provides.soundbank in the project's packs)."),
3934
+ p("commandsPath", "string", false, "JSON array (or {commands:[...]}) of command envelopes."),
3935
+ p("setupModule", "string", false, "ESM module exporting setup(world, manifest)."),
3936
+ p("listener", "string", false, "Entity whose transform is the listener (default: the scene camera)."),
3937
+ p("mode", "string", false, "listener.mode for rules: walk, drive, fly…"),
3938
+ p("weather", "string", false, "Weather profile: sunny, partly-cloudy, overcast, rain, snow, fog."),
3939
+ p("daylight", "number", false, "sky.daylight 0 (night) – 1 (day); default 1."),
3940
+ projectPathParam()
3941
+ ]
3942
+ },
3943
+ {
3944
+ name: "import_sound",
3945
+ summary: "Add an audio clip to a molen/soundbank@1 file: copy it beside the bank, hash it, probe its duration, and record license and provenance. --append adds a variation to an existing sound.",
3946
+ cli: "molen audio import <file> --id <sound.id> --bank <bank.json> --license <spdx> [--source <url>] [--site s] [--author a] [--prompt p] [--generator g] [--description d] [--loop] [--loop-start s] [--loop-end s] [--bus b] [--gain g] [--duration s] [--append] [--copy-to <dir>]",
3947
+ mcpTool: "import_sound",
3948
+ params: [
3949
+ p("file", "string", true, "Audio file (MP3 recommended; WAV and Ogg accepted)."),
3950
+ p("id", "string", true, "Sound id, e.g. \"ambience.rain.medium\"."),
3951
+ p("bankPath", "string", true, "Sound bank JSON to update (created when missing)."),
3952
+ p("license", "string", true, "SPDX license of the recording, e.g. \"CC0-1.0\"."),
3953
+ p("source", "string", false, "Page of the original recording."),
3954
+ p("site", "string", false, "Origin site: freesound, kenney, opengameart, …"),
3955
+ p("author", "string", false, "Recordist or creator."),
3956
+ p("prompt", "string", false, "Generation prompt, for generated clips."),
3957
+ p("generator", "string", false, "Generator/model name, for generated clips."),
3958
+ p("description", "string", false, "What it sounds like (agents choose sounds by it)."),
3959
+ p("loop", "boolean", false, "Loop the clip (ambience, engines)."),
3960
+ p("loopStart", "number", false, "Loop start in seconds."),
3961
+ p("loopEnd", "number", false, "Loop end in seconds."),
3962
+ p("bus", "string", false, "Default bus: music, ambience, sfx, ui, voice."),
3963
+ p("gain", "number", false, "Base gain (default 1)."),
3964
+ p("durationS", "number", false, "Duration in seconds; overrides the probed value."),
3965
+ p("append", "boolean", false, "Add as another variation of an existing sound."),
3966
+ p("copyTo", "string", false, "Directory under the bank for copied files (default audio).")
3967
+ ]
3968
+ },
3969
+ {
3970
+ name: "check_soundbank",
3971
+ summary: "Check a molen/soundbank@1 file and every clip it names: files present, hashes unchanged, durations and loop points consistent, provenance recorded; prints a license summary.",
3972
+ cli: "molen audio check <bank.json>",
3973
+ mcpTool: "check_soundbank",
3974
+ params: [p("bankPath", "string", true, "Sound bank JSON.")]
3975
+ },
3096
3976
  {
3097
3977
  name: "test_types",
3098
3978
  summary: "Smoke-test every registry type standalone: resolved shape validates, spawns, and survives N simulated ticks.",
@@ -3121,14 +4001,15 @@ const OPS_CATALOG = [
3121
4001
  {
3122
4002
  name: "import_asset",
3123
4003
  summary: "Import a glTF/GLB: normalize, extract bounds + collision (hulls/trimesh), write the asset sidecar, register in project.json.",
3124
- cli: "molen asset import <file.glb> [--id <asset-id>] [--trimesh] [--no-optimize] [--out-dir <d>] [--project <project.json>] [--force]",
4004
+ cli: "molen asset import <file.glb> [--id <asset-id>] [--trimesh] [--no-optimize] [--out-dir <d>] [--asset-dir <d>] [--project <project.json>] [--force]",
3125
4005
  mcpTool: "import_asset",
3126
4006
  params: [
3127
4007
  p("path", "string", true, "Source .glb/.gltf file."),
3128
4008
  p("id", "string", false, "Asset id (default: slugged filename; dotted ids join a namespace)."),
3129
4009
  p("trimesh", "boolean", false, "Also extract a whole-asset collision trimesh (collision.bin)."),
3130
4010
  p("optimize", "boolean", false, "Normalize pass dedup/prune/weld/quantize (default true)."),
3131
- p("outDir", "string", false, "Assets root override (default: <project dir>/assets)."),
4011
+ p("outDir", "string", false, "Assets root override; retains root/id layout. Mutually exclusive with assetDir."),
4012
+ p("assetDir", "string", false, "Exact bundle directory, relative to cwd. Mutually exclusive with outDir. Omit both to preserve an existing project asset directory."),
3132
4013
  p("projectPath", "string", false, "project.json to register into. Required when the source file sits in a different project than the cwd."),
3133
4014
  cwdParam(),
3134
4015
  p("force", "boolean", false, "Replace an existing asset directory (default false).")
@@ -3303,7 +4184,7 @@ function formatOp(op) {
3303
4184
  }
3304
4185
  //#endregion
3305
4186
  //#region src/ops/docs.ts
3306
- async function exists(p) {
4187
+ async function exists$1(p) {
3307
4188
  try {
3308
4189
  await access(p);
3309
4190
  return true;
@@ -3319,14 +4200,14 @@ async function exists(p) {
3319
4200
  async function locateDocsRoot(start = process.cwd()) {
3320
4201
  let dir = resolve(start);
3321
4202
  for (;;) {
3322
- if (await exists(join(dir, "docs-src", "llms.txt"))) return dir;
4203
+ if (await exists$1(join(dir, "docs-src", "llms.txt"))) return dir;
3323
4204
  const parent = dirname(dir);
3324
4205
  if (parent === dir) break;
3325
4206
  dir = parent;
3326
4207
  }
3327
4208
  dir = dirname(fileURLToPath(import.meta.url));
3328
4209
  for (;;) {
3329
- if (await exists(join(dir, "docs-src", "llms.txt"))) return dir;
4210
+ if (await exists$1(join(dir, "docs-src", "llms.txt"))) return dir;
3330
4211
  const parent = dirname(dir);
3331
4212
  if (parent === dir) throw new Error("Molen documentation bundle is missing; reinstall @bendyline/molen-tooling");
3332
4213
  dir = parent;
@@ -3348,7 +4229,7 @@ async function searchDocs(input) {
3348
4229
  const k = input.k ?? 5;
3349
4230
  const terms = input.query.toLowerCase().split(/\s+/).filter(Boolean);
3350
4231
  const root = input.baseDir ?? await locateDocsRoot();
3351
- if (!await exists(join(root, "docs-src", "llms.txt"))) return {
4232
+ if (!await exists$1(join(root, "docs-src", "llms.txt"))) return {
3352
4233
  ok: false,
3353
4234
  hits: [],
3354
4235
  root,
@@ -4425,6 +5306,15 @@ async function fetchContentPack(input) {
4425
5306
  size: bytes.length
4426
5307
  });
4427
5308
  }
5309
+ for (const pack of fetched) {
5310
+ const { file, version, contentHash, size } = pack;
5311
+ await recordInPackIndex(outDir, pack.id, {
5312
+ file,
5313
+ version,
5314
+ contentHash,
5315
+ size
5316
+ });
5317
+ }
4428
5318
  if (projectPath !== void 0) await updateProjectFile(projectPath, (manifest) => {
4429
5319
  for (const pack of fetched) {
4430
5320
  const file = relative(dirname(projectPath), join(outDir, pack.file));
@@ -4904,6 +5794,57 @@ async function diffSnapshots(input) {
4904
5794
  };
4905
5795
  }
4906
5796
  //#endregion
5797
+ //#region src/ops/templates.ts
5798
+ async function exists(path) {
5799
+ try {
5800
+ await access(path);
5801
+ return true;
5802
+ } catch {
5803
+ return false;
5804
+ }
5805
+ }
5806
+ /**
5807
+ * Walk up from this module to the template bundle: `templates/` beside the built entry points
5808
+ * (dist/), or `dist/templates/` above the sources (a workspace build, as the tests run it).
5809
+ */
5810
+ async function locateTemplates() {
5811
+ let dir = dirname(fileURLToPath(import.meta.url));
5812
+ for (;;) {
5813
+ for (const candidate of [join(dir, "templates"), join(dir, "dist", "templates")]) if (await exists(join(candidate, "index.json"))) return candidate;
5814
+ const parent = dirname(dir);
5815
+ if (parent === dir) return void 0;
5816
+ dir = parent;
5817
+ }
5818
+ }
5819
+ /** Read the shipped template bundle; throws when it is missing. */
5820
+ async function loadTemplateBundle() {
5821
+ const root = await locateTemplates();
5822
+ if (root === void 0) throw new Error("Molen template bundle is missing; reinstall @bendyline/molen-tooling (in the engine repository, build the tooling package)");
5823
+ return {
5824
+ root,
5825
+ templates: JSON.parse(await readFile(join(root, "index.json"), "utf8")).templates
5826
+ };
5827
+ }
5828
+ /** The sample templates `molen new --template <id>` can scaffold. */
5829
+ async function listTemplates() {
5830
+ try {
5831
+ const { templates } = await loadTemplateBundle();
5832
+ return {
5833
+ ok: true,
5834
+ templates: templates.map(({ id, description }) => ({
5835
+ id,
5836
+ description
5837
+ }))
5838
+ };
5839
+ } catch (error) {
5840
+ return {
5841
+ ok: false,
5842
+ templates: [],
5843
+ error: error.message
5844
+ };
5845
+ }
5846
+ }
5847
+ //#endregion
4907
5848
  //#region src/ops/scaffold.ts
4908
5849
  /** Scene names must be lower_snake; the scaffold namespace doubles as the types namespace. */
4909
5850
  function slug$1(name) {
@@ -5314,7 +6255,14 @@ export default defineConfig({
5314
6255
  plugins: [molenScripts()],
5315
6256
  // Worker bundles get their own plugin pipeline in Vite, and the kernel runs in the Worker.
5316
6257
  worker: { format: 'es', plugins: () => [molenScripts()] },
5317
- build: { target: 'es2022' },
6258
+ build: {
6259
+ target: 'es2022',
6260
+ // src/main.ts mounts with a top-level \`await\`, and the client lazy-loads its WebGPU driver.
6261
+ // Left in the entry chunk, three.js and the client would make that lazy chunk import the entry
6262
+ // while the entry is still suspended at the \`await\`, and the built page would stay blank in
6263
+ // every browser with WebGPU. Their own chunk breaks the cycle.
6264
+ rollupOptions: { output: { manualChunks: { vendor: ['three', '@bendyline/molen-client'] } } },
6265
+ },
5318
6266
  });
5319
6267
  `;
5320
6268
  const TSCONFIG = `{
@@ -5442,7 +6390,176 @@ function actionsJson() {
5442
6390
  }
5443
6391
  ], null, 2)}\n`;
5444
6392
  }
5445
- /** Scaffold a complete, runnable project (manifest + scene + types + scripts + setup + browser app). */
6393
+ const AGENTS_MD = "AGENTS.md";
6394
+ /** Project-relative, `/`-separated. */
6395
+ function projectRelative(dir, path) {
6396
+ return relative(dir, path).split(sep).join("/");
6397
+ }
6398
+ /** The scaffold-owned files already in `dir` (the force check). */
6399
+ async function existingFiles(dir, paths) {
6400
+ const existing = [];
6401
+ for (const rel of paths) try {
6402
+ await stat(join(dir, rel));
6403
+ existing.push(rel);
6404
+ } catch (error) {
6405
+ if (error.code !== "ENOENT") throw error;
6406
+ }
6407
+ return existing;
6408
+ }
6409
+ async function writeScaffoldFiles(dir, files, force) {
6410
+ for (const [rel, content] of files) {
6411
+ const abs = join(dir, rel);
6412
+ await mkdir(dirname(abs), { recursive: true });
6413
+ await writeFile(abs, content, force ? void 0 : { flag: "wx" });
6414
+ }
6415
+ }
6416
+ /** Refresh the typed handles and the scripts' ambient declarations from the installed registry. */
6417
+ async function refreshGeneratedTypes(dir) {
6418
+ const generated = await generateTypes({ projectPath: join(dir, "project.json") });
6419
+ if (!generated.ok) return { error: generated.error ?? "failed to generate types for the new project" };
6420
+ return { files: [projectRelative(dir, generated.outPath), ...(generated.scriptArtifacts ?? []).map((a) => projectRelative(dir, a.path))] };
6421
+ }
6422
+ /**
6423
+ * Word-wrap Markdown prose at 100 columns without breaking an inline code span. `first` prefixes
6424
+ * the first line (a bullet's `- `); continuation lines are indented to match it.
6425
+ */
6426
+ function wrap(text, first = "") {
6427
+ const indent = " ".repeat(first.length);
6428
+ const lines = [];
6429
+ let line = "";
6430
+ for (const token of text.match(/(?:[^\s`]*`[^`]*`)+[^\s`]*|\S+/g) ?? []) if (line.length === 0) line = `${lines.length === 0 ? first : indent}${token}`;
6431
+ else if (line.length + 1 + token.length > 100) {
6432
+ lines.push(line);
6433
+ line = `${indent}${token}`;
6434
+ } else line = `${line} ${token}`;
6435
+ lines.push(line);
6436
+ return lines.join("\n");
6437
+ }
6438
+ /**
6439
+ * The signpost for a coding agent working in the new project: where the version-locked docs are,
6440
+ * how to discover the ops, this project's own loop, and the rules that are cheap to break.
6441
+ */
6442
+ function agentsMd({ name, template, loop, generated }) {
6443
+ const origin = template === void 0 ? "the `molen new` starter" : `the \`${template.id}\` sample`;
6444
+ const generatedRule = generated.length > 0 ? `Generated files are never hand-edited: ${generated.map((f) => `\`${f}\``).join(", ")}. Change the scene or its type documents, then run \`npx molen types gen\` (\`npx molen types gen --check\` reports staleness).` : "Generated files are never hand-edited. Once the project has a `project.json` (https://molen.dev/guide/project), `npx molen types gen` writes its typed handles and each scripts directory's `molen-scripts.d.ts`; regenerate them instead.";
6445
+ return [
6446
+ `# AGENTS.md — ${name}`,
6447
+ "",
6448
+ wrap(`${name} is a Molen experience built from npm packages (engine ${ENGINE_VERSION}), scaffolded from ${origin}. Run every command below from this directory.`),
6449
+ "",
6450
+ "## Docs for this exact engine version",
6451
+ "",
6452
+ wrap("Start at `node_modules/@bendyline/molen-tooling/dist/docs-src/llms.txt`, then `guide/agent-loop.md` and `guide/scripting.md` beside it. They ship with the installed CLI, so they match the engine you are running; https://molen.dev/guide/agent-loop is the online copy.", "- "),
6453
+ wrap("`npx molen docs search <query>` searches that bundle offline.", "- "),
6454
+ wrap("`npx molen describe [op]` prints every operation's contract; `npx molen mcp` serves the same operations as MCP tools over stdio. `npx molen schema get <kind>` and `npx molen component <name>` give exact document and component shapes.", "- "),
6455
+ "",
6456
+ "## The headless loop",
6457
+ "",
6458
+ wrap("Install once with `npm install` (and `npx playwright install chromium` for `shot` and `drive`), then validate after every edit — a failure names the field and how to fix it:"),
6459
+ "",
6460
+ "```sh",
6461
+ ...loop,
6462
+ "```",
6463
+ "",
6464
+ "## Rules",
6465
+ "",
6466
+ wrap(generatedRule, "- "),
6467
+ wrap("Scene scripts run with the authority of the process that loads them; the CLI and the MCP server evaluate them in-process. Treat `scene.json` like source code and only run scenes you would run as a program.", "- "),
6468
+ wrap("Determinism: randomness through `molen.rng` and math through `molen.math` (in setup code, the world RNG and `dmath`); never `Math.random`, `Date` or wall-clock time in simulation code.", "- "),
6469
+ wrap("Reads are immutable: never mutate what `molen.get` / `world.get` returns; write with `set` / `patch`.", "- "),
6470
+ ""
6471
+ ].join("\n");
6472
+ }
6473
+ /** The built-in starter's loop, run from the project directory. */
6474
+ const STARTER_LOOP = [
6475
+ "npx molen validate scenes/main.scene.json",
6476
+ "npx molen types check",
6477
+ "npx molen scripts check",
6478
+ "npx molen sim run main --ticks 30 --commands cmds.json --assert checks.json --hash",
6479
+ "npx molen shot main --ticks 30 --out shot.png",
6480
+ "npx molen drive main --actions actions.json --out-dir shots"
6481
+ ];
6482
+ /** A template's loop: validate, check scripts, simulate (+ assert), replay, then its tests. */
6483
+ function templateLoop(template, scriptsCheck) {
6484
+ return [
6485
+ ...template.validate.map((doc) => `npx molen validate ${doc}`),
6486
+ ...scriptsCheck ? ["npx molen scripts check"] : [],
6487
+ ...template.sim !== null ? [`npx molen ${template.sim}`] : [],
6488
+ ...template.replays.map((fixture) => `npx molen replay ${fixture}`),
6489
+ ...template.tests ? ["npm test"] : []
6490
+ ];
6491
+ }
6492
+ /** The template's manifest as the new project's: its name, engine deps on this CLI's version line. */
6493
+ function templatePackageJson(source, name) {
6494
+ const { name: _name, ...manifest } = JSON.parse(source);
6495
+ const onEngineLine = (deps) => deps === void 0 ? void 0 : Object.fromEntries(Object.entries(deps).map(([dep, spec]) => [dep, spec.startsWith("workspace:") ? `^${ENGINE_VERSION}` : spec]));
6496
+ const pkg = {
6497
+ name,
6498
+ ...manifest,
6499
+ dependencies: onEngineLine(manifest.dependencies),
6500
+ devDependencies: onEngineLine(manifest.devDependencies)
6501
+ };
6502
+ return `${JSON.stringify(pkg, null, 2)}\n`;
6503
+ }
6504
+ async function scaffoldTemplate(input, dir) {
6505
+ const bundle = await loadTemplateBundle();
6506
+ const template = bundle.templates.find((t) => t.id === input.template);
6507
+ if (template === void 0) return {
6508
+ ok: false,
6509
+ error: `unknown template "${input.template}"; available templates: ${bundle.templates.map((t) => t.id).join(", ")} (molen templates describes them)`
6510
+ };
6511
+ const force = input.force === true;
6512
+ const files = [];
6513
+ for (const rel of template.files) {
6514
+ const source = await readFile(join(bundle.root, template.id, rel));
6515
+ files.push([rel, rel === "package.json" ? templatePackageJson(source.toString("utf8"), input.name) : source]);
6516
+ }
6517
+ if (!force) {
6518
+ const existing = await existingFiles(dir, [...files.map(([rel]) => rel), AGENTS_MD]);
6519
+ if (existing.length > 0) return {
6520
+ ok: false,
6521
+ error: `${dir} already contains scaffold files: ${existing.join(", ")} (pass force: true to replace them)`
6522
+ };
6523
+ }
6524
+ await writeScaffoldFiles(dir, files, force);
6525
+ let generated = [];
6526
+ if (template.project) {
6527
+ const refreshed = await refreshGeneratedTypes(dir);
6528
+ if (refreshed.error !== void 0) return {
6529
+ ok: false,
6530
+ error: refreshed.error
6531
+ };
6532
+ generated = refreshed.files ?? [];
6533
+ }
6534
+ const loop = templateLoop(template, generated.some((f) => f.endsWith("molen-scripts.d.ts")));
6535
+ await writeScaffoldFiles(dir, [[AGENTS_MD, agentsMd({
6536
+ name: input.name,
6537
+ template,
6538
+ loop,
6539
+ generated
6540
+ })]], force);
6541
+ return {
6542
+ ok: true,
6543
+ dir,
6544
+ files: [...new Set([
6545
+ ...files.map(([rel]) => rel),
6546
+ ...generated,
6547
+ AGENTS_MD
6548
+ ])].sort(),
6549
+ nextSteps: [
6550
+ `cd ${dir}`,
6551
+ "npm install # the engine, the molen CLI, TypeScript and Vite",
6552
+ "npx playwright install chromium # once per machine, for shot and drive",
6553
+ ...loop,
6554
+ "npm run dev"
6555
+ ]
6556
+ };
6557
+ }
6558
+ /**
6559
+ * Scaffold a complete, runnable project: the built-in starter (manifest + scene + types + scripts
6560
+ * + setup + browser app), or with `template` a copy of one of the shipped samples. Either way the
6561
+ * project gets an AGENTS.md pointing a coding agent at the version-locked docs and its loop.
6562
+ */
5446
6563
  async function scaffoldExperience(input) {
5447
6564
  if (!/^[a-zA-Z][\w-]*$/.test(input.name)) return {
5448
6565
  ok: false,
@@ -5450,6 +6567,10 @@ async function scaffoldExperience(input) {
5450
6567
  };
5451
6568
  const dir = resolve(input.dir ?? process.cwd(), input.name);
5452
6569
  try {
6570
+ if (input.template !== void 0) return await scaffoldTemplate({
6571
+ ...input,
6572
+ template: input.template
6573
+ }, dir);
5453
6574
  const files = [
5454
6575
  ["project.json", projectJson(input.name)],
5455
6576
  ["scenes/main.scene.json", sceneJson(input.name)],
@@ -5470,44 +6591,39 @@ async function scaffoldExperience(input) {
5470
6591
  ["package.json", packageJson(input.name)],
5471
6592
  ["README.md", readme(input.name)]
5472
6593
  ];
5473
- if (input.force !== true) {
5474
- const existing = [];
5475
- for (const [rel] of files) try {
5476
- await stat(join(dir, rel));
5477
- existing.push(rel);
5478
- } catch (error) {
5479
- if (error.code !== "ENOENT") throw error;
5480
- }
6594
+ const force = input.force === true;
6595
+ if (!force) {
6596
+ const existing = await existingFiles(dir, [...files.map(([rel]) => rel), AGENTS_MD]);
5481
6597
  if (existing.length > 0) return {
5482
6598
  ok: false,
5483
6599
  error: `${dir} already contains scaffold files: ${existing.join(", ")} (pass force: true to replace them)`
5484
6600
  };
5485
6601
  }
5486
- for (const [rel, content] of files) {
5487
- const abs = join(dir, rel);
5488
- await mkdir(dirname(abs), { recursive: true });
5489
- await writeFile(abs, content, input.force === true ? void 0 : { flag: "wx" });
5490
- }
5491
- const generated = await generateTypes({ projectPath: join(dir, "project.json") });
5492
- if (!generated.ok) return {
6602
+ await writeScaffoldFiles(dir, files, force);
6603
+ const generated = await refreshGeneratedTypes(dir);
6604
+ if (generated.error !== void 0) return {
5493
6605
  ok: false,
5494
- error: generated.error ?? "failed to generate types for the new project"
6606
+ error: generated.error
5495
6607
  };
5496
- const generatedFiles = [relative(dir, generated.outPath), ...(generated.scriptArtifacts ?? []).map((a) => relative(dir, a.path))];
6608
+ const generatedFiles = generated.files ?? [];
6609
+ await writeScaffoldFiles(dir, [[AGENTS_MD, agentsMd({
6610
+ name: input.name,
6611
+ loop: STARTER_LOOP,
6612
+ generated: generatedFiles
6613
+ })]], force);
5497
6614
  return {
5498
6615
  ok: true,
5499
6616
  dir,
5500
- files: [...files.map(([rel]) => rel), ...generatedFiles],
6617
+ files: [
6618
+ ...files.map(([rel]) => rel),
6619
+ ...generatedFiles,
6620
+ AGENTS_MD
6621
+ ],
5501
6622
  nextSteps: [
5502
6623
  `cd ${dir}`,
5503
6624
  "npm install # the engine, the molen CLI and TypeScript",
5504
6625
  "npx playwright install chromium # once per machine, for shot and drive",
5505
- "npx molen validate scenes/main.scene.json",
5506
- "npx molen types check",
5507
- "npx molen scripts check",
5508
- "npx molen sim run main --ticks 30 --commands cmds.json --assert checks.json --hash",
5509
- "npx molen shot main --ticks 30 --out shot.png",
5510
- "npx molen drive main --actions actions.json --out-dir shots"
6626
+ ...STARTER_LOOP
5511
6627
  ]
5512
6628
  };
5513
6629
  } catch (e) {
@@ -6979,6 +8095,10 @@ join("capture", "worldgen-preview.html");
6979
8095
  */
6980
8096
  /** Local archive path of a package source; remote archives are not read by this Node op. */
6981
8097
  function archivePath(source) {
8098
+ if (source.kind === "pmtiles-set") {
8099
+ const location = "path" in source ? source.path : source.url;
8100
+ throw new Error(`archive set ${location} is not supported; worldgen stats reads single local PMTiles archives`);
8101
+ }
6982
8102
  if ("path" in source) return source.path;
6983
8103
  throw new Error(`archive ${source.url} is remote; worldgen stats reads local packages only`);
6984
8104
  }
@@ -7243,4 +8363,4 @@ function formatWorldgenStats(result) {
7243
8363
  registerCameraTrackSchema();
7244
8364
  registerExperiencePlaySchema();
7245
8365
  //#endregion
7246
- export { importAsset as $, verifyContentPack as A, describeOps as B, listTypes as C, extractContentPack as D, buildContentPack as E, exportFrames as F, stageAssets as G, checkScripts as H, driveScene as I, formatPacked as J, screenshotAsset as K, locateDocsRoot as L, renderTypesModule as M, previewFigure as N, fetchContentPack as O, listFigurePresets as P, assetFileIndex as Q, searchDocs as R, checkTypesOp as S, reserveNamespace as T, schemaToTsType as U, formatOp as V, ASSET_INDEX_FILE as W, inspectAsset as X, packAsset as Y, listAssets as Z, loadComponentRegistry as _, lineupBatchDoc as a, parseExperiencePlayScenario as at, runReplayFile as b, validateAsset as c, runSimulation as d, findProjectFile as et, screenshotScene as f, listSchemasOp as g, listComponentsOp as h, bakeWorldgen as i, updateProjectFile as it, generateTypes as j, inspectContentPack as k, applyUvPaintOp as l, getSchemaOp as m, worldgenStats as n, loadSceneDocument as nt, loadStylePackFromDisk as o, playExperience as ot, getComponentOp as p, formatBytes as q, previewWorldgen as r, loadSetupLike as rt, simWatch as s, registerExperiencePlaySchema as st, formatWorldgenStats as t, loadProject as tt, testTypes as u, scaffoldExperience as v, projectInfo as w, rasterizeMaterial as x, diffSnapshots as y, OPS_CATALOG as z };
8366
+ export { packAsset as $, inspectContentPack as A, OPS_CATALOG as B, checkTypesOp as C, buildContentPack as D, reserveNamespace as E, listFigurePresets as F, planAudio as G, formatOp as H, exportFrames as I, ASSET_INDEX_FILE as J, importSound as K, driveScene as L, generateTypes as M, renderTypesModule as N, extractContentPack as O, previewFigure as P, formatPacked as Q, locateDocsRoot as R, rasterizeMaterial as S, projectInfo as T, checkScripts as U, describeOps as V, schemaToTsType as W, screenshotAsset as X, stageAssets as Y, formatBytes as Z, loadComponentRegistry as _, lineupBatchDoc as a, loadProject as at, diffSnapshots as b, validateAsset as c, updateProjectFile as ct, runSimulation as d, registerExperiencePlaySchema as dt, inspectAsset as et, screenshotScene as f, listSchemasOp as g, listComponentsOp as h, bakeWorldgen as i, findProjectFile as it, verifyContentPack as j, fetchContentPack as k, applyUvPaintOp as l, parseExperiencePlayScenario as lt, getSchemaOp as m, worldgenStats as n, assetFileIndex as nt, loadStylePackFromDisk as o, loadSceneDocument as ot, getComponentOp as p, checkSoundbank as q, previewWorldgen as r, importAsset as rt, simWatch as s, loadSetupLike as st, formatWorldgenStats as t, listAssets as tt, testTypes as u, playExperience as ut, scaffoldExperience as v, listTypes as w, runReplayFile as x, listTemplates as y, searchDocs as z };