agentscape3d-engine 0.0.0-stage → 1.0.0-beta.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 (457) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +19 -2
  3. package/cli.mjs +53 -0
  4. package/dist/ArticulationVerifier-BfGxXY8V.js +337 -0
  5. package/dist/ArticulationVerifier-BfGxXY8V.js.map +1 -0
  6. package/dist/AssetCompiler-BLj09iu1.js +2424 -0
  7. package/dist/AssetCompiler-BLj09iu1.js.map +1 -0
  8. package/dist/AssetModule-DME-XaFS.js +2637 -0
  9. package/dist/AssetModule-DME-XaFS.js.map +1 -0
  10. package/dist/AssetRecipe-g8dZBhgJ.js +298 -0
  11. package/dist/AssetRecipe-g8dZBhgJ.js.map +1 -0
  12. package/dist/BrowserCodeWorker.js +53856 -0
  13. package/dist/BrowserCodeWorker.js.map +1 -0
  14. package/dist/CarryCapability-CXwHU5ay.js +104 -0
  15. package/dist/CarryCapability-CXwHU5ay.js.map +1 -0
  16. package/dist/KinematicHypothesisScreen-C3TKiuYR.js +241 -0
  17. package/dist/KinematicHypothesisScreen-C3TKiuYR.js.map +1 -0
  18. package/dist/ObjectTransform-BlQUNK7c.js +61 -0
  19. package/dist/ObjectTransform-BlQUNK7c.js.map +1 -0
  20. package/dist/RapierPhysicsBackend-B2wQe_Vl.js +3259 -0
  21. package/dist/RapierPhysicsBackend-B2wQe_Vl.js.map +1 -0
  22. package/dist/RenderingSystem-WIr1ZuGu.js +1042 -0
  23. package/dist/RenderingSystem-WIr1ZuGu.js.map +1 -0
  24. package/dist/ScenePresentation-LsYiDxbm.js +152 -0
  25. package/dist/ScenePresentation-LsYiDxbm.js.map +1 -0
  26. package/dist/SceneProject-K7HH1s8o.js +2687 -0
  27. package/dist/SceneProject-K7HH1s8o.js.map +1 -0
  28. package/dist/SceneSerializer-zOzbX4jZ.js +932 -0
  29. package/dist/SceneSerializer-zOzbX4jZ.js.map +1 -0
  30. package/dist/SimulationProfile-DSYZbBLQ.js +165 -0
  31. package/dist/SimulationProfile-DSYZbBLQ.js.map +1 -0
  32. package/dist/StylePack-DcRa_kU0.js +88 -0
  33. package/dist/StylePack-DcRa_kU0.js.map +1 -0
  34. package/dist/WorldArchive-BiFGLt--.js +451 -0
  35. package/dist/WorldArchive-BiFGLt--.js.map +1 -0
  36. package/dist/WorldCommands-Debj7V4L.js +2207 -0
  37. package/dist/WorldCommands-Debj7V4L.js.map +1 -0
  38. package/dist/WorldIO-Ch8QBfKY.js +151 -0
  39. package/dist/WorldIO-Ch8QBfKY.js.map +1 -0
  40. package/dist/admission-CVEvsrdz.js +121 -0
  41. package/dist/admission-CVEvsrdz.js.map +1 -0
  42. package/dist/blankWorld-B0MW6g7q.js +75 -0
  43. package/dist/blankWorld-B0MW6g7q.js.map +1 -0
  44. package/dist/core.d.ts +68 -0
  45. package/dist/core.js +209 -0
  46. package/dist/core.js.map +1 -0
  47. package/dist/disposeObject3D-DIMzy0FA.js +128 -0
  48. package/dist/disposeObject3D-DIMzy0FA.js.map +1 -0
  49. package/dist/environments-HOe3sJXH.js +567 -0
  50. package/dist/environments-HOe3sJXH.js.map +1 -0
  51. package/dist/gltfIO-BzVKLyaL.js +339 -0
  52. package/dist/gltfIO-BzVKLyaL.js.map +1 -0
  53. package/dist/grandUrbanBlock-DRndRZjF.js +515 -0
  54. package/dist/grandUrbanBlock-DRndRZjF.js.map +1 -0
  55. package/dist/index.d.ts +345 -0
  56. package/dist/index.js +16952 -0
  57. package/dist/index.js.map +1 -0
  58. package/dist/magicCabin-CfBZjx2Q.js +11019 -0
  59. package/dist/magicCabin-CfBZjx2Q.js.map +1 -0
  60. package/dist/manifests-D0LwbJ36.js +866 -0
  61. package/dist/manifests-D0LwbJ36.js.map +1 -0
  62. package/dist/mcp.d.ts +2 -0
  63. package/dist/mcp.js +1 -0
  64. package/dist/monumentHall-awZiGtda.js +403 -0
  65. package/dist/monumentHall-awZiGtda.js.map +1 -0
  66. package/dist/node.d.ts +16 -0
  67. package/dist/node.js +26 -0
  68. package/dist/parts-DrEcfJRl.js +37 -0
  69. package/dist/parts-DrEcfJRl.js.map +1 -0
  70. package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
  71. package/dist/ruinedCourtyard-DuF7NmUU.js +696 -0
  72. package/dist/ruinedCourtyard-DuF7NmUU.js.map +1 -0
  73. package/dist/runtime/application/AgentTools.js +28 -0
  74. package/dist/runtime/application/README.md +14 -0
  75. package/dist/runtime/application/agent/ProgressiveAgentTools.js +92 -0
  76. package/dist/runtime/application/agent/StudioMcpAllowlist.js +10 -0
  77. package/dist/runtime/application/agent/StudioProjectTools.js +18 -0
  78. package/dist/runtime/application/agent/TaskEvidence.js +199 -0
  79. package/dist/runtime/application/buildTaskObservation.js +117 -0
  80. package/dist/runtime/application/code-execution/AuthoringSandboxEntry.js +50 -0
  81. package/dist/runtime/application/code-execution/BrowserCodeExecutor.js +35 -0
  82. package/dist/runtime/application/code-execution/BrowserCodeWorker.js +17 -0
  83. package/dist/runtime/application/code-execution/RemoteAuthoringDocument.js +82 -0
  84. package/dist/runtime/application/createSession.js +66 -0
  85. package/dist/runtime/application/createWorldAuthoringContext.js +400 -0
  86. package/dist/runtime/application/generation/GenerationOrchestrator.js +630 -0
  87. package/dist/runtime/application/generation/GenerationRuntime.js +215 -0
  88. package/dist/runtime/application/generation/PromptHybridWorldOrchestrator.js +289 -0
  89. package/dist/runtime/application/native-scene/CodeProject.js +215 -0
  90. package/dist/runtime/application/native-scene/CodeProjectModules.js +143 -0
  91. package/dist/runtime/application/native-scene/ExampleWorldCatalog.js +35 -0
  92. package/dist/runtime/application/native-scene/NativeArticulation.js +53 -0
  93. package/dist/runtime/application/native-scene/NativeEditableRegistry.js +150 -0
  94. package/dist/runtime/application/native-scene/NativeEnvironmentGeometry.js +85 -0
  95. package/dist/runtime/application/native-scene/NativeLightingInspection.js +33 -0
  96. package/dist/runtime/application/native-scene/NativeMaterialInspection.js +52 -0
  97. package/dist/runtime/application/native-scene/NativeOverlayCheckpoint.js +127 -0
  98. package/dist/runtime/application/native-scene/NativePhysicsGeometry.js +64 -0
  99. package/dist/runtime/application/native-scene/NativeRenderDiscovery.js +51 -0
  100. package/dist/runtime/application/native-scene/NativeSceneHost.js +406 -0
  101. package/dist/runtime/application/native-scene/NativeSceneInspection.js +203 -0
  102. package/dist/runtime/application/native-scene/NativeSceneOverlay.js +116 -0
  103. package/dist/runtime/application/native-scene/NativeSceneQuery.js +123 -0
  104. package/dist/runtime/application/native-scene/NativeSceneReview.js +132 -0
  105. package/dist/runtime/application/native-scene/NativeThreeModule.js +16 -0
  106. package/dist/runtime/application/native-scene/SceneObserver.js +97 -0
  107. package/dist/runtime/application/native-scene/VisualCapturePolicy.js +4 -0
  108. package/dist/runtime/application/object-forge/SceneObjectForge.js +263 -0
  109. package/dist/runtime/application/programmatic-assets/ProgrammaticAssetBuilder.js +59 -0
  110. package/dist/runtime/application/programmatic-assets/ProgrammaticAssetContract.js +22 -0
  111. package/dist/runtime/application/programmatic-assets/ThreeCodeAsset.js +40 -0
  112. package/dist/runtime/application/scene/CapabilityResolver.js +90 -0
  113. package/dist/runtime/application/scene/NativeEditableContracts.js +18 -0
  114. package/dist/runtime/application/scene/RequestWindow.js +54 -0
  115. package/dist/runtime/application/scene/SceneAgentTools.js +21 -0
  116. package/dist/runtime/application/scene/SceneContracts.js +49 -0
  117. package/dist/runtime/application/scene/SceneEditService.js +154 -0
  118. package/dist/runtime/application/scene/SceneFacade.js +356 -0
  119. package/dist/runtime/application/scene/SceneInteractionAdapters.js +41 -0
  120. package/dist/runtime/application/scene/SceneJobController.js +320 -0
  121. package/dist/runtime/application/scene/SceneLifecycle.js +57 -0
  122. package/dist/runtime/application/scene/ScenePackage.js +173 -0
  123. package/dist/runtime/application/scene/ScenePersistence.js +50 -0
  124. package/dist/runtime/application/scene/SceneProject.js +95 -0
  125. package/dist/runtime/application/scene/SceneSkillNames.js +5 -0
  126. package/dist/runtime/application/scene/StarterScene.js +56 -0
  127. package/dist/runtime/application/scene/WorldArchive.js +89 -0
  128. package/dist/runtime/application/scene/WorldDirectory.js +20 -0
  129. package/dist/runtime/application/scene/WorldDocument.js +76 -0
  130. package/dist/runtime/application/scene/WorldIO.js +103 -0
  131. package/dist/runtime/application/scene/WorldStorage.js +155 -0
  132. package/dist/runtime/application/skills/SkillRegistry.js +193 -0
  133. package/dist/runtime/application/skills/packs/acceptanceSkills.js +32 -0
  134. package/dist/runtime/application/skills/packs/affordanceSkills.js +36 -0
  135. package/dist/runtime/application/skills/packs/assetSkills.js +46 -0
  136. package/dist/runtime/application/skills/packs/authoringSkills.js +16 -0
  137. package/dist/runtime/application/skills/packs/batchSkills.js +22 -0
  138. package/dist/runtime/application/skills/packs/codeSkills.js +106 -0
  139. package/dist/runtime/application/skills/packs/generationSkills.js +45 -0
  140. package/dist/runtime/application/skills/packs/interactionSkills.js +46 -0
  141. package/dist/runtime/application/skills/packs/recoverySkills.js +80 -0
  142. package/dist/runtime/application/skills/packs/sceneSkills.js +24 -0
  143. package/dist/runtime/application/skills/packs/spatialSkills.js +35 -0
  144. package/dist/runtime/application/skills/packs/verificationSkills.js +14 -0
  145. package/dist/runtime/application/skills/packs/worldSkills.js +45 -0
  146. package/dist/runtime/application/skills/registerCoreSkills.js +31 -0
  147. package/dist/runtime/application/skills/skillPrimitives.js +4 -0
  148. package/dist/runtime/application/tasks/CabinetCupTask.js +76 -0
  149. package/dist/runtime/application/tasks.jsonl +67 -0
  150. package/dist/runtime/application/world-authoring/AuthoringAssetProducer.js +42 -0
  151. package/dist/runtime/application/world-authoring/AuthoringDiff.js +149 -0
  152. package/dist/runtime/application/world-authoring/AuthoringDocument.js +825 -0
  153. package/dist/runtime/application/world-authoring/AuthoringExecutionHost.js +109 -0
  154. package/dist/runtime/application/world-authoring/AuthoringIdentity.js +17 -0
  155. package/dist/runtime/application/world-authoring/AuthoringModelResolver.js +29 -0
  156. package/dist/runtime/application/world-authoring/AuthoringPatch.js +118 -0
  157. package/dist/runtime/application/world-authoring/AuthoringPromotionController.js +334 -0
  158. package/dist/runtime/application/world-authoring/AuthoringPromotionSource.js +126 -0
  159. package/dist/runtime/application/world-authoring/AuthoringRevisionHistory.js +144 -0
  160. package/dist/runtime/application/world-authoring/HeadlessImageExport.js +92 -0
  161. package/dist/runtime/application/world-authoring/ModelRef.js +62 -0
  162. package/dist/runtime/application/world-authoring/SceneGLBExport.js +88 -0
  163. package/dist/runtime/apps/mcp-server/AUTHORING.md +71 -0
  164. package/dist/runtime/apps/mcp-server/AgentMcpCompat.js +68 -0
  165. package/dist/runtime/apps/mcp-server/AuthoringSandboxEntry.js +1 -0
  166. package/dist/runtime/apps/mcp-server/AuthoringSandboxWorker.mjs +30 -0
  167. package/dist/runtime/apps/mcp-server/BuildEnvironment.js +17 -0
  168. package/dist/runtime/apps/mcp-server/CodeExecutor.js +71 -0
  169. package/dist/runtime/apps/mcp-server/DEPLOYMENT-PC2.md +42 -0
  170. package/dist/runtime/apps/mcp-server/DockerBuildRunner.js +66 -0
  171. package/dist/runtime/apps/mcp-server/FileAssetRepository.js +159 -0
  172. package/dist/runtime/apps/mcp-server/HeadlessAssetIO.js +8 -0
  173. package/dist/runtime/apps/mcp-server/HeadlessGLTFLoader.js +47 -0
  174. package/dist/runtime/apps/mcp-server/HeadlessWorldHost.js +157 -0
  175. package/dist/runtime/apps/mcp-server/IsolatedAuthoringExecutor.js +6 -0
  176. package/dist/runtime/apps/mcp-server/PROGRAMMATIC-ASSETS.md +116 -0
  177. package/dist/runtime/apps/mcp-server/ProgrammaticAssets.js +60 -0
  178. package/dist/runtime/apps/mcp-server/README.md +269 -0
  179. package/dist/runtime/apps/mcp-server/RemoteAuthoringDocument.js +1 -0
  180. package/dist/runtime/apps/mcp-server/SandboxBundle.js +13 -0
  181. package/dist/runtime/apps/mcp-server/SessionManager.js +148 -0
  182. package/dist/runtime/apps/mcp-server/StudioBridgeHttp.js +75 -0
  183. package/dist/runtime/apps/mcp-server/StudioLiveBridge.js +246 -0
  184. package/dist/runtime/apps/mcp-server/StudioProjectToolContracts.js +58 -0
  185. package/dist/runtime/apps/mcp-server/TransferHttp.js +47 -0
  186. package/dist/runtime/apps/mcp-server/TransferLimits.js +6 -0
  187. package/dist/runtime/apps/mcp-server/TransferStore.js +134 -0
  188. package/dist/runtime/apps/mcp-server/TrustedAuthoringWorker.mjs +16 -0
  189. package/dist/runtime/apps/mcp-server/VALIDATION.md +45 -0
  190. package/dist/runtime/apps/mcp-server/acceptance-evidence.json +332 -0
  191. package/dist/runtime/apps/mcp-server/errorDiagnostics.js +32 -0
  192. package/dist/runtime/apps/mcp-server/examples/code-house.js +24 -0
  193. package/dist/runtime/apps/mcp-server/examples/procedural-assets.js +85 -0
  194. package/dist/runtime/apps/mcp-server/main.mjs +82 -0
  195. package/dist/runtime/apps/mcp-server/registerTools.js +274 -0
  196. package/dist/runtime/apps/mcp-server/sandbox/run.mjs +23 -0
  197. package/dist/runtime/apps/mcp-server/security.js +23 -0
  198. package/dist/runtime/apps/mcp-server/tasks.jsonl +9 -0
  199. package/dist/runtime/apps/server/CapabilityAdapterRegistry.js +157 -0
  200. package/dist/runtime/apps/server/README.md +7 -0
  201. package/dist/runtime/apps/server/WorldRepository.js +338 -0
  202. package/dist/runtime/apps/server/WorldRepositoryHttp.js +96 -0
  203. package/dist/runtime/apps/server/openai-compatible-agent-gateway.mjs +278 -0
  204. package/dist/runtime/apps/server/tasks.jsonl +10 -0
  205. package/dist/runtime/apps/shared/node/WorldDiskStorage.js +62 -0
  206. package/dist/runtime/foundation/EventBus.js +26 -0
  207. package/dist/runtime/foundation/JsonGateway.js +47 -0
  208. package/dist/runtime/foundation/PngRgba.js +99 -0
  209. package/dist/runtime/foundation/PolicyEngine.js +21 -0
  210. package/dist/runtime/foundation/README.md +7 -0
  211. package/dist/runtime/foundation/TraceRecorder.js +76 -0
  212. package/dist/runtime/foundation/errors.js +8 -0
  213. package/dist/runtime/foundation/simulation/SimulationProfile.js +143 -0
  214. package/dist/runtime/foundation/version.js +2 -0
  215. package/dist/runtime/modules/agent/README.md +11 -0
  216. package/dist/runtime/modules/agent/ToolCallingAgent.js +19 -0
  217. package/dist/runtime/modules/agent/bootstrapWorld.js +10 -0
  218. package/dist/runtime/modules/agent/buildRecoveryProposals.js +533 -0
  219. package/dist/runtime/modules/agent/execution/AgentExecutionRules.js +128 -0
  220. package/dist/runtime/modules/agent/execution/AgentRunResults.js +55 -0
  221. package/dist/runtime/modules/agent/execution/AgentRunSession.js +393 -0
  222. package/dist/runtime/modules/agent/execution/AgentToolInvoker.js +40 -0
  223. package/dist/runtime/modules/agent/gateway/HttpLLMGateway.js +19 -0
  224. package/dist/runtime/modules/agent/prompt/index.js +52 -0
  225. package/dist/runtime/modules/agent/tasks.jsonl +94 -0
  226. package/dist/runtime/modules/artifact/ArtifactContentGate.js +144 -0
  227. package/dist/runtime/modules/artifact/ArtifactDescriptor.js +280 -0
  228. package/dist/runtime/modules/artifact/ArtifactImporter.js +185 -0
  229. package/dist/runtime/modules/artifact/ArtifactModule.js +111 -0
  230. package/dist/runtime/modules/artifact/ArtifactRegistry.js +197 -0
  231. package/dist/runtime/modules/artifact/IncrementalSha256.js +129 -0
  232. package/dist/runtime/modules/artifact/MemoryArtifactByteStore.js +115 -0
  233. package/dist/runtime/modules/artifact/README.md +7 -0
  234. package/dist/runtime/modules/artifact/storage/IndexedDbArtifactStore.js +67 -0
  235. package/dist/runtime/modules/artifact/tasks.jsonl +31 -0
  236. package/dist/runtime/modules/asset/AssetModule.js +416 -0
  237. package/dist/runtime/modules/asset/README.md +67 -0
  238. package/dist/runtime/modules/asset/loading/AssetLoader.js +157 -0
  239. package/dist/runtime/modules/asset/loading/GltfAssetLoader.js +61 -0
  240. package/dist/runtime/modules/asset/loading/builtins/BuiltinAssets.js +95 -0
  241. package/dist/runtime/modules/asset/loading/builtins/HouseDoor.js +33 -0
  242. package/dist/runtime/modules/asset/loading/builtins/IndustrialCabinet.js +103 -0
  243. package/dist/runtime/modules/asset/model/AssetInputContracts.js +139 -0
  244. package/dist/runtime/modules/asset/model/AssetRef.js +12 -0
  245. package/dist/runtime/modules/asset/model/MechanicalAssetDraft.js +172 -0
  246. package/dist/runtime/modules/asset/model/ProceduralTextureContract.js +24 -0
  247. package/dist/runtime/modules/asset/model/admission.js +117 -0
  248. package/dist/runtime/modules/asset/model/errors.js +6 -0
  249. package/dist/runtime/modules/asset/model/parts.js +27 -0
  250. package/dist/runtime/modules/asset/model/resourceBudget.js +10 -0
  251. package/dist/runtime/modules/asset/model/schema.js +150 -0
  252. package/dist/runtime/modules/asset/persistence/AssetManifestStore.js +78 -0
  253. package/dist/runtime/modules/asset/persistence/CompiledAssetStore.js +84 -0
  254. package/dist/runtime/modules/asset/persistence/LocalAssetLibrary.js +86 -0
  255. package/dist/runtime/modules/asset/persistence/LocalAssetLibraryStore.js +81 -0
  256. package/dist/runtime/modules/asset/production/AssetProductionPipeline.js +272 -0
  257. package/dist/runtime/modules/asset/production/AssetRecipe.js +91 -0
  258. package/dist/runtime/modules/asset/production/ProceduralTexture.js +85 -0
  259. package/dist/runtime/modules/asset/production/adapters/EmbodiedGenAdapter.js +45 -0
  260. package/dist/runtime/modules/asset/production/adapters/EmbodiedGenBundleAdapter.js +590 -0
  261. package/dist/runtime/modules/asset/production/compiler/AssetCompiler.js +173 -0
  262. package/dist/runtime/modules/asset/production/compiler/evidence/AnimationMotionEvidence.js +124 -0
  263. package/dist/runtime/modules/asset/production/compiler/evidence/StaticPanelEvidence.js +56 -0
  264. package/dist/runtime/modules/asset/production/compiler/gltfIO.js +6 -0
  265. package/dist/runtime/modules/asset/production/compiler/partGeometry.js +74 -0
  266. package/dist/runtime/modules/asset/production/compiler/passes/ArticulatedCollisionPass.js +63 -0
  267. package/dist/runtime/modules/asset/production/compiler/passes/ArticulationCandidatePass.js +48 -0
  268. package/dist/runtime/modules/asset/production/compiler/passes/AuthoringIntentPass.js +16 -0
  269. package/dist/runtime/modules/asset/production/compiler/passes/ColliderFallbackPass.js +30 -0
  270. package/dist/runtime/modules/asset/production/compiler/passes/CompileQualityPass.js +75 -0
  271. package/dist/runtime/modules/asset/production/compiler/passes/ExplicitDefinitionPass.js +20 -0
  272. package/dist/runtime/modules/asset/production/compiler/passes/GLTFInspectPass.js +34 -0
  273. package/dist/runtime/modules/asset/production/compiler/passes/GeometryPass.js +32 -0
  274. package/dist/runtime/modules/asset/production/compiler/passes/JointFramePass.js +116 -0
  275. package/dist/runtime/modules/asset/production/compiler/passes/KinematicEvidencePass.js +84 -0
  276. package/dist/runtime/modules/asset/production/compiler/passes/ManifestPass.js +63 -0
  277. package/dist/runtime/modules/asset/production/compiler/passes/NormalizeTransformPass.js +16 -0
  278. package/dist/runtime/modules/asset/production/compiler/passes/OptimizeGLBPass.js +23 -0
  279. package/dist/runtime/modules/asset/production/compiler/passes/PartColliderPass.js +50 -0
  280. package/dist/runtime/modules/asset/production/compiler/passes/PartGeometryEnrichmentPass.js +60 -0
  281. package/dist/runtime/modules/asset/production/compiler/passes/PartProposalPass.js +93 -0
  282. package/dist/runtime/modules/asset/production/compiler/passes/RemoteEnrichmentPass.js +32 -0
  283. package/dist/runtime/modules/asset/production/compiler/passes/ResourceBudgetPass.js +55 -0
  284. package/dist/runtime/modules/asset/production/compiler/passes/SegmentMaterializePass.js +203 -0
  285. package/dist/runtime/modules/asset/production/compiler/passes/SegmentationEvidencePass.js +43 -0
  286. package/dist/runtime/modules/asset/production/compiler/passes/SemanticHeuristicPass.js +33 -0
  287. package/dist/runtime/modules/asset/production/compiler/passes/StructurePass.js +60 -0
  288. package/dist/runtime/modules/asset/production/compiler/providers/HttpCompilerProvider.js +23 -0
  289. package/dist/runtime/modules/asset/production/verification/KinematicHypothesisScreen.js +198 -0
  290. package/dist/runtime/modules/asset/registry/AssetCatalog.js +72 -0
  291. package/dist/runtime/modules/asset/registry/AssetRegistry.js +51 -0
  292. package/dist/runtime/modules/asset/registry/manifests/index.js +173 -0
  293. package/dist/runtime/modules/asset/tasks.jsonl +87 -0
  294. package/dist/runtime/modules/generation/README.md +9 -0
  295. package/dist/runtime/modules/generation/connector/ConnectorArtifactClient.js +45 -0
  296. package/dist/runtime/modules/generation/connector/ConnectorCapabilityAdapter.js +169 -0
  297. package/dist/runtime/modules/generation/connector/ConnectorClient.js +192 -0
  298. package/dist/runtime/modules/generation/connector/ConnectorJobClient.js +167 -0
  299. package/dist/runtime/modules/generation/connector/ConnectorJobEventClient.js +179 -0
  300. package/dist/runtime/modules/generation/connector/ConnectorSession.js +202 -0
  301. package/dist/runtime/modules/generation/jobs/GenerationJobProjection.js +239 -0
  302. package/dist/runtime/modules/generation/jobs/GenerationJobReconciler.js +99 -0
  303. package/dist/runtime/modules/generation/jobs/GenerationJobStore.js +91 -0
  304. package/dist/runtime/modules/generation/jobs/GenerationJobTransportOverlay.js +50 -0
  305. package/dist/runtime/modules/generation/providers/ProviderRegistry.js +304 -0
  306. package/dist/runtime/modules/generation/tasks.jsonl +35 -0
  307. package/dist/runtime/modules/navigation/NavigationBackend.js +17 -0
  308. package/dist/runtime/modules/navigation/RecastNavigationBackend.js +263 -0
  309. package/dist/runtime/modules/physics/JoltPhysicsBackend.js +850 -0
  310. package/dist/runtime/modules/physics/PhysicsApiSurface.js +660 -0
  311. package/dist/runtime/modules/physics/PhysicsBackend.js +88 -0
  312. package/dist/runtime/modules/physics/RapierPhysicsBackend.js +414 -0
  313. package/dist/runtime/modules/rendering/README.md +7 -0
  314. package/dist/runtime/modules/rendering/RendererProbe.js +153 -0
  315. package/dist/runtime/modules/rendering/WebGpuPostFxPipeline.js +140 -0
  316. package/dist/runtime/modules/rendering/captureStill.js +54 -0
  317. package/dist/runtime/modules/rendering/createRenderer.js +76 -0
  318. package/dist/runtime/modules/rendering/disposeObject3D.js +37 -0
  319. package/dist/runtime/modules/rendering/loadGaussianSplatVisual.js +74 -0
  320. package/dist/runtime/modules/rendering/spatial/ThreeBvhRuntime.js +107 -0
  321. package/dist/runtime/modules/rendering/style/StylePack.js +34 -0
  322. package/dist/runtime/modules/rendering/style/StyleSystem.js +173 -0
  323. package/dist/runtime/modules/rendering/tasks.jsonl +7 -0
  324. package/dist/runtime/modules/world/README.md +13 -0
  325. package/dist/runtime/modules/world/build/WorldBuilder.js +170 -0
  326. package/dist/runtime/modules/world/compiler/PipelineEngine.js +32 -0
  327. package/dist/runtime/modules/world/compiler/WorldAdmission.js +43 -0
  328. package/dist/runtime/modules/world/compiler/WorldBehaviorCompiler.js +68 -0
  329. package/dist/runtime/modules/world/compiler/WorldCompilation.js +157 -0
  330. package/dist/runtime/modules/world/compiler/WorldComposer.js +201 -0
  331. package/dist/runtime/modules/world/compiler/WorldPhysicsAdmission.js +76 -0
  332. package/dist/runtime/modules/world/compiler/WorldRecompiler.js +356 -0
  333. package/dist/runtime/modules/world/compiler/WorldRetry.js +75 -0
  334. package/dist/runtime/modules/world/compiler/createWorldPipeline.js +379 -0
  335. package/dist/runtime/modules/world/content/blankWorld.js +35 -0
  336. package/dist/runtime/modules/world/content/environments.js +84 -0
  337. package/dist/runtime/modules/world/content/grandUrbanBlock.js +189 -0
  338. package/dist/runtime/modules/world/content/magic-cabin/README.md +28 -0
  339. package/dist/runtime/modules/world/content/magic-cabin/affordances.js +64 -0
  340. package/dist/runtime/modules/world/content/magic-cabin/cabinContents.js +7078 -0
  341. package/dist/runtime/modules/world/content/magic-cabin/lighting.js +26 -0
  342. package/dist/runtime/modules/world/content/magic-cabin/materials.js +20 -0
  343. package/dist/runtime/modules/world/content/magicCabin.js +190 -0
  344. package/dist/runtime/modules/world/content/monumentHall.js +154 -0
  345. package/dist/runtime/modules/world/content/ruinedCourtyard.js +196 -0
  346. package/dist/runtime/modules/world/content/suzhouGarden/README.md +141 -0
  347. package/dist/runtime/modules/world/content/suzhouGarden/index.js +137 -0
  348. package/dist/runtime/modules/world/content/suzhouGarden/src/arch.js +491 -0
  349. package/dist/runtime/modules/world/content/suzhouGarden/src/buildings.js +670 -0
  350. package/dist/runtime/modules/world/content/suzhouGarden/src/core.js +578 -0
  351. package/dist/runtime/modules/world/content/suzhouGarden/src/lod.js +127 -0
  352. package/dist/runtime/modules/world/content/suzhouGarden/src/main.js +642 -0
  353. package/dist/runtime/modules/world/content/suzhouGarden/src/nature.js +650 -0
  354. package/dist/runtime/modules/world/content/suzhouGarden/src/rockery.js +280 -0
  355. package/dist/runtime/modules/world/content/suzhouGarden/src/sky.js +242 -0
  356. package/dist/runtime/modules/world/content/suzhouGarden/src/water.js +215 -0
  357. package/dist/runtime/modules/world/content/woodlandWorkshop.js +192 -0
  358. package/dist/runtime/modules/world/content/yuanmingyuan/README.md +36 -0
  359. package/dist/runtime/modules/world/content/yuanmingyuan/arch.js +351 -0
  360. package/dist/runtime/modules/world/content/yuanmingyuan/buildings.js +490 -0
  361. package/dist/runtime/modules/world/content/yuanmingyuan/core.js +505 -0
  362. package/dist/runtime/modules/world/content/yuanmingyuan/index.js +101 -0
  363. package/dist/runtime/modules/world/content/yuanmingyuan/nature.js +435 -0
  364. package/dist/runtime/modules/world/content/yuanmingyuan/sky.js +169 -0
  365. package/dist/runtime/modules/world/content/yuanmingyuan/water.js +245 -0
  366. package/dist/runtime/modules/world/errors.js +9 -0
  367. package/dist/runtime/modules/world/generated/GeneratedWorldCoordinates.js +50 -0
  368. package/dist/runtime/modules/world/generated/GeneratedWorldLoader.js +297 -0
  369. package/dist/runtime/modules/world/runtime/CommandHistory.js +111 -0
  370. package/dist/runtime/modules/world/runtime/EntityCapabilityRegistry.js +165 -0
  371. package/dist/runtime/modules/world/runtime/NativeNavigationGeometry.js +84 -0
  372. package/dist/runtime/modules/world/runtime/NativePhysicsSnapshot.js +245 -0
  373. package/dist/runtime/modules/world/runtime/ObjectStore.js +31 -0
  374. package/dist/runtime/modules/world/runtime/ObjectTransform.js +62 -0
  375. package/dist/runtime/modules/world/runtime/ObservedEntity.js +37 -0
  376. package/dist/runtime/modules/world/runtime/ProjectCapabilities.js +240 -0
  377. package/dist/runtime/modules/world/runtime/SceneExtensions.js +36 -0
  378. package/dist/runtime/modules/world/runtime/ScenePresentation.js +101 -0
  379. package/dist/runtime/modules/world/runtime/SceneSerializer.js +281 -0
  380. package/dist/runtime/modules/world/runtime/WorldAuthority.js +41 -0
  381. package/dist/runtime/modules/world/runtime/WorldCollisionSignature.js +14 -0
  382. package/dist/runtime/modules/world/runtime/WorldCommands.js +503 -0
  383. package/dist/runtime/modules/world/runtime/WorldObservation.js +71 -0
  384. package/dist/runtime/modules/world/runtime/WorldQueries.js +340 -0
  385. package/dist/runtime/modules/world/runtime/WorldRecovery.js +78 -0
  386. package/dist/runtime/modules/world/runtime/WorldRuntime.js +806 -0
  387. package/dist/runtime/modules/world/runtime/affordance/ObjectAffordances.js +110 -0
  388. package/dist/runtime/modules/world/runtime/affordance/WorldAffordances.js +130 -0
  389. package/dist/runtime/modules/world/runtime/behavior/BehaviorCompiler.js +79 -0
  390. package/dist/runtime/modules/world/runtime/behavior/ProjectStateMachine.js +195 -0
  391. package/dist/runtime/modules/world/runtime/behavior/RuleGraph.js +70 -0
  392. package/dist/runtime/modules/world/runtime/behavior/RuleRuntime.js +115 -0
  393. package/dist/runtime/modules/world/runtime/graph/SceneGraph.js +390 -0
  394. package/dist/runtime/modules/world/runtime/interaction/ArticulationRuntime.js +214 -0
  395. package/dist/runtime/modules/world/runtime/interaction/CarryCapability.js +65 -0
  396. package/dist/runtime/modules/world/runtime/interaction/CarryRuntime.js +244 -0
  397. package/dist/runtime/modules/world/runtime/interaction/InteractionApproach.js +147 -0
  398. package/dist/runtime/modules/world/runtime/interaction/InteractionContract.js +57 -0
  399. package/dist/runtime/modules/world/runtime/interaction/ManipulationActions.js +7 -0
  400. package/dist/runtime/modules/world/runtime/interaction/NativePhysicalTarget.js +31 -0
  401. package/dist/runtime/modules/world/runtime/interaction/RecoveryRuntime.js +123 -0
  402. package/dist/runtime/modules/world/runtime/interaction/SettleRuntime.js +134 -0
  403. package/dist/runtime/modules/world/runtime/semantic/NativePhysicsState.js +89 -0
  404. package/dist/runtime/modules/world/runtime/semantic/SemanticWorldView.js +129 -0
  405. package/dist/runtime/modules/world/runtime/simulation/SimulationClock.js +89 -0
  406. package/dist/runtime/modules/world/runtime/simulation/SimulationSession.js +104 -0
  407. package/dist/runtime/modules/world/runtime/simulation/ThermalSystem.js +269 -0
  408. package/dist/runtime/modules/world/runtime/simulation/WorldTimeline.js +110 -0
  409. package/dist/runtime/modules/world/runtime/spatial/SpatialSnapshot.js +56 -0
  410. package/dist/runtime/modules/world/runtime/spatial/VisualMeshBounds.js +41 -0
  411. package/dist/runtime/modules/world/runtime/systems/AudioSystem.js +306 -0
  412. package/dist/runtime/modules/world/runtime/systems/Instrument.js +39 -0
  413. package/dist/runtime/modules/world/runtime/systems/InteractionSystem.js +806 -0
  414. package/dist/runtime/modules/world/runtime/systems/LocomotionSystem.js +281 -0
  415. package/dist/runtime/modules/world/runtime/systems/NavigationSystem.js +561 -0
  416. package/dist/runtime/modules/world/runtime/systems/PhysicsSystem.js +1752 -0
  417. package/dist/runtime/modules/world/runtime/systems/RenderingSystem.js +527 -0
  418. package/dist/runtime/modules/world/runtime/systems/SpatialSystem.js +402 -0
  419. package/dist/runtime/modules/world/spec/WorldIR.js +165 -0
  420. package/dist/runtime/modules/world/spec/WorldIRToolSchema.js +86 -0
  421. package/dist/runtime/modules/world/spec/WorldPlannerProposal.js +51 -0
  422. package/dist/runtime/modules/world/spec/WorldRevision.js +231 -0
  423. package/dist/runtime/modules/world/spec/WorldSpec.js +86 -0
  424. package/dist/runtime/modules/world/tasks.jsonl +530 -0
  425. package/dist/runtime/modules/world/verification/ArticulationVerifier.js +254 -0
  426. package/dist/runtime/modules/world/verification/Finding.js +105 -0
  427. package/dist/runtime/modules/world/verification/InteractionEvidence.js +73 -0
  428. package/dist/runtime/modules/world/verification/RepairEngine.js +49 -0
  429. package/dist/runtime/modules/world/verification/VisualLayoutAcceptance.js +58 -0
  430. package/dist/runtime/modules/world/verification/WorldAcceptance.js +176 -0
  431. package/dist/runtime/modules/world/verification/WorldValidator.js +67 -0
  432. package/dist/runtime/package-lock.json +16071 -0
  433. package/dist/runtime/package.json +106 -0
  434. package/dist/runtime/public/assets/cabinet.glb +0 -0
  435. package/dist/runtime/public/assets/grand-urban-block/clean_asphalt_diff_1k.jpg +0 -0
  436. package/dist/runtime/public/assets/grand-urban-block/clean_asphalt_nor_gl_1k.jpg +0 -0
  437. package/dist/runtime/public/assets/grand-urban-block/concrete_pavement_diff_1k.jpg +0 -0
  438. package/dist/runtime/public/assets/grand-urban-block/urban_street_01_1k.hdr +0 -0
  439. package/dist/runtime/public/assets/monument-hall/marble_diff_1k.jpg +0 -0
  440. package/dist/runtime/public/assets/monument-hall/marble_nor_gl_1k.jpg +0 -0
  441. package/dist/runtime/public/assets/monument-hall/marble_rough_1k.jpg +0 -0
  442. package/dist/runtime/public/assets/monument-hall/solitude_interior_1k.hdr +0 -0
  443. package/dist/runtime/public/assets/ruined-courtyard/courtyard_1k.hdr +0 -0
  444. package/dist/runtime/public/assets/ruined-courtyard/mossy_cobblestone_diff_1k.jpg +0 -0
  445. package/dist/runtime/public/assets/ruined-courtyard/mossy_cobblestone_nor_gl_1k.jpg +0 -0
  446. package/dist/runtime/public/assets/ruined-courtyard/mossy_sandstone_diff_1k.jpg +0 -0
  447. package/dist/schema-DT7K9NjP.js +165 -0
  448. package/dist/schema-DT7K9NjP.js.map +1 -0
  449. package/dist/suzhouGarden-Y3hny8j6.js +6150 -0
  450. package/dist/suzhouGarden-Y3hny8j6.js.map +1 -0
  451. package/dist/version-CHc-i8ch.js +5 -0
  452. package/dist/version-CHc-i8ch.js.map +1 -0
  453. package/dist/woodlandWorkshop-DsScU-cx.js +483 -0
  454. package/dist/woodlandWorkshop-DsScU-cx.js.map +1 -0
  455. package/dist/yuanmingyuan-DsFnPzzR.js +4955 -0
  456. package/dist/yuanmingyuan-DsFnPzzR.js.map +1 -0
  457. package/package.json +75 -4
@@ -0,0 +1,2687 @@
1
+ import { t as assetAdmission } from "./admission-CVEvsrdz.js";
2
+ import { o as canonicalAssetJson, r as assetDigest } from "./gltfIO-BzVKLyaL.js";
3
+ import { a as artifactImmutableSignature, c as normalizeArtifactLocation, i as ArtifactContractError, l as requireSafeArtifactId, n as createAssetModule, o as normalizeArtifactDescriptor, r as ARTIFACT_LEASE_HOLDER_KINDS, s as normalizeArtifactHash } from "./AssetModule-DME-XaFS.js";
4
+ import { r as encodePngRgba } from "./AssetRecipe-g8dZBhgJ.js";
5
+ import { t as validateAssetManifest } from "./schema-DT7K9NjP.js";
6
+ import { n as disposeObject3D } from "./disposeObject3D-DIMzy0FA.js";
7
+ import { a as sha256ArtifactHash, t as BUILTIN_ENVIRONMENT_IDS } from "./environments-HOe3sJXH.js";
8
+ import { t as ArticulationVerifier } from "./ArticulationVerifier-BfGxXY8V.js";
9
+ import { r as uniformScaleValue } from "./ObjectTransform-BlQUNK7c.js";
10
+ import * as z from "zod/v4";
11
+ import * as THREE from "three";
12
+ import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
13
+ // modules/artifact/ArtifactRegistry.js
14
+ const HOLDER_KIND_SET = new Set(ARTIFACT_LEASE_HOLDER_KINDS);
15
+ const SAFE_REASON = /^[A-Za-z0-9][A-Za-z0-9 ._:-]{0,199}$/;
16
+ const SAFE_CODE = /^[A-Z0-9][A-Z0-9._:-]{0,119}$/i;
17
+ const UNSAFE_REASON_RE = /https?:\/\/|Bearer\s+/i;
18
+ const clone$5 = (value) => value == null ? value : structuredClone(value);
19
+ function normalizeTime(value, field, { required = false } = {}) {
20
+ if (value == null || value === "") {
21
+ if (required) throw new ArtifactContractError("ARTIFACT_LEASE_INVALID", `Artifact lease requires ${field}`, { field });
22
+ return null;
23
+ }
24
+ const time = Date.parse(String(value));
25
+ if (!Number.isFinite(time)) throw new ArtifactContractError("ARTIFACT_LEASE_INVALID", `Artifact lease has invalid ${field}`, { field });
26
+ return new Date(time).toISOString();
27
+ }
28
+ function normalizeLease(value = {}, artifactId) {
29
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new ArtifactContractError("ARTIFACT_LEASE_INVALID", "Artifact lease must be an object");
30
+ const holder = value.holder;
31
+ if (!holder || typeof holder !== "object" || Array.isArray(holder)) throw new ArtifactContractError("ARTIFACT_LEASE_INVALID", "Artifact lease requires holder");
32
+ const holderKind = String(holder.kind || "");
33
+ if (!HOLDER_KIND_SET.has(holderKind)) throw new ArtifactContractError("ARTIFACT_LEASE_INVALID", `Unsupported artifact lease holder kind: ${holderKind}`);
34
+ const reason = String(value.reason || "").trim();
35
+ if (!SAFE_REASON.test(reason) || UNSAFE_REASON_RE.test(reason)) throw new ArtifactContractError("ARTIFACT_LEASE_INVALID", "Artifact lease reason is invalid");
36
+ const createdAt = normalizeTime(value.createdAt, "createdAt", { required: true });
37
+ const expiresAt = normalizeTime(value.expiresAt, "expiresAt");
38
+ if (expiresAt && Date.parse(expiresAt) <= Date.parse(createdAt)) throw new ArtifactContractError("ARTIFACT_LEASE_INVALID", "Artifact lease expiry must be after creation");
39
+ return {
40
+ id: requireSafeArtifactId(value.id, "lease.id"),
41
+ artifactId,
42
+ locationId: value.locationId == null ? null : requireSafeArtifactId(value.locationId, "lease.locationId"),
43
+ holder: {
44
+ kind: holderKind,
45
+ id: requireSafeArtifactId(holder.id, "lease.holder.id")
46
+ },
47
+ reason,
48
+ createdAt,
49
+ expiresAt
50
+ };
51
+ }
52
+ var ArtifactRegistry = class {
53
+ #now;
54
+ #artifacts = /* @__PURE__ */ new Map();
55
+ #hashIndex = /* @__PURE__ */ new Map();
56
+ #leases = /* @__PURE__ */ new Map();
57
+ constructor({ now = () => Date.now() } = {}) {
58
+ this.#now = now;
59
+ }
60
+ register(payload) {
61
+ const descriptor = normalizeArtifactDescriptor(payload);
62
+ const previous = this.#artifacts.get(descriptor.id);
63
+ if (previous) {
64
+ if (artifactImmutableSignature(previous) !== artifactImmutableSignature(descriptor)) throw new ArtifactContractError("ARTIFACT_IDENTITY_CONFLICT", "Artifact ID already exists with different immutable identity", { id: descriptor.id });
65
+ return this.get(descriptor.id);
66
+ }
67
+ this.#artifacts.set(descriptor.id, descriptor);
68
+ if (!this.#hashIndex.has(descriptor.hash)) this.#hashIndex.set(descriptor.hash, /* @__PURE__ */ new Set());
69
+ this.#hashIndex.get(descriptor.hash).add(descriptor.id);
70
+ return this.get(descriptor.id);
71
+ }
72
+ has(id) {
73
+ return this.#artifacts.has(id);
74
+ }
75
+ get(id) {
76
+ const artifact = this.#artifacts.get(id);
77
+ return artifact ? clone$5(artifact) : null;
78
+ }
79
+ list() {
80
+ return [...this.#artifacts.values()].map(clone$5).sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt) || a.id.localeCompare(b.id));
81
+ }
82
+ findByHash(hash) {
83
+ const canonical = normalizeArtifactHash(hash);
84
+ return [...this.#hashIndex.get(canonical) || []].sort();
85
+ }
86
+ updateLocation(id, locationPayload) {
87
+ const artifactId = requireSafeArtifactId(id);
88
+ const artifact = this.#artifacts.get(artifactId);
89
+ if (!artifact) throw new ArtifactContractError("ARTIFACT_NOT_FOUND", "Artifact does not exist", { id: artifactId });
90
+ const location = normalizeArtifactLocation(locationPayload, artifactId);
91
+ const next = clone$5(artifact);
92
+ const index = next.locations.findIndex((item) => item.id === location.id);
93
+ if (index === -1) next.locations.push(location);
94
+ else {
95
+ const previous = next.locations[index];
96
+ const accessConflict = previous.access && location.access && JSON.stringify(previous.access) !== JSON.stringify(location.access);
97
+ if (previous.kind !== location.kind || previous.scope !== location.scope || accessConflict) throw new ArtifactContractError("ARTIFACT_LOCATION_IDENTITY_CONFLICT", "Artifact location ID cannot change kind, scope, or active access identity", {
98
+ id: artifactId,
99
+ locationId: location.id
100
+ });
101
+ next.locations[index] = location;
102
+ }
103
+ this.#artifacts.set(artifactId, next);
104
+ return this.get(artifactId);
105
+ }
106
+ removeLocation(id, locationId) {
107
+ const artifactId = requireSafeArtifactId(id);
108
+ const locationKey = requireSafeArtifactId(locationId, "locationId");
109
+ const artifact = this.#artifacts.get(artifactId);
110
+ if (!artifact) throw new ArtifactContractError("ARTIFACT_NOT_FOUND", "Artifact does not exist", { id: artifactId });
111
+ if (!artifact.locations.some((item) => item.id === locationKey)) return {
112
+ removed: false,
113
+ artifact: this.get(artifactId)
114
+ };
115
+ if (this.isLeased(artifactId, { locationId: locationKey })) throw new ArtifactContractError("ARTIFACT_LOCATION_LEASED", "Artifact location is protected by an active lease", {
116
+ id: artifactId,
117
+ locationId: locationKey
118
+ });
119
+ const next = clone$5(artifact);
120
+ next.locations = next.locations.filter((item) => item.id !== locationKey);
121
+ this.#artifacts.set(artifactId, next);
122
+ return {
123
+ removed: true,
124
+ artifact: this.get(artifactId)
125
+ };
126
+ }
127
+ verifyIntegrity(id, evidence = {}) {
128
+ const artifactId = requireSafeArtifactId(id);
129
+ const artifact = this.#artifacts.get(artifactId);
130
+ if (!artifact) throw new ArtifactContractError("ARTIFACT_NOT_FOUND", "Artifact does not exist", { id: artifactId });
131
+ const hash = normalizeArtifactHash(evidence.hash, "integrity.hash");
132
+ const bytes = Number(evidence.bytes);
133
+ if (!Number.isSafeInteger(bytes) || bytes < 0) throw new ArtifactContractError("ARTIFACT_INTEGRITY_INVALID", "Integrity evidence bytes are invalid");
134
+ const mime = String(evidence.mime || "").trim().toLowerCase();
135
+ if (hash !== artifact.hash || bytes !== artifact.bytes || mime !== artifact.mime) throw new ArtifactContractError("ARTIFACT_INTEGRITY_MISMATCH", "Integrity evidence does not match the declared descriptor", { id: artifactId });
136
+ const verifiedAt = normalizeTime(evidence.verifiedAt, "verifiedAt", { required: true });
137
+ const method = String(evidence.method || "").trim();
138
+ if (!method || !SAFE_CODE.test(method)) throw new ArtifactContractError("ARTIFACT_INTEGRITY_INVALID", "Integrity verification method must be a stable safe identifier");
139
+ const next = clone$5(artifact);
140
+ next.integrity = {
141
+ state: "verified",
142
+ verifiedAt,
143
+ method,
144
+ rejection: null
145
+ };
146
+ this.#artifacts.set(artifactId, next);
147
+ return this.get(artifactId);
148
+ }
149
+ rejectIntegrity(id, evidence = {}) {
150
+ const artifactId = requireSafeArtifactId(id);
151
+ const artifact = this.#artifacts.get(artifactId);
152
+ if (!artifact) throw new ArtifactContractError("ARTIFACT_NOT_FOUND", "Artifact does not exist", { id: artifactId });
153
+ const code = String(evidence.code || "").trim();
154
+ if (!code || !SAFE_CODE.test(code)) throw new ArtifactContractError("ARTIFACT_INTEGRITY_INVALID", "Integrity rejection code must be a stable safe identifier");
155
+ const checkedAt = normalizeTime(evidence.checkedAt, "checkedAt", { required: true });
156
+ const next = clone$5(artifact);
157
+ next.integrity = {
158
+ state: "rejected",
159
+ verifiedAt: null,
160
+ method: null,
161
+ rejection: {
162
+ code,
163
+ checkedAt
164
+ }
165
+ };
166
+ this.#artifacts.set(artifactId, next);
167
+ return this.get(artifactId);
168
+ }
169
+ acquireLease(artifactId, leasePayload) {
170
+ const id = requireSafeArtifactId(artifactId);
171
+ const artifact = this.#artifacts.get(id);
172
+ if (!artifact) throw new ArtifactContractError("ARTIFACT_NOT_FOUND", "Artifact does not exist", { id });
173
+ const lease = normalizeLease(leasePayload, id);
174
+ if (lease.expiresAt && Date.parse(lease.expiresAt) <= this.#now()) throw new ArtifactContractError("ARTIFACT_LEASE_INVALID", "Artifact lease is already expired", { leaseId: lease.id });
175
+ if (lease.locationId && !artifact.locations.some((location) => location.id === lease.locationId)) throw new ArtifactContractError("ARTIFACT_LEASE_INVALID", "Artifact lease references an unknown location", {
176
+ id,
177
+ locationId: lease.locationId
178
+ });
179
+ const previous = this.#leases.get(lease.id);
180
+ if (previous && JSON.stringify(previous) !== JSON.stringify(lease)) throw new ArtifactContractError("ARTIFACT_LEASE_CONFLICT", "Artifact lease ID already exists with different semantics", { leaseId: lease.id });
181
+ this.#leases.set(lease.id, lease);
182
+ return clone$5(lease);
183
+ }
184
+ releaseLease(leaseId) {
185
+ const id = requireSafeArtifactId(leaseId, "leaseId");
186
+ return this.#leases.delete(id);
187
+ }
188
+ leasesFor(artifactId, { includeExpired = false } = {}) {
189
+ const id = requireSafeArtifactId(artifactId);
190
+ const now = this.#now();
191
+ return [...this.#leases.values()].filter((lease) => lease.artifactId === id && (includeExpired || !lease.expiresAt || Date.parse(lease.expiresAt) > now)).map(clone$5).sort((a, b) => a.id.localeCompare(b.id));
192
+ }
193
+ isLeased(artifactId, { locationId = null } = {}) {
194
+ const id = requireSafeArtifactId(artifactId);
195
+ const location = locationId == null ? null : requireSafeArtifactId(locationId, "locationId");
196
+ return this.leasesFor(id).some((lease) => lease.locationId == null || location == null || lease.locationId === location);
197
+ }
198
+ };
199
+ // modules/artifact/MemoryArtifactByteStore.js
200
+ const COMMIT_TOKEN = Symbol("artifact-byte-store-commit");
201
+ const cloneEntry = (entry) => entry ? {
202
+ key: entry.key,
203
+ artifactId: entry.artifactId,
204
+ hash: entry.hash,
205
+ mime: entry.mime,
206
+ bytes: entry.bytes,
207
+ data: new Uint8Array(entry.data)
208
+ } : null;
209
+ var MemoryArtifactByteWriter = class {
210
+ #store;
211
+ #artifactId;
212
+ #maxBytes;
213
+ #chunks = [];
214
+ #bytes = 0;
215
+ #state = "open";
216
+ constructor(store, { artifactId, maxBytes }) {
217
+ this.#store = store;
218
+ this.#artifactId = requireSafeArtifactId(artifactId);
219
+ this.#maxBytes = maxBytes;
220
+ }
221
+ get state() {
222
+ return this.#state;
223
+ }
224
+ get bytesWritten() {
225
+ return this.#bytes;
226
+ }
227
+ async write(chunk) {
228
+ if (this.#state !== "open") throw new ArtifactContractError("ARTIFACT_BYTE_STORE_STATE", "Artifact byte writer is not open");
229
+ if (!(chunk instanceof Uint8Array)) throw new ArtifactContractError("ARTIFACT_BYTE_STORE_INVALID", "Artifact byte writer requires Uint8Array chunks");
230
+ if (this.#bytes + chunk.byteLength > this.#maxBytes) throw new ArtifactContractError("ARTIFACT_BYTES_LIMIT", "Artifact temporary byte store exceeded maxBytes");
231
+ this.#chunks.push(new Uint8Array(chunk));
232
+ this.#bytes += chunk.byteLength;
233
+ }
234
+ async commit({ key, hash, mime, bytes }) {
235
+ if (this.#state !== "open") throw new ArtifactContractError("ARTIFACT_BYTE_STORE_STATE", "Artifact byte writer is not open");
236
+ const cacheKey = requireSafeArtifactId(key, "cacheKey");
237
+ const canonicalHash = normalizeArtifactHash(hash);
238
+ const expected = Number(bytes);
239
+ if (!Number.isSafeInteger(expected) || expected < 0 || expected !== this.#bytes) throw new ArtifactContractError("ARTIFACT_BYTE_STORE_INVALID", "Artifact byte store commit length mismatch");
240
+ const data = new Uint8Array(this.#bytes);
241
+ let offset = 0;
242
+ for (const chunk of this.#chunks) {
243
+ data.set(chunk, offset);
244
+ offset += chunk.byteLength;
245
+ }
246
+ const result = this.#store._commit(COMMIT_TOKEN, {
247
+ key: cacheKey,
248
+ artifactId: this.#artifactId,
249
+ hash: canonicalHash,
250
+ mime: String(mime || "").toLowerCase(),
251
+ bytes: expected,
252
+ data
253
+ });
254
+ this.#chunks = [];
255
+ this.#state = "committed";
256
+ return result;
257
+ }
258
+ async abort() {
259
+ if (this.#state === "open") {
260
+ this.#chunks = [];
261
+ this.#bytes = 0;
262
+ this.#state = "aborted";
263
+ }
264
+ }
265
+ };
266
+ var MemoryArtifactByteStore = class {
267
+ #entries = /* @__PURE__ */ new Map();
268
+ #hashIndex = /* @__PURE__ */ new Map();
269
+ restore(entry = {}) {
270
+ const key = requireSafeArtifactId(entry.key, "cacheKey");
271
+ const artifactId = requireSafeArtifactId(entry.artifactId);
272
+ const hash = normalizeArtifactHash(entry.hash);
273
+ const mime = String(entry.mime || "").trim().toLowerCase();
274
+ const bytes = Number(entry.bytes);
275
+ const data = entry.data instanceof Uint8Array ? new Uint8Array(entry.data) : null;
276
+ if (!mime || !Number.isSafeInteger(bytes) || bytes < 0 || !data || data.byteLength !== bytes) throw new ArtifactContractError("ARTIFACT_BYTE_STORE_INVALID", "Persisted Artifact cache entry is invalid", { key });
277
+ return this._commit(COMMIT_TOKEN, {
278
+ key,
279
+ artifactId,
280
+ hash,
281
+ mime,
282
+ bytes,
283
+ data
284
+ });
285
+ }
286
+ begin({ artifactId, maxBytes }) {
287
+ const limit = Number(maxBytes);
288
+ if (!Number.isSafeInteger(limit) || limit < 0) throw new ArtifactContractError("ARTIFACT_BYTES_LIMIT", "Artifact byte store maxBytes must be a non-negative safe integer");
289
+ return new MemoryArtifactByteWriter(this, {
290
+ artifactId,
291
+ maxBytes: limit
292
+ });
293
+ }
294
+ _commit(token, entry) {
295
+ if (token !== COMMIT_TOKEN) throw new ArtifactContractError("ARTIFACT_BYTE_STORE_STATE", "Artifact byte store commit is writer-managed only");
296
+ const previous = this.#entries.get(entry.key);
297
+ if (previous) {
298
+ if (previous.hash !== entry.hash || previous.bytes !== entry.bytes || previous.mime !== entry.mime || previous.artifactId !== entry.artifactId) throw new ArtifactContractError("ARTIFACT_CACHE_KEY_CONFLICT", "Artifact cache key already contains different content", { key: entry.key });
299
+ return {
300
+ key: entry.key,
301
+ hash: entry.hash,
302
+ mime: entry.mime,
303
+ bytes: entry.bytes
304
+ };
305
+ }
306
+ this.#entries.set(entry.key, entry);
307
+ if (!this.#hashIndex.has(entry.hash)) this.#hashIndex.set(entry.hash, /* @__PURE__ */ new Set());
308
+ this.#hashIndex.get(entry.hash).add(entry.key);
309
+ return {
310
+ key: entry.key,
311
+ hash: entry.hash,
312
+ mime: entry.mime,
313
+ bytes: entry.bytes
314
+ };
315
+ }
316
+ get(key) {
317
+ return cloneEntry(this.#entries.get(key));
318
+ }
319
+ remove(key) {
320
+ const entry = this.#entries.get(key);
321
+ if (!entry) return false;
322
+ this.#entries.delete(key);
323
+ const keys = this.#hashIndex.get(entry.hash);
324
+ keys?.delete(key);
325
+ if (keys && !keys.size) this.#hashIndex.delete(entry.hash);
326
+ return true;
327
+ }
328
+ findByHash(hash) {
329
+ const canonical = normalizeArtifactHash(hash);
330
+ return [...this.#hashIndex.get(canonical) || []].sort();
331
+ }
332
+ };
333
+ // modules/artifact/storage/IndexedDbArtifactStore.js
334
+ const DB_NAME = "agentscape-artifacts";
335
+ const DB_VERSION = 1;
336
+ const DESCRIPTOR_STORE = "descriptors";
337
+ const BYTE_STORE = "bytes";
338
+ const clone$4 = (value) => value == null ? value : structuredClone(value);
339
+ var IndexedDbArtifactStore = class {
340
+ constructor({ indexedDBImpl = globalThis.indexedDB } = {}) {
341
+ this.indexedDB = indexedDBImpl;
342
+ }
343
+ async open() {
344
+ if (!this.indexedDB) return null;
345
+ return new Promise((resolve, reject) => {
346
+ const request = this.indexedDB.open(DB_NAME, DB_VERSION);
347
+ request.onupgradeneeded = () => {
348
+ const db = request.result;
349
+ if (!db.objectStoreNames.contains(DESCRIPTOR_STORE)) db.createObjectStore(DESCRIPTOR_STORE);
350
+ if (!db.objectStoreNames.contains(BYTE_STORE)) db.createObjectStore(BYTE_STORE);
351
+ };
352
+ request.onsuccess = () => resolve(request.result);
353
+ request.onerror = () => reject(request.error);
354
+ });
355
+ }
356
+ async load() {
357
+ const db = await this.open();
358
+ if (!db) return {
359
+ descriptors: [],
360
+ entries: []
361
+ };
362
+ try {
363
+ const tx = db.transaction([DESCRIPTOR_STORE, BYTE_STORE], "readonly");
364
+ const readAll = (storeName) => new Promise((resolve, reject) => {
365
+ const request = tx.objectStore(storeName).getAll();
366
+ request.onsuccess = () => resolve(request.result || []);
367
+ request.onerror = () => reject(request.error);
368
+ });
369
+ const [descriptors, entries] = await Promise.all([readAll(DESCRIPTOR_STORE), readAll(BYTE_STORE)]);
370
+ return {
371
+ descriptors: descriptors.map(clone$4),
372
+ entries: entries.map((entry) => ({
373
+ ...clone$4(entry),
374
+ data: new Uint8Array(entry.data)
375
+ }))
376
+ };
377
+ } finally {
378
+ db.close();
379
+ }
380
+ }
381
+ async putArtifact(descriptor, entry) {
382
+ const db = await this.open();
383
+ if (!db) return false;
384
+ try {
385
+ await new Promise((resolve, reject) => {
386
+ const tx = db.transaction([DESCRIPTOR_STORE, BYTE_STORE], "readwrite");
387
+ tx.objectStore(DESCRIPTOR_STORE).put(clone$4(descriptor), descriptor.id);
388
+ tx.objectStore(BYTE_STORE).put({
389
+ ...clone$4(entry),
390
+ data: new Uint8Array(entry.data)
391
+ }, entry.key);
392
+ tx.oncomplete = resolve;
393
+ tx.onerror = () => reject(tx.error);
394
+ tx.onabort = () => reject(tx.error);
395
+ });
396
+ return true;
397
+ } finally {
398
+ db.close();
399
+ }
400
+ }
401
+ };
402
+ // modules/artifact/ArtifactModule.js
403
+ const localCacheLocations = (descriptor) => (descriptor.locations || []).filter((location) => location.kind === "local-cache" && location.state === "available" && location.access?.kind === "cache-key");
404
+ const persistedEntryFor = (descriptor, entriesByKey) => {
405
+ const locations = localCacheLocations(descriptor);
406
+ for (const location of locations) {
407
+ const entry = entriesByKey.get(location.access.key);
408
+ if (entry) return {
409
+ location,
410
+ entry
411
+ };
412
+ }
413
+ return null;
414
+ };
415
+ const assertVerifiedPersistence = (descriptor, entry) => {
416
+ const mismatches = [];
417
+ if (!(entry?.data instanceof Uint8Array)) mismatches.push("data");
418
+ if (entry?.artifactId !== descriptor.id) mismatches.push("artifactId");
419
+ if (entry?.hash !== descriptor.hash) mismatches.push("hash");
420
+ if (entry?.mime !== descriptor.mime) mismatches.push("mime");
421
+ if (entry?.bytes !== descriptor.bytes || entry?.data?.byteLength !== descriptor.bytes) mismatches.push("bytes");
422
+ if (!mismatches.length && sha256ArtifactHash([entry.data]) !== descriptor.hash) mismatches.push("contentHash");
423
+ if (mismatches.length) throw new ArtifactContractError("ARTIFACT_PERSISTENCE_INTEGRITY_MISMATCH", "Persisted Artifact bytes do not match the verified descriptor", {
424
+ artifactId: descriptor.id,
425
+ mismatches
426
+ });
427
+ };
428
+ function createArtifactModule({ registry = null, byteStore = null, persistentStore = void 0, now = () => Date.now() } = {}) {
429
+ const artifactRegistry = registry || new ArtifactRegistry({ now });
430
+ const artifactByteStore = byteStore || new MemoryArtifactByteStore();
431
+ const durableStore = persistentStore === void 0 ? globalThis.indexedDB ? new IndexedDbArtifactStore() : null : persistentStore;
432
+ let hydrated = false;
433
+ return Object.freeze({
434
+ registry: artifactRegistry,
435
+ byteStore: artifactByteStore,
436
+ persistentStore: durableStore,
437
+ async hydrate() {
438
+ if (hydrated) return {
439
+ artifacts: artifactRegistry.list().length,
440
+ restored: false
441
+ };
442
+ if (!durableStore?.load) {
443
+ hydrated = true;
444
+ return {
445
+ artifacts: artifactRegistry.list().length,
446
+ restored: false
447
+ };
448
+ }
449
+ const snapshot = await durableStore.load();
450
+ const entriesByKey = new Map((snapshot.entries || []).map((entry) => [entry.key, entry]));
451
+ for (const descriptor of snapshot.descriptors || []) {
452
+ const integrity = descriptor.integrity || { state: "declared" };
453
+ const nonLocalLocations = (descriptor.locations || []).filter((location) => location.kind !== "local-cache");
454
+ let verifiedPersistence = null;
455
+ if (integrity.state === "verified") {
456
+ verifiedPersistence = persistedEntryFor(descriptor, entriesByKey);
457
+ if (!verifiedPersistence) throw new ArtifactContractError("ARTIFACT_PERSISTENCE_INTEGRITY_MISMATCH", "Verified persisted Artifact has no matching local byte entry", { artifactId: descriptor.id });
458
+ assertVerifiedPersistence(descriptor, verifiedPersistence.entry);
459
+ }
460
+ artifactRegistry.register({
461
+ ...descriptor,
462
+ locations: nonLocalLocations,
463
+ integrity: { state: "declared" }
464
+ });
465
+ if (integrity.state === "verified") {
466
+ artifactByteStore.restore(verifiedPersistence.entry);
467
+ artifactRegistry.updateLocation(descriptor.id, verifiedPersistence.location);
468
+ artifactRegistry.verifyIntegrity(descriptor.id, {
469
+ hash: sha256ArtifactHash([verifiedPersistence.entry.data]),
470
+ bytes: verifiedPersistence.entry.data.byteLength,
471
+ mime: verifiedPersistence.entry.mime,
472
+ verifiedAt: new Date(now()).toISOString(),
473
+ method: "persisted-sha256-v1"
474
+ });
475
+ } else if (integrity.state === "rejected" && integrity.rejection) artifactRegistry.rejectIntegrity(descriptor.id, integrity.rejection);
476
+ }
477
+ hydrated = true;
478
+ return {
479
+ artifacts: (snapshot.descriptors || []).length,
480
+ entries: (snapshot.entries || []).length,
481
+ restored: true
482
+ };
483
+ },
484
+ async persistArtifact(artifactId, cacheKey) {
485
+ if (!durableStore?.putArtifact) return false;
486
+ const descriptor = artifactRegistry.get(artifactId);
487
+ const entry = artifactByteStore.get(cacheKey);
488
+ if (!descriptor || !entry) return false;
489
+ return durableStore.putArtifact(descriptor, entry);
490
+ }
491
+ });
492
+ }
493
+ // application/world-authoring/ModelRef.js
494
+ function clone$3(value) {
495
+ return JSON.parse(JSON.stringify(value));
496
+ }
497
+ const modelRefs = /* @__PURE__ */ new WeakMap();
498
+ function normalizeAssetRef(assetRef) {
499
+ const assetId = String(assetRef?.assetId ?? "").trim();
500
+ if (!assetId) throw new TypeError("World Authoring ModelRef requires a valid AssetRef");
501
+ return { assetId };
502
+ }
503
+ function normalizeAuthoringModelRef(reference) {
504
+ const source = reference?.source || reference;
505
+ if (source?.type === "url") {
506
+ const uri = String(source.uri || "").trim();
507
+ if (!uri) throw new TypeError("World Authoring ModelRef URL requires uri");
508
+ return { source: {
509
+ type: "url",
510
+ uri
511
+ } };
512
+ }
513
+ if (source?.type === "asset") return { source: {
514
+ type: "asset",
515
+ assetRef: normalizeAssetRef(source.assetRef)
516
+ } };
517
+ if (reference?.assetRef) return { source: {
518
+ type: "asset",
519
+ assetRef: normalizeAssetRef(reference.assetRef)
520
+ } };
521
+ if (typeof reference?.uri === "string" && reference.uri.trim()) return { source: {
522
+ type: "url",
523
+ uri: reference.uri.trim()
524
+ } };
525
+ throw new TypeError("World Authoring ModelRef requires a url or AssetRef source");
526
+ }
527
+ function markAuthoringModelRef(object, reference) {
528
+ if (!object?.isObject3D) throw new TypeError("World Authoring ModelRef target must be an Object3D");
529
+ modelRefs.set(object, normalizeAuthoringModelRef(reference));
530
+ return object;
531
+ }
532
+ function getAuthoringModelRef(object) {
533
+ const reference = object?.isObject3D ? modelRefs.get(object) || object.userData?.authoringModelRef : null;
534
+ return reference ? normalizeAuthoringModelRef(reference) : null;
535
+ }
536
+ function cloneAuthoringModelRef(reference) {
537
+ return clone$3(normalizeAuthoringModelRef(reference));
538
+ }
539
+ // application/world-authoring/AuthoringIdentity.js
540
+ const objectIds = /* @__PURE__ */ new WeakMap();
541
+ function getAuthoringObjectId(object) {
542
+ if (!object?.isObject3D) return null;
543
+ const sidecarId = objectIds.get(object);
544
+ if (sidecarId) return sidecarId;
545
+ const legacyId = object.userData?.authoringId;
546
+ return typeof legacyId === "string" && legacyId.trim() ? legacyId : null;
547
+ }
548
+ function setAuthoringObjectId(object, id) {
549
+ if (!object?.isObject3D) throw new TypeError("World Authoring identity target must be an Object3D");
550
+ const value = String(id || "").trim();
551
+ if (!value) throw new TypeError("World Authoring identity requires a non-empty id");
552
+ objectIds.set(object, value);
553
+ return value;
554
+ }
555
+ // application/world-authoring/AuthoringDocument.js
556
+ const AUTHORING_FORMAT = "agentscape-world-authoring";
557
+ const ROOT_ID = "root";
558
+ const RESERVED_USER_DATA = /* @__PURE__ */ new Set([
559
+ "authoringId",
560
+ "authoringGeometryId",
561
+ "authoringMaterialId",
562
+ "authoringTextureId",
563
+ "authoringSource",
564
+ "authoringModelRef",
565
+ "instanceId",
566
+ "visualDecoration",
567
+ "visualDecorationRoot",
568
+ "worldAuthoringRoot"
569
+ ]);
570
+ const PRIMITIVE_GEOMETRIES = /* @__PURE__ */ new Set([
571
+ "BoxGeometry",
572
+ "SphereGeometry",
573
+ "PlaneGeometry",
574
+ "CylinderGeometry",
575
+ "ConeGeometry",
576
+ "TorusGeometry"
577
+ ]);
578
+ const MATERIAL_TYPES = /* @__PURE__ */ new Set([
579
+ "MeshBasicMaterial",
580
+ "MeshStandardMaterial",
581
+ "MeshPhysicalMaterial"
582
+ ]);
583
+ const TEXTURE_SLOTS = [
584
+ "map",
585
+ "normalMap",
586
+ "roughnessMap",
587
+ "metalnessMap",
588
+ "emissiveMap",
589
+ "alphaMap",
590
+ "aoMap"
591
+ ];
592
+ const geometryIdsByObject = /* @__PURE__ */ new WeakMap();
593
+ const materialIdsByObject = /* @__PURE__ */ new WeakMap();
594
+ const textureIdsByObject = /* @__PURE__ */ new WeakMap();
595
+ const textureSourcesByObject = /* @__PURE__ */ new WeakMap();
596
+ function makeId(prefix) {
597
+ return `${prefix}_${THREE.MathUtils.generateUUID().toLowerCase()}`;
598
+ }
599
+ function structuredCloneJson(value) {
600
+ return JSON.parse(JSON.stringify(value));
601
+ }
602
+ function ensureObjectId(object, usedIds, isRoot = false) {
603
+ let id = isRoot ? ROOT_ID : getAuthoringObjectId(object);
604
+ if (typeof id !== "string" || !id.trim() || usedIds.has(id) && usedIds.get(id) !== object) id = isRoot ? ROOT_ID : makeId("node");
605
+ setAuthoringObjectId(object, id);
606
+ usedIds.set(id, object);
607
+ return id;
608
+ }
609
+ function ensureResourceId(resource, legacyKey, prefix, usedIds, sidecar) {
610
+ let id = sidecar.get(resource) || resource.userData?.[legacyKey];
611
+ if (typeof id !== "string" || !id.trim() || usedIds.has(id) && usedIds.get(id) !== resource) id = makeId(prefix);
612
+ sidecar.set(resource, id);
613
+ usedIds.set(id, resource);
614
+ return id;
615
+ }
616
+ function toJsonValue(value, seen = /* @__PURE__ */ new WeakSet()) {
617
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
618
+ if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
619
+ if (Array.isArray(value)) {
620
+ if (seen.has(value)) return void 0;
621
+ seen.add(value);
622
+ const result = value.map((item) => toJsonValue(item, seen)).filter((item) => item !== void 0);
623
+ seen.delete(value);
624
+ return result;
625
+ }
626
+ if (typeof value !== "object" || value?.isObject3D || value?.isMaterial || value?.isTexture) return void 0;
627
+ if (seen.has(value)) return void 0;
628
+ seen.add(value);
629
+ const result = {};
630
+ for (const [key, entry] of Object.entries(value)) {
631
+ if (RESERVED_USER_DATA.has(key)) continue;
632
+ const converted = toJsonValue(entry, seen);
633
+ if (converted !== void 0) result[key] = converted;
634
+ }
635
+ seen.delete(value);
636
+ return result;
637
+ }
638
+ function captureMetadata(object) {
639
+ const metadata = toJsonValue(object.userData);
640
+ return metadata && Object.keys(metadata).length > 0 ? metadata : void 0;
641
+ }
642
+ function transformComponent(object) {
643
+ return {
644
+ type: "Transform",
645
+ properties: {
646
+ position: object.position.toArray(),
647
+ quaternion: object.quaternion.toArray(),
648
+ scale: object.scale.toArray()
649
+ }
650
+ };
651
+ }
652
+ function geometryDefinition(geometry) {
653
+ if (PRIMITIVE_GEOMETRIES.has(geometry.type) && geometry.parameters) return {
654
+ type: geometry.type,
655
+ parameters: structuredCloneJson(geometry.parameters)
656
+ };
657
+ const json = geometry.toJSON();
658
+ delete json.metadata;
659
+ delete json.uuid;
660
+ delete json.userData;
661
+ return {
662
+ type: "BufferGeometry",
663
+ sourceType: geometry.type,
664
+ json
665
+ };
666
+ }
667
+ function textureSource(texture) {
668
+ const explicit = textureSourcesByObject.get(texture) || texture.userData?.authoringSource;
669
+ if (explicit && typeof explicit === "object") {
670
+ const source = toJsonValue(explicit);
671
+ if (source?.type === "url" && typeof source.uri === "string" && source.uri) return source;
672
+ }
673
+ const image = texture.image;
674
+ const uri = image?.currentSrc || image?.src;
675
+ if (typeof uri === "string" && uri) return {
676
+ type: "url",
677
+ uri
678
+ };
679
+ if (image?.data && Number.isFinite(image.width) && Number.isFinite(image.height)) {
680
+ const data = Array.from(image.data);
681
+ return {
682
+ type: "data",
683
+ width: image.width,
684
+ height: image.height,
685
+ dataType: image.data.constructor?.name || "Uint8Array",
686
+ data
687
+ };
688
+ }
689
+ throw new TypeError("World Authoring texture requires a URL or DataTexture source");
690
+ }
691
+ function textureDefinition(texture) {
692
+ return {
693
+ source: textureSource(texture),
694
+ mapping: texture.mapping,
695
+ wrapS: texture.wrapS,
696
+ wrapT: texture.wrapT,
697
+ magFilter: texture.magFilter,
698
+ minFilter: texture.minFilter,
699
+ anisotropy: texture.anisotropy,
700
+ format: texture.format,
701
+ type: texture.type,
702
+ colorSpace: texture.colorSpace,
703
+ flipY: texture.flipY,
704
+ premultiplyAlpha: texture.premultiplyAlpha,
705
+ generateMipmaps: texture.generateMipmaps,
706
+ offset: texture.offset.toArray(),
707
+ repeat: texture.repeat.toArray(),
708
+ center: texture.center.toArray(),
709
+ rotation: texture.rotation
710
+ };
711
+ }
712
+ function captureMaterial(material, textureIds, textures) {
713
+ if (!MATERIAL_TYPES.has(material.type)) throw new TypeError(`Unsupported World Authoring material: ${material.type}`);
714
+ const json = material.toJSON();
715
+ delete json.metadata;
716
+ delete json.uuid;
717
+ delete json.userData;
718
+ delete json.textures;
719
+ delete json.images;
720
+ for (const slot of TEXTURE_SLOTS) {
721
+ const texture = material[slot];
722
+ if (!texture) {
723
+ delete json[slot];
724
+ continue;
725
+ }
726
+ const textureId = ensureResourceId(texture, "authoringTextureId", "tex", textureIds, textureIdsByObject);
727
+ if (!textures[textureId]) textures[textureId] = textureDefinition(texture);
728
+ json[slot] = textureId;
729
+ }
730
+ return json;
731
+ }
732
+ function lightComponent(object) {
733
+ if (!(object.isAmbientLight || object.isHemisphereLight || object.isDirectionalLight || object.isPointLight || object.isSpotLight)) return null;
734
+ const base = {
735
+ color: `#${object.color.getHexString()}`,
736
+ intensity: object.intensity
737
+ };
738
+ if (object.isAmbientLight) return {
739
+ type: "AmbientLight",
740
+ properties: base
741
+ };
742
+ if (object.isHemisphereLight) return {
743
+ type: "HemisphereLight",
744
+ properties: {
745
+ ...base,
746
+ groundColor: `#${object.groundColor.getHexString()}`
747
+ }
748
+ };
749
+ if (object.isDirectionalLight) return {
750
+ type: "DirectionalLight",
751
+ properties: {
752
+ ...base,
753
+ target: object.target.position.toArray(),
754
+ castShadow: object.castShadow
755
+ }
756
+ };
757
+ if (object.isPointLight) return {
758
+ type: "PointLight",
759
+ properties: {
760
+ ...base,
761
+ distance: object.distance,
762
+ decay: object.decay,
763
+ castShadow: object.castShadow
764
+ }
765
+ };
766
+ if (object.isSpotLight) return {
767
+ type: "SpotLight",
768
+ properties: {
769
+ ...base,
770
+ distance: object.distance,
771
+ angle: object.angle,
772
+ penumbra: object.penumbra,
773
+ decay: object.decay,
774
+ target: object.target.position.toArray(),
775
+ castShadow: object.castShadow
776
+ }
777
+ };
778
+ return null;
779
+ }
780
+ function captureMeshResources(object, geometryIds, materialIds, textureIds, geometries, materials, textures) {
781
+ if (Array.isArray(object.material)) throw new TypeError("World Authoring v1 does not persist multi-material Mesh");
782
+ const geometryId = ensureResourceId(object.geometry, "authoringGeometryId", "geo", geometryIds, geometryIdsByObject);
783
+ const materialId = ensureResourceId(object.material, "authoringMaterialId", "mat", materialIds, materialIdsByObject);
784
+ if (!geometries[geometryId]) geometries[geometryId] = geometryDefinition(object.geometry);
785
+ if (!materials[materialId]) materials[materialId] = captureMaterial(object.material, textureIds, textures);
786
+ return {
787
+ geometryId,
788
+ materialId
789
+ };
790
+ }
791
+ function captureInstancedMesh(object) {
792
+ const matrices = Array.from(object.instanceMatrix.array);
793
+ const colors = object.instanceColor ? Array.from(object.instanceColor.array) : void 0;
794
+ return {
795
+ type: "InstancedMesh",
796
+ properties: {
797
+ count: object.count,
798
+ matrices,
799
+ ...colors ? { colors } : {},
800
+ castShadow: object.castShadow,
801
+ receiveShadow: object.receiveShadow
802
+ }
803
+ };
804
+ }
805
+ function sceneComponent(object, textureIds, textures) {
806
+ if (!object.isScene) return null;
807
+ const properties = {};
808
+ if (object.background?.isColor) properties.background = {
809
+ type: "color",
810
+ value: `#${object.background.getHexString()}`
811
+ };
812
+ else if (object.background?.isTexture) {
813
+ const textureId = ensureResourceId(object.background, "authoringTextureId", "tex", textureIds, textureIdsByObject);
814
+ if (!textures[textureId]) textures[textureId] = textureDefinition(object.background);
815
+ properties.background = {
816
+ type: "texture",
817
+ textureId
818
+ };
819
+ }
820
+ if (object.environment?.isTexture) {
821
+ const textureId = ensureResourceId(object.environment, "authoringTextureId", "tex", textureIds, textureIdsByObject);
822
+ if (!textures[textureId]) textures[textureId] = textureDefinition(object.environment);
823
+ properties.environment = { textureId };
824
+ }
825
+ if (object.fog?.isFog) properties.fog = {
826
+ type: "Fog",
827
+ color: `#${object.fog.color.getHexString()}`,
828
+ near: object.fog.near,
829
+ far: object.fog.far
830
+ };
831
+ else if (object.fog?.isFogExp2) properties.fog = {
832
+ type: "FogExp2",
833
+ color: `#${object.fog.color.getHexString()}`,
834
+ density: object.fog.density
835
+ };
836
+ if (Number.isFinite(object.backgroundBlurriness)) properties.backgroundBlurriness = object.backgroundBlurriness;
837
+ if (Number.isFinite(object.backgroundIntensity)) properties.backgroundIntensity = object.backgroundIntensity;
838
+ if (Number.isFinite(object.environmentIntensity)) properties.environmentIntensity = object.environmentIntensity;
839
+ return {
840
+ type: "Scene",
841
+ properties
842
+ };
843
+ }
844
+ function captureNode(object, geometryIds, materialIds, textureIds, geometries, materials, textures) {
845
+ const components = { transform: transformComponent(object) };
846
+ const modelRef = getAuthoringModelRef(object);
847
+ if (modelRef) components.modelRef = {
848
+ type: "ModelRef",
849
+ properties: cloneAuthoringModelRef(modelRef)
850
+ };
851
+ else if (object.isScene) components.scene = sceneComponent(object, textureIds, textures);
852
+ else if (object.isInstancedMesh) {
853
+ const { geometryId, materialId } = captureMeshResources(object, geometryIds, materialIds, textureIds, geometries, materials, textures);
854
+ components.instancedMesh = captureInstancedMesh(object);
855
+ components.geometry = {
856
+ type: "GeometryRef",
857
+ properties: { geometryId }
858
+ };
859
+ components.material = {
860
+ type: "MaterialRef",
861
+ properties: { materialId }
862
+ };
863
+ } else if (object.isMesh) {
864
+ const { geometryId, materialId } = captureMeshResources(object, geometryIds, materialIds, textureIds, geometries, materials, textures);
865
+ components.mesh = {
866
+ type: "Mesh",
867
+ properties: {
868
+ castShadow: object.castShadow,
869
+ receiveShadow: object.receiveShadow
870
+ }
871
+ };
872
+ components.geometry = {
873
+ type: "GeometryRef",
874
+ properties: { geometryId }
875
+ };
876
+ components.material = {
877
+ type: "MaterialRef",
878
+ properties: { materialId }
879
+ };
880
+ } else {
881
+ const light = lightComponent(object);
882
+ if (light) components.light = light;
883
+ else if (!(object.isGroup || object.type === "Object3D")) throw new TypeError(`Unsupported World Authoring object: ${object.type}`);
884
+ }
885
+ const node = {
886
+ id: getAuthoringObjectId(object),
887
+ name: object.name || void 0,
888
+ visible: object.visible === false ? false : void 0,
889
+ components
890
+ };
891
+ const metadata = captureMetadata(object);
892
+ if (metadata) node.metadata = metadata;
893
+ return node;
894
+ }
895
+ function captureAuthoringState(root) {
896
+ if (!root?.isObject3D) throw new TypeError("World Authoring capture requires an Object3D root");
897
+ const state = {
898
+ version: 1,
899
+ rootId: ROOT_ID,
900
+ nodesById: {},
901
+ childIdsById: {},
902
+ parentIdById: {},
903
+ geometries: {},
904
+ materials: {},
905
+ textures: {}
906
+ };
907
+ const objectIds = /* @__PURE__ */ new Map();
908
+ const geometryIds = /* @__PURE__ */ new Map();
909
+ const materialIds = /* @__PURE__ */ new Map();
910
+ const textureIds = /* @__PURE__ */ new Map();
911
+ function visit(object, parentId = null, isRoot = false) {
912
+ const id = ensureObjectId(object, objectIds, isRoot);
913
+ const node = captureNode(object, geometryIds, materialIds, textureIds, state.geometries, state.materials, state.textures);
914
+ node.id = id;
915
+ state.nodesById[id] = node;
916
+ state.parentIdById[id] = parentId;
917
+ state.childIdsById[id] = [];
918
+ if (!node.components.modelRef) for (const child of object.children) {
919
+ const childId = visit(child, id, false);
920
+ state.childIdsById[id].push(childId);
921
+ }
922
+ return id;
923
+ }
924
+ state.rootId = visit(root, null, true);
925
+ return state;
926
+ }
927
+ function denormalizeNode(id, state) {
928
+ const node = state.nodesById[id];
929
+ if (!node) throw new TypeError(`Missing World Authoring node: ${id}`);
930
+ const childIds = state.childIdsById[id] || [];
931
+ if (node.components?.modelRef && childIds.length > 0) throw new TypeError("World Authoring ModelRef node cannot contain authored children");
932
+ const children = childIds.map((childId) => denormalizeNode(childId, state));
933
+ return {
934
+ ...structuredCloneJson(node),
935
+ ...children.length ? { children } : {}
936
+ };
937
+ }
938
+ function exportAuthoringDocument(state) {
939
+ if (!state || state.version !== 1 || !state.rootId) throw new TypeError("Invalid World Authoring state");
940
+ return {
941
+ format: AUTHORING_FORMAT,
942
+ version: 1,
943
+ root: denormalizeNode(state.rootId, state),
944
+ ...Object.keys(state.geometries || {}).length ? { geometries: structuredCloneJson(state.geometries) } : {},
945
+ ...Object.keys(state.materials || {}).length ? { materials: structuredCloneJson(state.materials) } : {},
946
+ ...Object.keys(state.textures || {}).length ? { textures: structuredCloneJson(state.textures) } : {}
947
+ };
948
+ }
949
+ function parseAuthoringDocument(document) {
950
+ if (!document || document.format !== "agentscape-world-authoring") throw new TypeError(`World Authoring document format must be ${AUTHORING_FORMAT}`);
951
+ if (document.version !== 1) throw new TypeError(`Unsupported World Authoring document version: ${document.version}`);
952
+ if (!document.root || typeof document.root.id !== "string") throw new TypeError("World Authoring document requires a root node");
953
+ const state = {
954
+ version: 1,
955
+ rootId: document.root.id,
956
+ nodesById: {},
957
+ childIdsById: {},
958
+ parentIdById: {},
959
+ geometries: structuredCloneJson(document.geometries || {}),
960
+ materials: structuredCloneJson(document.materials || {}),
961
+ textures: structuredCloneJson(document.textures || {})
962
+ };
963
+ function insert(node, parentId) {
964
+ if (!node || typeof node.id !== "string" || !node.id) throw new TypeError("World Authoring node id is required");
965
+ if (state.nodesById[node.id]) throw new TypeError(`Duplicate World Authoring node id: ${node.id}`);
966
+ const { children = [], ...record } = node;
967
+ if (record.components?.modelRef && children.length > 0) throw new TypeError("World Authoring ModelRef node cannot contain authored children");
968
+ state.nodesById[node.id] = structuredCloneJson(record);
969
+ state.parentIdById[node.id] = parentId;
970
+ state.childIdsById[node.id] = [];
971
+ for (const child of children) {
972
+ insert(child, node.id);
973
+ state.childIdsById[node.id].push(child.id);
974
+ }
975
+ }
976
+ insert(document.root, null);
977
+ return state;
978
+ }
979
+ function createPrimitiveGeometry(definition) {
980
+ const p = definition.parameters || {};
981
+ switch (definition.type) {
982
+ case "BoxGeometry": return new THREE.BoxGeometry(p.width, p.height, p.depth, p.widthSegments, p.heightSegments, p.depthSegments);
983
+ case "SphereGeometry": return new THREE.SphereGeometry(p.radius, p.widthSegments, p.heightSegments, p.phiStart, p.phiLength, p.thetaStart, p.thetaLength);
984
+ case "PlaneGeometry": return new THREE.PlaneGeometry(p.width, p.height, p.widthSegments, p.heightSegments);
985
+ case "CylinderGeometry": return new THREE.CylinderGeometry(p.radiusTop, p.radiusBottom, p.height, p.radialSegments, p.heightSegments, p.openEnded, p.thetaStart, p.thetaLength);
986
+ case "ConeGeometry": return new THREE.ConeGeometry(p.radius, p.height, p.radialSegments, p.heightSegments, p.openEnded, p.thetaStart, p.thetaLength);
987
+ case "TorusGeometry": return new THREE.TorusGeometry(p.radius, p.tube, p.radialSegments, p.tubularSegments, p.arc);
988
+ default: return null;
989
+ }
990
+ }
991
+ function hydrateGeometries(definitions) {
992
+ const geometries = {};
993
+ for (const [id, definition] of Object.entries(definitions || {})) {
994
+ let geometry = createPrimitiveGeometry(definition);
995
+ if (!geometry && definition.type === "BufferGeometry" && definition.json) geometry = new THREE.BufferGeometryLoader().parse(definition.json);
996
+ if (!geometry) throw new TypeError(`Unsupported World Authoring geometry: ${definition.type}`);
997
+ geometryIdsByObject.set(geometry, id);
998
+ geometries[id] = geometry;
999
+ }
1000
+ return geometries;
1001
+ }
1002
+ const TYPED_ARRAYS = {
1003
+ Uint8Array,
1004
+ Uint8ClampedArray,
1005
+ Uint16Array,
1006
+ Uint32Array,
1007
+ Int8Array,
1008
+ Int16Array,
1009
+ Int32Array,
1010
+ Float32Array,
1011
+ Float64Array
1012
+ };
1013
+ function hydrateTextureSource(source) {
1014
+ if (source?.type === "data") {
1015
+ const ArrayType = TYPED_ARRAYS[source.dataType] || Uint8Array;
1016
+ const texture = new THREE.DataTexture(new ArrayType(source.data || []), source.width, source.height);
1017
+ texture.needsUpdate = true;
1018
+ return texture;
1019
+ }
1020
+ if (source?.type === "url" && typeof source.uri === "string" && source.uri) {
1021
+ let texture;
1022
+ if (typeof document !== "undefined") texture = new THREE.TextureLoader().load(source.uri);
1023
+ else texture = new THREE.Texture();
1024
+ textureSourcesByObject.set(texture, structuredCloneJson(source));
1025
+ return texture;
1026
+ }
1027
+ throw new TypeError("Unsupported World Authoring texture source");
1028
+ }
1029
+ function hydrateTextures(definitions) {
1030
+ const textures = {};
1031
+ for (const [id, definition] of Object.entries(definitions || {})) {
1032
+ const texture = hydrateTextureSource(definition.source);
1033
+ texture.mapping = definition.mapping ?? texture.mapping;
1034
+ texture.wrapS = definition.wrapS ?? texture.wrapS;
1035
+ texture.wrapT = definition.wrapT ?? texture.wrapT;
1036
+ texture.magFilter = definition.magFilter ?? texture.magFilter;
1037
+ texture.minFilter = definition.minFilter ?? texture.minFilter;
1038
+ texture.anisotropy = definition.anisotropy ?? texture.anisotropy;
1039
+ texture.format = definition.format ?? texture.format;
1040
+ texture.type = definition.type ?? texture.type;
1041
+ texture.colorSpace = definition.colorSpace ?? texture.colorSpace;
1042
+ texture.flipY = definition.flipY ?? texture.flipY;
1043
+ texture.premultiplyAlpha = definition.premultiplyAlpha ?? texture.premultiplyAlpha;
1044
+ texture.generateMipmaps = definition.generateMipmaps ?? texture.generateMipmaps;
1045
+ if (Array.isArray(definition.offset)) texture.offset.fromArray(definition.offset);
1046
+ if (Array.isArray(definition.repeat)) texture.repeat.fromArray(definition.repeat);
1047
+ if (Array.isArray(definition.center)) texture.center.fromArray(definition.center);
1048
+ if (Number.isFinite(definition.rotation)) texture.rotation = definition.rotation;
1049
+ textureIdsByObject.set(texture, id);
1050
+ if (definition.source) textureSourcesByObject.set(texture, structuredCloneJson(definition.source));
1051
+ textures[id] = texture;
1052
+ }
1053
+ return textures;
1054
+ }
1055
+ function hydrateMaterials(definitions, textures) {
1056
+ const materials = {};
1057
+ const loader = new THREE.MaterialLoader();
1058
+ loader.setTextures(textures);
1059
+ for (const [id, definition] of Object.entries(definitions || {})) {
1060
+ if (!MATERIAL_TYPES.has(definition.type)) throw new TypeError(`Unsupported World Authoring material: ${definition.type}`);
1061
+ const material = loader.parse(definition);
1062
+ materialIdsByObject.set(material, id);
1063
+ materials[id] = material;
1064
+ }
1065
+ return materials;
1066
+ }
1067
+ function applyTransform(object, component) {
1068
+ const p = component?.properties || {};
1069
+ if (Array.isArray(p.position) && p.position.length === 3) object.position.fromArray(p.position);
1070
+ if (Array.isArray(p.quaternion) && p.quaternion.length === 4) object.quaternion.fromArray(p.quaternion);
1071
+ if (Array.isArray(p.scale) && p.scale.length === 3) object.scale.fromArray(p.scale);
1072
+ }
1073
+ function createLight(component) {
1074
+ const p = component.properties || {};
1075
+ const color = p.color ?? "#ffffff";
1076
+ let light;
1077
+ switch (component.type) {
1078
+ case "AmbientLight":
1079
+ light = new THREE.AmbientLight(color, p.intensity);
1080
+ break;
1081
+ case "HemisphereLight":
1082
+ light = new THREE.HemisphereLight(color, p.groundColor ?? "#ffffff", p.intensity);
1083
+ break;
1084
+ case "DirectionalLight":
1085
+ light = new THREE.DirectionalLight(color, p.intensity);
1086
+ if (Array.isArray(p.target)) light.target.position.fromArray(p.target);
1087
+ light.castShadow = Boolean(p.castShadow);
1088
+ break;
1089
+ case "PointLight":
1090
+ light = new THREE.PointLight(color, p.intensity, p.distance, p.decay);
1091
+ light.castShadow = Boolean(p.castShadow);
1092
+ break;
1093
+ case "SpotLight":
1094
+ light = new THREE.SpotLight(color, p.intensity, p.distance, p.angle, p.penumbra, p.decay);
1095
+ if (Array.isArray(p.target)) light.target.position.fromArray(p.target);
1096
+ light.castShadow = Boolean(p.castShadow);
1097
+ break;
1098
+ default: throw new TypeError(`Unsupported World Authoring light: ${component.type}`);
1099
+ }
1100
+ return light;
1101
+ }
1102
+ function requiredMeshResources(components, geometries, materials) {
1103
+ const geometryId = components.geometry?.properties?.geometryId;
1104
+ const materialId = components.material?.properties?.materialId;
1105
+ const geometry = geometries[geometryId];
1106
+ const material = materials[materialId];
1107
+ if (!geometry) throw new TypeError(`Missing World Authoring geometry: ${geometryId}`);
1108
+ if (!material) throw new TypeError(`Missing World Authoring material: ${materialId}`);
1109
+ return {
1110
+ geometry,
1111
+ material
1112
+ };
1113
+ }
1114
+ function createInstancedMesh(component, geometry, material) {
1115
+ const p = component.properties || {};
1116
+ const count = Number(p.count);
1117
+ if (!Number.isInteger(count) || count < 0) throw new TypeError("Invalid World Authoring InstancedMesh count");
1118
+ const object = new THREE.InstancedMesh(geometry, material, count);
1119
+ const matrices = p.matrices || [];
1120
+ if (matrices.length !== count * 16) throw new TypeError("Invalid World Authoring InstancedMesh matrix data");
1121
+ object.instanceMatrix.array.set(matrices);
1122
+ object.instanceMatrix.needsUpdate = true;
1123
+ if (Array.isArray(p.colors)) {
1124
+ if (p.colors.length !== count * 3) throw new TypeError("Invalid World Authoring InstancedMesh color data");
1125
+ object.instanceColor = new THREE.InstancedBufferAttribute(new Float32Array(p.colors), 3);
1126
+ object.instanceColor.needsUpdate = true;
1127
+ }
1128
+ object.castShadow = Boolean(p.castShadow);
1129
+ object.receiveShadow = Boolean(p.receiveShadow);
1130
+ return object;
1131
+ }
1132
+ function applySceneComponent(scene, component, textures) {
1133
+ const p = component?.properties || {};
1134
+ const background = p.background;
1135
+ if (background?.type === "color") scene.background = new THREE.Color(background.value);
1136
+ else if (background?.type === "texture") scene.background = textures[background.textureId] || null;
1137
+ if (p.environment?.textureId) scene.environment = textures[p.environment.textureId] || null;
1138
+ if (p.fog?.type === "Fog") scene.fog = new THREE.Fog(p.fog.color, p.fog.near, p.fog.far);
1139
+ else if (p.fog?.type === "FogExp2") scene.fog = new THREE.FogExp2(p.fog.color, p.fog.density);
1140
+ if (Number.isFinite(p.backgroundBlurriness)) scene.backgroundBlurriness = p.backgroundBlurriness;
1141
+ if (Number.isFinite(p.backgroundIntensity)) scene.backgroundIntensity = p.backgroundIntensity;
1142
+ if (Number.isFinite(p.environmentIntensity)) scene.environmentIntensity = p.environmentIntensity;
1143
+ }
1144
+ function createObjectForNode(node, geometries, materials, textures) {
1145
+ const components = node.components || {};
1146
+ let object;
1147
+ if (components.modelRef) throw new TypeError("World Authoring ModelRef requires loadAsync()");
1148
+ else if (components.scene) {
1149
+ object = new THREE.Scene();
1150
+ applySceneComponent(object, components.scene, textures);
1151
+ } else if (components.instancedMesh) {
1152
+ const { geometry, material } = requiredMeshResources(components, geometries, materials);
1153
+ object = createInstancedMesh(components.instancedMesh, geometry, material);
1154
+ } else if (components.mesh) {
1155
+ const { geometry, material } = requiredMeshResources(components, geometries, materials);
1156
+ object = new THREE.Mesh(geometry, material);
1157
+ object.castShadow = Boolean(components.mesh.properties?.castShadow);
1158
+ object.receiveShadow = Boolean(components.mesh.properties?.receiveShadow);
1159
+ } else if (components.light) object = createLight(components.light);
1160
+ else object = new THREE.Group();
1161
+ object.name = node.name || "";
1162
+ object.visible = node.visible !== false;
1163
+ object.userData = node.metadata ? structuredCloneJson(node.metadata) : {};
1164
+ setAuthoringObjectId(object, node.id);
1165
+ applyTransform(object, components.transform);
1166
+ return object;
1167
+ }
1168
+ function hydrateAuthoringState(state) {
1169
+ if (!state || state.version !== 1) throw new TypeError("Invalid World Authoring state");
1170
+ const geometries = hydrateGeometries(state.geometries);
1171
+ const textures = hydrateTextures(state.textures);
1172
+ const materials = hydrateMaterials(state.materials, textures);
1173
+ function build(id) {
1174
+ const node = state.nodesById[id];
1175
+ if (!node) throw new TypeError(`Missing World Authoring node: ${id}`);
1176
+ const object = createObjectForNode(node, geometries, materials, textures);
1177
+ for (const childId of state.childIdsById[id] || []) object.add(build(childId));
1178
+ return object;
1179
+ }
1180
+ return build(state.rootId);
1181
+ }
1182
+ async function createObjectForNodeAsync(node, geometries, materials, textures, resolveModel) {
1183
+ const components = node.components || {};
1184
+ if (!components.modelRef) return createObjectForNode(node, geometries, materials, textures);
1185
+ if (typeof resolveModel !== "function") throw new TypeError("World Authoring loadAsync requires resolveModel for ModelRef");
1186
+ const reference = cloneAuthoringModelRef(components.modelRef.properties);
1187
+ const resolved = await resolveModel(reference, node);
1188
+ if (!resolved?.isObject3D) throw new TypeError("World Authoring ModelRef resolver must return an Object3D");
1189
+ const object = new THREE.Group();
1190
+ object.name = node.name || "";
1191
+ object.visible = node.visible !== false;
1192
+ object.userData = node.metadata ? structuredCloneJson(node.metadata) : {};
1193
+ setAuthoringObjectId(object, node.id);
1194
+ markAuthoringModelRef(object, reference);
1195
+ applyTransform(object, components.transform);
1196
+ object.add(resolved);
1197
+ return object;
1198
+ }
1199
+ async function hydrateAuthoringStateAsync(state, { resolveModel } = {}) {
1200
+ if (!state || state.version !== 1) throw new TypeError("Invalid World Authoring state");
1201
+ const geometries = hydrateGeometries(state.geometries);
1202
+ const textures = hydrateTextures(state.textures);
1203
+ const materials = hydrateMaterials(state.materials, textures);
1204
+ async function build(id) {
1205
+ const node = state.nodesById[id];
1206
+ if (!node) throw new TypeError("Missing World Authoring node: " + id);
1207
+ const object = await createObjectForNodeAsync(node, geometries, materials, textures, resolveModel);
1208
+ for (const childId of state.childIdsById[id] || []) object.add(await build(childId));
1209
+ return object;
1210
+ }
1211
+ return build(state.rootId);
1212
+ }
1213
+ // application/world-authoring/AuthoringDiff.js
1214
+ const AUTHORING_DIFF_FORMAT = "agentscape-world-authoring-diff";
1215
+ function clone$2(value) {
1216
+ return value === void 0 ? void 0 : JSON.parse(JSON.stringify(value));
1217
+ }
1218
+ function canonical(value) {
1219
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
1220
+ if (Array.isArray(value)) return "[" + value.map(canonical).join(",") + "]";
1221
+ return "{" + Object.keys(value).sort().map((key) => JSON.stringify(key) + ":" + canonical(value[key])).join(",") + "}";
1222
+ }
1223
+ function same(a, b) {
1224
+ return canonical(a) === canonical(b);
1225
+ }
1226
+ function flatten(document) {
1227
+ const state = parseAuthoringDocument(document);
1228
+ const records = {};
1229
+ for (const [id, node] of Object.entries(state.nodesById)) {
1230
+ const parentId = state.parentIdById[id];
1231
+ records[id] = {
1232
+ id,
1233
+ parentId,
1234
+ index: (parentId == null ? [id] : state.childIdsById[parentId] || []).indexOf(id),
1235
+ node: clone$2(node)
1236
+ };
1237
+ }
1238
+ return {
1239
+ state,
1240
+ records
1241
+ };
1242
+ }
1243
+ function diffResourcePool(beforePool = {}, afterPool = {}) {
1244
+ const added = [];
1245
+ const removed = [];
1246
+ const updated = [];
1247
+ for (const id of Object.keys(afterPool).sort()) if (!(id in beforePool)) added.push({
1248
+ id,
1249
+ value: clone$2(afterPool[id])
1250
+ });
1251
+ else if (!same(beforePool[id], afterPool[id])) updated.push({
1252
+ id,
1253
+ before: clone$2(beforePool[id]),
1254
+ after: clone$2(afterPool[id])
1255
+ });
1256
+ for (const id of Object.keys(beforePool).sort()) if (!(id in afterPool)) removed.push({
1257
+ id,
1258
+ value: clone$2(beforePool[id])
1259
+ });
1260
+ return {
1261
+ added,
1262
+ removed,
1263
+ updated
1264
+ };
1265
+ }
1266
+ function diffAuthoringDocuments(before, after) {
1267
+ if (before?.format !== "agentscape-world-authoring" || before?.version !== 1) throw new TypeError("World Authoring diff requires a valid before document");
1268
+ if (after?.format !== "agentscape-world-authoring" || after?.version !== 1) throw new TypeError("World Authoring diff requires a valid after document");
1269
+ const left = flatten(before);
1270
+ const right = flatten(after);
1271
+ const added = [];
1272
+ const removed = [];
1273
+ const updated = [];
1274
+ const moved = [];
1275
+ for (const id of Object.keys(right.records).sort()) {
1276
+ const next = right.records[id];
1277
+ const previous = left.records[id];
1278
+ if (!previous) {
1279
+ added.push(clone$2(next));
1280
+ continue;
1281
+ }
1282
+ if (!same(previous.node, next.node)) updated.push({
1283
+ id,
1284
+ before: clone$2(previous.node),
1285
+ after: clone$2(next.node)
1286
+ });
1287
+ if (previous.parentId !== next.parentId || previous.index !== next.index) moved.push({
1288
+ id,
1289
+ from: {
1290
+ parentId: previous.parentId,
1291
+ index: previous.index
1292
+ },
1293
+ to: {
1294
+ parentId: next.parentId,
1295
+ index: next.index
1296
+ }
1297
+ });
1298
+ }
1299
+ for (const id of Object.keys(left.records).sort()) if (!right.records[id]) removed.push(clone$2(left.records[id]));
1300
+ const geometries = diffResourcePool(left.state.geometries, right.state.geometries);
1301
+ const materials = diffResourcePool(left.state.materials, right.state.materials);
1302
+ const textures = diffResourcePool(left.state.textures, right.state.textures);
1303
+ const empty = added.length === 0 && removed.length === 0 && updated.length === 0 && moved.length === 0 && geometries.added.length === 0 && geometries.removed.length === 0 && geometries.updated.length === 0 && materials.added.length === 0 && materials.removed.length === 0 && materials.updated.length === 0 && textures.added.length === 0 && textures.removed.length === 0 && textures.updated.length === 0;
1304
+ return {
1305
+ format: AUTHORING_DIFF_FORMAT,
1306
+ version: 1,
1307
+ empty,
1308
+ nodes: {
1309
+ added,
1310
+ removed,
1311
+ updated,
1312
+ moved
1313
+ },
1314
+ resources: {
1315
+ geometries,
1316
+ materials,
1317
+ textures
1318
+ }
1319
+ };
1320
+ }
1321
+ function canonicalizeAuthoringDocument(document) {
1322
+ parseAuthoringDocument(document);
1323
+ return canonical(document);
1324
+ }
1325
+ // application/world-authoring/AuthoringPatch.js
1326
+ function clone$1(value) {
1327
+ return JSON.parse(JSON.stringify(value));
1328
+ }
1329
+ function mergeObject(base, patch) {
1330
+ if (!patch || typeof patch !== "object" || Array.isArray(patch)) return clone$1(patch);
1331
+ const result = { ...base || {} };
1332
+ for (const [key, value] of Object.entries(patch)) {
1333
+ if (value === void 0) continue;
1334
+ if (value && typeof value === "object" && !Array.isArray(value) && result[key] && typeof result[key] === "object" && !Array.isArray(result[key])) result[key] = mergeObject(result[key], value);
1335
+ else result[key] = clone$1(value);
1336
+ }
1337
+ return result;
1338
+ }
1339
+ function removeSubtree(state, id) {
1340
+ if (id === state.rootId) throw new TypeError("World Authoring patch cannot remove the root");
1341
+ if (!state.nodesById[id]) throw new TypeError(`World Authoring patch node not found: ${id}`);
1342
+ for (const childId of [...state.childIdsById[id] || []]) removeSubtree(state, childId);
1343
+ const parentId = state.parentIdById[id];
1344
+ if (parentId && state.childIdsById[parentId]) state.childIdsById[parentId] = state.childIdsById[parentId].filter((childId) => childId !== id);
1345
+ delete state.nodesById[id];
1346
+ delete state.childIdsById[id];
1347
+ delete state.parentIdById[id];
1348
+ }
1349
+ function insertNode(state, node, parentId, index) {
1350
+ if (!state.nodesById[parentId]) throw new TypeError(`World Authoring patch parent not found: ${parentId}`);
1351
+ if (state.nodesById[parentId].components?.modelRef) throw new TypeError("World Authoring patch cannot add authored children to ModelRef");
1352
+ if (!node || typeof node.id !== "string" || !node.id) throw new TypeError("World Authoring patch added node requires an id");
1353
+ if (state.nodesById[node.id]) throw new TypeError(`World Authoring patch duplicate node id: ${node.id}`);
1354
+ const { children = [], ...record } = clone$1(node);
1355
+ state.nodesById[node.id] = record;
1356
+ state.parentIdById[node.id] = parentId;
1357
+ state.childIdsById[node.id] = [];
1358
+ const siblings = state.childIdsById[parentId];
1359
+ const insertAt = Number.isInteger(index) ? Math.max(0, Math.min(index, siblings.length)) : siblings.length;
1360
+ siblings.splice(insertAt, 0, node.id);
1361
+ for (const child of children) insertNode(state, child, node.id);
1362
+ }
1363
+ function mergeResources(target, additions, label) {
1364
+ for (const [id, definition] of Object.entries(additions || {})) {
1365
+ if (target[id] && JSON.stringify(target[id]) !== JSON.stringify(definition)) throw new TypeError(`World Authoring patch ${label} id conflict: ${id}`);
1366
+ target[id] = clone$1(definition);
1367
+ }
1368
+ }
1369
+ function patchAuthoringDocument(document, patch = {}) {
1370
+ const state = parseAuthoringDocument(document);
1371
+ mergeResources(state.geometries, patch.geometries, "geometry");
1372
+ mergeResources(state.materials, patch.materials, "material");
1373
+ mergeResources(state.textures, patch.textures, "texture");
1374
+ for (const change of patch.update || []) {
1375
+ if (!change || typeof change.id !== "string") throw new TypeError("World Authoring patch update requires an id");
1376
+ const node = state.nodesById[change.id];
1377
+ if (!node) throw new TypeError(`World Authoring patch node not found: ${change.id}`);
1378
+ const { id, ...updates } = change;
1379
+ state.nodesById[id] = mergeObject(node, updates);
1380
+ state.nodesById[id].id = id;
1381
+ }
1382
+ for (const id of patch.remove || []) removeSubtree(state, id);
1383
+ for (const addition of patch.add || []) {
1384
+ if (!addition || typeof addition.parentId !== "string" || !addition.node) throw new TypeError("World Authoring patch add requires parentId and node");
1385
+ insertNode(state, addition.node, addition.parentId, addition.index);
1386
+ }
1387
+ return exportAuthoringDocument(state);
1388
+ }
1389
+ // application/world-authoring/AuthoringRevisionHistory.js
1390
+ function clone(value) {
1391
+ return value == null ? value : JSON.parse(JSON.stringify(value));
1392
+ }
1393
+ function normalizeLimit(value) {
1394
+ const limit = Number(value ?? 64);
1395
+ if (!Number.isInteger(limit) || limit < 2) throw new TypeError("World Authoring revision history limit must be an integer >= 2");
1396
+ return limit;
1397
+ }
1398
+ var AuthoringRevisionHistory = class {
1399
+ constructor({ limit = 64, now = () => (/* @__PURE__ */ new Date()).toISOString() } = {}) {
1400
+ this.limit = normalizeLimit(limit);
1401
+ this.now = now;
1402
+ this.entries = [];
1403
+ this.cursor = -1;
1404
+ this.sequence = 0;
1405
+ }
1406
+ reset(document, { label = "Loaded world", source = "load" } = {}) {
1407
+ parseAuthoringDocument(document);
1408
+ this.entries = [];
1409
+ this.cursor = -1;
1410
+ this.sequence = 0;
1411
+ return this.commit(document, {
1412
+ label,
1413
+ source,
1414
+ force: true
1415
+ });
1416
+ }
1417
+ commit(document, { label = "", source = "manual", force = false } = {}) {
1418
+ parseAuthoringDocument(document);
1419
+ const snapshot = clone(document);
1420
+ const canonical = canonicalizeAuthoringDocument(snapshot);
1421
+ const current = this.entries[this.cursor];
1422
+ if (!force && current && canonicalizeAuthoringDocument(current.document) === canonical) return {
1423
+ created: false,
1424
+ revision: this.describe(current)
1425
+ };
1426
+ if (this.cursor < this.entries.length - 1) this.entries.splice(this.cursor + 1);
1427
+ const entry = {
1428
+ id: `rev_${String(++this.sequence).padStart(6, "0")}`,
1429
+ index: this.cursor + 1,
1430
+ label: String(label || ""),
1431
+ source: String(source || "manual"),
1432
+ createdAt: this.now(),
1433
+ document: snapshot
1434
+ };
1435
+ this.entries.push(entry);
1436
+ this.cursor = this.entries.length - 1;
1437
+ while (this.entries.length > this.limit) {
1438
+ this.entries.shift();
1439
+ this.cursor -= 1;
1440
+ }
1441
+ this.reindex();
1442
+ return {
1443
+ created: true,
1444
+ revision: this.describe(this.entries[this.cursor])
1445
+ };
1446
+ }
1447
+ reindex() {
1448
+ this.entries.forEach((entry, index) => {
1449
+ entry.index = index;
1450
+ });
1451
+ }
1452
+ describe(entry) {
1453
+ if (!entry) return null;
1454
+ return {
1455
+ id: entry.id,
1456
+ index: entry.index,
1457
+ label: entry.label,
1458
+ source: entry.source,
1459
+ createdAt: entry.createdAt
1460
+ };
1461
+ }
1462
+ list() {
1463
+ return this.entries.map((entry) => ({
1464
+ ...this.describe(entry),
1465
+ current: entry === this.entries[this.cursor]
1466
+ }));
1467
+ }
1468
+ current() {
1469
+ return this.describe(this.entries[this.cursor]);
1470
+ }
1471
+ currentDocument() {
1472
+ return clone(this.entries[this.cursor]?.document || null);
1473
+ }
1474
+ getDocument(revisionId) {
1475
+ const entry = this.entries.find((item) => item.id === revisionId);
1476
+ if (!entry) throw new TypeError(`World Authoring revision not found: ${revisionId}`);
1477
+ return clone(entry.document);
1478
+ }
1479
+ canUndo() {
1480
+ return this.cursor > 0;
1481
+ }
1482
+ canRedo() {
1483
+ return this.cursor >= 0 && this.cursor < this.entries.length - 1;
1484
+ }
1485
+ undo() {
1486
+ if (!this.canUndo()) return null;
1487
+ this.cursor -= 1;
1488
+ return {
1489
+ revision: this.current(),
1490
+ document: this.currentDocument()
1491
+ };
1492
+ }
1493
+ redo() {
1494
+ if (!this.canRedo()) return null;
1495
+ this.cursor += 1;
1496
+ return {
1497
+ revision: this.current(),
1498
+ document: this.currentDocument()
1499
+ };
1500
+ }
1501
+ diff(fromRevisionId, toRevisionId) {
1502
+ return diffAuthoringDocuments(this.getDocument(fromRevisionId), this.getDocument(toRevisionId));
1503
+ }
1504
+ };
1505
+ // application/world-authoring/AuthoringExecutionHost.js
1506
+ function createThreeNamespace(GLTFLoaderClass) {
1507
+ class AuthoringGLTFLoader extends GLTFLoaderClass {
1508
+ async loadAsync(url, onProgress) {
1509
+ const gltf = await super.loadAsync(url, onProgress);
1510
+ if (gltf?.scene) markAuthoringModelRef(gltf.scene, { uri: String(url) });
1511
+ return gltf;
1512
+ }
1513
+ load(url, onLoad, onProgress, onError) {
1514
+ return super.load(url, (gltf) => {
1515
+ if (gltf?.scene) markAuthoringModelRef(gltf.scene, { uri: String(url) });
1516
+ onLoad?.(gltf);
1517
+ }, onProgress, onError);
1518
+ }
1519
+ }
1520
+ return Object.freeze({
1521
+ ...THREE,
1522
+ GLTFLoader: AuthoringGLTFLoader
1523
+ });
1524
+ }
1525
+ function createAuthoringExecutionHost({ gltfLoaderClass = GLTFLoader, requestFrame = globalThis.requestAnimationFrame?.bind(globalThis), cancelFrame = globalThis.cancelAnimationFrame?.bind(globalThis), setTimeoutImpl = globalThis.setTimeout?.bind(globalThis), clearTimeoutImpl = globalThis.clearTimeout?.bind(globalThis), setIntervalImpl = globalThis.setInterval?.bind(globalThis), clearIntervalImpl = globalThis.clearInterval?.bind(globalThis) } = {}) {
1526
+ const frames = /* @__PURE__ */ new Set();
1527
+ const timeouts = /* @__PURE__ */ new Set();
1528
+ const intervals = /* @__PURE__ */ new Set();
1529
+ const authoringThree = createThreeNamespace(gltfLoaderClass);
1530
+ const requestAnimationFrame = (callback) => {
1531
+ if (typeof requestFrame !== "function") throw new TypeError("requestAnimationFrame is unavailable");
1532
+ let id = null;
1533
+ id = requestFrame((time) => {
1534
+ frames.delete(id);
1535
+ callback(time);
1536
+ });
1537
+ frames.add(id);
1538
+ return id;
1539
+ };
1540
+ const cancelAnimationFrame = (id) => {
1541
+ frames.delete(id);
1542
+ cancelFrame?.(id);
1543
+ };
1544
+ const setTimeout = (callback, delay = 0, ...args) => {
1545
+ if (typeof setTimeoutImpl !== "function") throw new TypeError("setTimeout is unavailable");
1546
+ let id = null;
1547
+ id = setTimeoutImpl((...values) => {
1548
+ timeouts.delete(id);
1549
+ callback(...values);
1550
+ }, delay, ...args);
1551
+ timeouts.add(id);
1552
+ return id;
1553
+ };
1554
+ const clearTimeout = (id) => {
1555
+ timeouts.delete(id);
1556
+ clearTimeoutImpl?.(id);
1557
+ };
1558
+ const setInterval = (callback, delay = 0, ...args) => {
1559
+ if (typeof setIntervalImpl !== "function") throw new TypeError("setInterval is unavailable");
1560
+ const id = setIntervalImpl(callback, delay, ...args);
1561
+ intervals.add(id);
1562
+ return id;
1563
+ };
1564
+ const clearInterval = (id) => {
1565
+ intervals.delete(id);
1566
+ clearIntervalImpl?.(id);
1567
+ };
1568
+ const clear = () => {
1569
+ for (const id of frames) cancelFrame?.(id);
1570
+ for (const id of timeouts) clearTimeoutImpl?.(id);
1571
+ for (const id of intervals) clearIntervalImpl?.(id);
1572
+ frames.clear();
1573
+ timeouts.clear();
1574
+ intervals.clear();
1575
+ };
1576
+ return {
1577
+ THREE: authoringThree,
1578
+ requestAnimationFrame,
1579
+ cancelAnimationFrame,
1580
+ setTimeout,
1581
+ clearTimeout,
1582
+ setInterval,
1583
+ clearInterval,
1584
+ clear,
1585
+ diagnostics: () => ({
1586
+ frames: frames.size,
1587
+ timeouts: timeouts.size,
1588
+ intervals: intervals.size
1589
+ })
1590
+ };
1591
+ }
1592
+ // application/createWorldAuthoringContext.js
1593
+ const AsyncFunction = Object.getPrototypeOf(async function() {}).constructor;
1594
+ function createWorldAuthoringContext(world, { historyLimit = 64, now = () => (/* @__PURE__ */ new Date()).toISOString(), presentationMode = "overlay", executionHost = createAuthoringExecutionHost(), executeCode = null } = {}) {
1595
+ if (!world || !world.rendering && !executeCode) throw new TypeError("World authoring requires a rendering presentation or isolated code executor");
1596
+ const presentation = world.rendering;
1597
+ const root = new THREE.Scene();
1598
+ root.name = "$llm-world";
1599
+ setAuthoringObjectId(root, "root");
1600
+ presentation?.addAuthoringScene(root, { mode: presentationMode });
1601
+ const frameHandlers = /* @__PURE__ */ new Set();
1602
+ const revisions = new AuthoringRevisionHistory({
1603
+ limit: historyLimit,
1604
+ now
1605
+ });
1606
+ let disposed = false;
1607
+ let promotedNodes = /* @__PURE__ */ new Set();
1608
+ const suppressed = /* @__PURE__ */ new Map();
1609
+ const restoreVisibility = () => {
1610
+ for (const [object, state] of suppressed) Object.defineProperty(object, "visible", {
1611
+ configurable: true,
1612
+ enumerable: true,
1613
+ writable: true,
1614
+ value: state.visible
1615
+ });
1616
+ suppressed.clear();
1617
+ };
1618
+ const suppressVisibility = () => {
1619
+ root.traverse((object) => {
1620
+ if (promotedNodes.has(getAuthoringObjectId(object))) {
1621
+ if (suppressed.has(object)) return;
1622
+ const state = { visible: object.visible };
1623
+ suppressed.set(object, state);
1624
+ Object.defineProperty(object, "visible", {
1625
+ configurable: true,
1626
+ enumerable: true,
1627
+ get: () => false,
1628
+ set: (value) => {
1629
+ state.visible = value;
1630
+ }
1631
+ });
1632
+ }
1633
+ });
1634
+ };
1635
+ const setPromotedNodes = (ids = []) => {
1636
+ restoreVisibility();
1637
+ promotedNodes = new Set(ids);
1638
+ suppressVisibility();
1639
+ };
1640
+ const assertActive = () => {
1641
+ if (disposed) throw new Error("World authoring context is disposed");
1642
+ };
1643
+ const changed = () => world.events?.emit?.("authoring.changed", {});
1644
+ const clear = () => {
1645
+ assertActive();
1646
+ restoreVisibility();
1647
+ frameHandlers.clear();
1648
+ executionHost.clear();
1649
+ for (const child of [...root.children]) {
1650
+ root.remove(child);
1651
+ disposeObject3D(child);
1652
+ }
1653
+ root.background = null;
1654
+ root.environment = null;
1655
+ root.fog = null;
1656
+ root.overrideMaterial = null;
1657
+ root.backgroundBlurriness = 0;
1658
+ root.backgroundIntensity = 1;
1659
+ root.environmentIntensity = 1;
1660
+ changed();
1661
+ return true;
1662
+ };
1663
+ const onFrame = (handler) => {
1664
+ assertActive();
1665
+ if (typeof handler !== "function") throw new TypeError("World authoring frame handler must be a function");
1666
+ frameHandlers.add(handler);
1667
+ return () => frameHandlers.delete(handler);
1668
+ };
1669
+ const update = (delta = 0, elapsed = 0) => {
1670
+ if (disposed) return false;
1671
+ restoreVisibility();
1672
+ for (const handler of [...frameHandlers]) try {
1673
+ handler(delta, elapsed);
1674
+ } catch (error) {
1675
+ frameHandlers.delete(handler);
1676
+ world.events?.emit?.("authoring.frame-error", { message: error?.message || String(error) });
1677
+ }
1678
+ suppressVisibility();
1679
+ return true;
1680
+ };
1681
+ const modelRef = (object, reference) => {
1682
+ assertActive();
1683
+ return markAuthoringModelRef(object, reference);
1684
+ };
1685
+ const capture = () => {
1686
+ assertActive();
1687
+ restoreVisibility();
1688
+ try {
1689
+ return captureAuthoringState(root);
1690
+ } finally {
1691
+ suppressVisibility();
1692
+ }
1693
+ };
1694
+ const exportDocument = () => exportAuthoringDocument(capture());
1695
+ const applyHydratedRoot = (hydratedRoot, state) => {
1696
+ clear();
1697
+ root.name = hydratedRoot.name || "$llm-world";
1698
+ root.position.copy(hydratedRoot.position);
1699
+ root.quaternion.copy(hydratedRoot.quaternion);
1700
+ root.scale.copy(hydratedRoot.scale);
1701
+ root.visible = hydratedRoot.visible;
1702
+ root.userData = { ...hydratedRoot.userData };
1703
+ setAuthoringObjectId(root, state.rootId);
1704
+ if (hydratedRoot.isScene) {
1705
+ root.background = hydratedRoot.background;
1706
+ root.environment = hydratedRoot.environment;
1707
+ root.fog = hydratedRoot.fog;
1708
+ root.overrideMaterial = hydratedRoot.overrideMaterial;
1709
+ root.backgroundBlurriness = hydratedRoot.backgroundBlurriness;
1710
+ root.backgroundIntensity = hydratedRoot.backgroundIntensity;
1711
+ root.environmentIntensity = hydratedRoot.environmentIntensity;
1712
+ }
1713
+ while (hydratedRoot.children.length > 0) root.add(hydratedRoot.children[0]);
1714
+ suppressVisibility();
1715
+ changed();
1716
+ return root;
1717
+ };
1718
+ const applyDocument = (document) => {
1719
+ const state = parseAuthoringDocument(document);
1720
+ const hydratedRoot = hydrateAuthoringState(state);
1721
+ return applyHydratedRoot(hydratedRoot, state);
1722
+ };
1723
+ const applyDocumentAsync = async (document, { resolveModel } = {}) => {
1724
+ const state = parseAuthoringDocument(document);
1725
+ const hydratedRoot = await hydrateAuthoringStateAsync(state, { resolveModel });
1726
+ return applyHydratedRoot(hydratedRoot, state);
1727
+ };
1728
+ const load = (document, { label = "Loaded world" } = {}) => {
1729
+ assertActive();
1730
+ const result = applyDocument(document);
1731
+ revisions.reset(document, {
1732
+ label,
1733
+ source: "load"
1734
+ });
1735
+ return result;
1736
+ };
1737
+ const loadAsync = async (document, { resolveModel, label = "Loaded world" } = {}) => {
1738
+ assertActive();
1739
+ const result = await applyDocumentAsync(document, { resolveModel });
1740
+ revisions.reset(document, {
1741
+ label,
1742
+ source: "load"
1743
+ });
1744
+ return result;
1745
+ };
1746
+ const restore = (document) => {
1747
+ assertActive();
1748
+ return applyDocument(document);
1749
+ };
1750
+ const normalizeCommitOptions = (options) => {
1751
+ if (typeof options === "string") return { label: options };
1752
+ return options || {};
1753
+ };
1754
+ const commit = (options = {}) => {
1755
+ assertActive();
1756
+ const normalized = normalizeCommitOptions(options);
1757
+ return revisions.commit(exportDocument(), {
1758
+ ...normalized,
1759
+ source: normalized.source || "manual"
1760
+ });
1761
+ };
1762
+ const patch = (changes, { label = "Patch" } = {}) => {
1763
+ assertActive();
1764
+ const document = patchAuthoringDocument(exportDocument(), changes);
1765
+ applyDocument(document);
1766
+ revisions.commit(document, {
1767
+ label,
1768
+ source: "patch"
1769
+ });
1770
+ return document;
1771
+ };
1772
+ const patchAsync = async (changes, { resolveModel, label = "Patch" } = {}) => {
1773
+ assertActive();
1774
+ const document = patchAuthoringDocument(exportDocument(), changes);
1775
+ await applyDocumentAsync(document, { resolveModel });
1776
+ revisions.commit(document, {
1777
+ label,
1778
+ source: "patch"
1779
+ });
1780
+ return document;
1781
+ };
1782
+ const history = () => {
1783
+ assertActive();
1784
+ return revisions.list();
1785
+ };
1786
+ const currentRevision = () => {
1787
+ assertActive();
1788
+ return revisions.current();
1789
+ };
1790
+ const diff = (fromRevisionId = null, toRevisionId = null) => {
1791
+ assertActive();
1792
+ if (fromRevisionId && toRevisionId) return revisions.diff(fromRevisionId, toRevisionId);
1793
+ const before = fromRevisionId ? revisions.getDocument(fromRevisionId) : revisions.currentDocument();
1794
+ if (!before) throw new Error("World Authoring has no committed revision");
1795
+ return diffAuthoringDocuments(before, toRevisionId ? revisions.getDocument(toRevisionId) : exportDocument());
1796
+ };
1797
+ const undo = () => {
1798
+ assertActive();
1799
+ const result = revisions.undo();
1800
+ if (!result) return null;
1801
+ try {
1802
+ applyDocument(result.document);
1803
+ return result.revision;
1804
+ } catch (error) {
1805
+ revisions.redo();
1806
+ throw error;
1807
+ }
1808
+ };
1809
+ const redo = () => {
1810
+ assertActive();
1811
+ const result = revisions.redo();
1812
+ if (!result) return null;
1813
+ try {
1814
+ applyDocument(result.document);
1815
+ return result.revision;
1816
+ } catch (error) {
1817
+ revisions.undo();
1818
+ throw error;
1819
+ }
1820
+ };
1821
+ const undoAsync = async ({ resolveModel } = {}) => {
1822
+ assertActive();
1823
+ const result = revisions.undo();
1824
+ if (!result) return null;
1825
+ try {
1826
+ await applyDocumentAsync(result.document, { resolveModel });
1827
+ return result.revision;
1828
+ } catch (error) {
1829
+ revisions.redo();
1830
+ throw error;
1831
+ }
1832
+ };
1833
+ const redoAsync = async ({ resolveModel } = {}) => {
1834
+ assertActive();
1835
+ const result = revisions.redo();
1836
+ if (!result) return null;
1837
+ try {
1838
+ await applyDocumentAsync(result.document, { resolveModel });
1839
+ return result.revision;
1840
+ } catch (error) {
1841
+ revisions.undo();
1842
+ throw error;
1843
+ }
1844
+ };
1845
+ const canUndo = () => revisions.canUndo();
1846
+ const canRedo = () => revisions.canRedo();
1847
+ const get = (id) => {
1848
+ assertActive();
1849
+ if (typeof id !== "string" || !id) return null;
1850
+ if (getAuthoringObjectId(root) === id) return root;
1851
+ let found = null;
1852
+ root.traverse((object) => {
1853
+ if (!found && getAuthoringObjectId(object) === id) found = object;
1854
+ });
1855
+ return found;
1856
+ };
1857
+ revisions.reset(exportDocument(), {
1858
+ label: "Initial world",
1859
+ source: "init"
1860
+ });
1861
+ return {
1862
+ codeIsolation: executeCode ? "external-executor" : "trusted-local",
1863
+ THREE: executionHost.THREE,
1864
+ scene: root,
1865
+ clear,
1866
+ onFrame,
1867
+ update,
1868
+ modelRef,
1869
+ capture,
1870
+ export: exportDocument,
1871
+ load,
1872
+ loadAsync,
1873
+ restore,
1874
+ commit,
1875
+ history,
1876
+ currentRevision,
1877
+ diff,
1878
+ patch,
1879
+ patchAsync,
1880
+ patchDocument: patchAuthoringDocument,
1881
+ undo,
1882
+ redo,
1883
+ undoAsync,
1884
+ redoAsync,
1885
+ canUndo,
1886
+ canRedo,
1887
+ get,
1888
+ setPromotedNodes,
1889
+ setPresentationMode(mode) {
1890
+ assertActive();
1891
+ return presentation?.setAuthoringSceneMode(root, mode) ?? false;
1892
+ },
1893
+ async run(source) {
1894
+ assertActive();
1895
+ if (typeof source !== "string" || !source.trim()) throw new TypeError("World authoring source is required");
1896
+ if (executeCode) {
1897
+ const document = await executeCode({
1898
+ code: source,
1899
+ document: exportDocument()
1900
+ });
1901
+ applyDocument(document);
1902
+ return;
1903
+ }
1904
+ if (!presentation) throw new Error("Headless authoring requires an isolated code executor");
1905
+ const execute = new AsyncFunction("THREE", "scene", "clear", "onFrame", "modelRef", "requestAnimationFrame", "cancelAnimationFrame", "setTimeout", "clearTimeout", "setInterval", "clearInterval", `'use strict';\n${source}`);
1906
+ restoreVisibility();
1907
+ try {
1908
+ return await execute(executionHost.THREE, root, clear, onFrame, modelRef, executionHost.requestAnimationFrame, executionHost.cancelAnimationFrame, executionHost.setTimeout, executionHost.clearTimeout, executionHost.setInterval, executionHost.clearInterval);
1909
+ } finally {
1910
+ restoreVisibility();
1911
+ suppressVisibility();
1912
+ changed();
1913
+ }
1914
+ },
1915
+ dispose() {
1916
+ if (disposed) return false;
1917
+ clear();
1918
+ disposed = true;
1919
+ return presentation?.removeAuthoringScene(root) ?? true;
1920
+ }
1921
+ };
1922
+ }
1923
+ // application/world-authoring/HeadlessImageExport.js
1924
+ var HeadlessImageData = class {
1925
+ constructor(dataOrWidth, widthOrHeight, height) {
1926
+ if (typeof dataOrWidth === "number") {
1927
+ this.width = dataOrWidth;
1928
+ this.height = widthOrHeight;
1929
+ this.data = new Uint8ClampedArray(this.width * this.height * 4);
1930
+ return;
1931
+ }
1932
+ this.data = dataOrWidth instanceof Uint8ClampedArray ? dataOrWidth : new Uint8ClampedArray(dataOrWidth);
1933
+ this.width = widthOrHeight;
1934
+ this.height = height;
1935
+ }
1936
+ };
1937
+ var HeadlessOffscreenCanvas = class {
1938
+ constructor(width = 1, height = 1) {
1939
+ this.width = width;
1940
+ this.height = height;
1941
+ this.pixels = null;
1942
+ }
1943
+ getContext(type) {
1944
+ if (type !== "2d") return null;
1945
+ const canvas = this;
1946
+ return {
1947
+ canvas,
1948
+ putImageData(image) {
1949
+ canvas.pixels = {
1950
+ data: new Uint8ClampedArray(image.data),
1951
+ width: image.width,
1952
+ height: image.height
1953
+ };
1954
+ },
1955
+ drawImage(source) {
1956
+ if (source?.pixels) canvas.pixels = {
1957
+ data: new Uint8ClampedArray(source.pixels.data),
1958
+ width: source.pixels.width,
1959
+ height: source.pixels.height
1960
+ };
1961
+ },
1962
+ scale() {},
1963
+ translate() {},
1964
+ clearRect() {},
1965
+ fillRect() {}
1966
+ };
1967
+ }
1968
+ convertToBlob({ type = "image/png" } = {}) {
1969
+ const image = this.pixels || {
1970
+ data: new Uint8ClampedArray(this.width * this.height * 4),
1971
+ width: this.width,
1972
+ height: this.height
1973
+ };
1974
+ return Promise.resolve(new Blob([encodePngRgba(image.data, image.width, image.height)], { type }));
1975
+ }
1976
+ };
1977
+ const installations = /* @__PURE__ */ new WeakMap();
1978
+ function installHeadlessImageSupport(scope = globalThis) {
1979
+ let installation = installations.get(scope);
1980
+ if (!installation) {
1981
+ if (typeof scope.OffscreenCanvas !== "undefined" && typeof scope.ImageData !== "undefined") return null;
1982
+ const previous = {
1983
+ OffscreenCanvas: scope.OffscreenCanvas,
1984
+ ImageData: scope.ImageData
1985
+ };
1986
+ if (typeof scope.OffscreenCanvas === "undefined") scope.OffscreenCanvas = HeadlessOffscreenCanvas;
1987
+ if (typeof scope.ImageData === "undefined") scope.ImageData = HeadlessImageData;
1988
+ installation = {
1989
+ previous,
1990
+ count: 0
1991
+ };
1992
+ installations.set(scope, installation);
1993
+ }
1994
+ installation.count++;
1995
+ let released = false;
1996
+ return () => {
1997
+ if (released) return;
1998
+ released = true;
1999
+ if (--installation.count !== 0) return;
2000
+ const { previous } = installation;
2001
+ if (previous.OffscreenCanvas === void 0) delete scope.OffscreenCanvas;
2002
+ else scope.OffscreenCanvas = previous.OffscreenCanvas;
2003
+ if (previous.ImageData === void 0) delete scope.ImageData;
2004
+ else scope.ImageData = previous.ImageData;
2005
+ installations.delete(scope);
2006
+ };
2007
+ }
2008
+ // application/world-authoring/AuthoringPromotionSource.js
2009
+ const promotionError = (code, message) => Object.assign(new Error(message), { code });
2010
+ const promotionHash = (value) => sha256ArtifactHash([new TextEncoder().encode(JSON.stringify(value))]);
2011
+ function capturePromotionSource(authoring, nodeId) {
2012
+ const state = parseAuthoringDocument(authoring.export());
2013
+ if (!state.nodesById[nodeId] || nodeId === state.rootId) throw promotionError("AUTHORING_SELECTION_INVALID", "请选择一个创作对象或分组,不能晋升整个创作根节点");
2014
+ const ids = [];
2015
+ const visit = (id) => {
2016
+ ids.push(id);
2017
+ for (const child of state.childIdsById[id] || []) visit(child);
2018
+ };
2019
+ visit(nodeId);
2020
+ const geometries = {}, materials = {};
2021
+ for (const id of ids) {
2022
+ const components = state.nodesById[id].components;
2023
+ const geometryId = components.geometry?.properties?.geometryId;
2024
+ const materialId = components.material?.properties?.materialId;
2025
+ if (geometryId) geometries[geometryId] = state.geometries[geometryId];
2026
+ if (materialId) materials[materialId] = state.materials[materialId];
2027
+ }
2028
+ const textures = {};
2029
+ for (const material of Object.values(materials)) for (const value of Object.values(material)) if (typeof value === "string" && state.textures[value]) textures[value] = state.textures[value];
2030
+ const object = authoring.get(nodeId);
2031
+ object.updateWorldMatrix(true, true);
2032
+ const matrix = object.matrixWorld.clone();
2033
+ const position = new THREE.Vector3(), quaternion = new THREE.Quaternion(), scale = new THREE.Vector3();
2034
+ matrix.decompose(position, quaternion, scale);
2035
+ const uniform = uniformScaleValue(scale.toArray());
2036
+ const reconstructed = new THREE.Matrix4().compose(position, quaternion, scale);
2037
+ if (matrix.elements.some((v, i) => !Number.isFinite(v) || Math.abs(v - reconstructed.elements[i]) > 1e-6)) throw promotionError("AUTHORING_TRANSFORM_UNSUPPORTED", "当前世界不支持带剪切的对象变换");
2038
+ let ancestor = nodeId;
2039
+ while (ancestor) {
2040
+ if (state.nodesById[ancestor].visible === false) throw promotionError("AUTHORING_NODE_HIDDEN", "请先显示创作对象及其父分组");
2041
+ ancestor = state.parentIdById[ancestor];
2042
+ }
2043
+ const content = {
2044
+ nodes: ids.map((id) => ({
2045
+ ...state.nodesById[id],
2046
+ childIds: state.childIdsById[id]
2047
+ })),
2048
+ geometries,
2049
+ materials,
2050
+ textures
2051
+ };
2052
+ const assetContent = structuredClone(content);
2053
+ delete assetContent.nodes[0].components.transform;
2054
+ const transform = {
2055
+ position: position.toArray(),
2056
+ quaternion: quaternion.toArray(),
2057
+ scale: uniform
2058
+ };
2059
+ return {
2060
+ nodeId,
2061
+ name: object.name || nodeId,
2062
+ ids,
2063
+ object,
2064
+ transform,
2065
+ reference: state.nodesById[nodeId].components.modelRef?.properties || null,
2066
+ contentHash: promotionHash(assetContent),
2067
+ sourceHash: promotionHash({
2068
+ content,
2069
+ transform
2070
+ }),
2071
+ revisionId: authoring.currentRevision()?.id || null
2072
+ };
2073
+ }
2074
+ async function exportPromotionGLB(source) {
2075
+ const { GLTFExporter } = await import("three/addons/exporters/GLTFExporter.js");
2076
+ const object = source.object.clone(true);
2077
+ object.position.set(0, 0, 0);
2078
+ object.quaternion.identity();
2079
+ object.scale.set(1, 1, 1);
2080
+ object.matrixAutoUpdate = true;
2081
+ object.updateMatrix();
2082
+ object.visible = true;
2083
+ const materials = [];
2084
+ const expand = (node) => {
2085
+ for (const child of [...node.children]) if (child.isInstancedMesh) {
2086
+ const group = new THREE.Group();
2087
+ group.name = child.name;
2088
+ group.position.copy(child.position);
2089
+ group.quaternion.copy(child.quaternion);
2090
+ group.scale.copy(child.scale);
2091
+ group.visible = child.visible;
2092
+ for (let i = 0; i < child.count; i++) {
2093
+ let material = child.material;
2094
+ if (child.instanceColor) {
2095
+ material = material.clone();
2096
+ material.color.multiply(new THREE.Color().fromBufferAttribute(child.instanceColor, i));
2097
+ materials.push(material);
2098
+ }
2099
+ const mesh = new THREE.Mesh(child.geometry, material);
2100
+ child.getMatrixAt(i, mesh.matrix);
2101
+ mesh.matrixAutoUpdate = false;
2102
+ group.add(mesh);
2103
+ }
2104
+ while (child.children.length) group.add(child.children[0]);
2105
+ node.remove(child);
2106
+ node.add(group);
2107
+ expand(group);
2108
+ } else expand(child);
2109
+ };
2110
+ const wrapper = new THREE.Group();
2111
+ wrapper.add(object);
2112
+ let meshes = 0;
2113
+ const restoreImageSupport = installHeadlessImageSupport();
2114
+ try {
2115
+ expand(wrapper);
2116
+ wrapper.traverse((node) => {
2117
+ if (node.isLight || node.isCamera || node.isSkinnedMesh || node.animations?.length) throw promotionError("AUTHORING_EXPORT_UNSUPPORTED", "请将灯光、相机、蒙皮或动画与待晋升对象分开");
2118
+ if (node.isMesh) meshes++;
2119
+ node.userData = {};
2120
+ });
2121
+ if (!meshes) throw promotionError("AUTHORING_MODEL_UNRESOLVED", "对象没有可导出的网格,请先加载模型");
2122
+ const bytes = await new GLTFExporter().parseAsync(wrapper, {
2123
+ binary: true,
2124
+ onlyVisible: true
2125
+ });
2126
+ return new Uint8Array(bytes);
2127
+ } finally {
2128
+ restoreImageSupport?.();
2129
+ for (const material of materials) material.dispose();
2130
+ }
2131
+ }
2132
+ // application/world-authoring/AuthoringAssetProducer.js
2133
+ function createAuthoringAssetProducer({ assets, artifacts, exportGLB = exportPromotionGLB }) {
2134
+ return async (source, { usage, definition = null, assetId: requestedAssetId = null }) => {
2135
+ const data = await exportGLB(source);
2136
+ const hash = sha256ArtifactHash([data]);
2137
+ const suffix = hash.slice(7);
2138
+ const artifactId = `authored_${suffix}`;
2139
+ const assetId = requestedAssetId || `authored_${suffix}_${usage}`;
2140
+ const cacheKey = `cache_${artifactId}`;
2141
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2142
+ if (!artifacts.registry.get(artifactId)) artifacts.registry.register({
2143
+ id: artifactId,
2144
+ role: "primary-glb",
2145
+ type: "asset-bundle",
2146
+ schema: {
2147
+ id: "agentscape.artifact",
2148
+ version: "1"
2149
+ },
2150
+ displayName: "Authored object",
2151
+ mime: "model/gltf-binary",
2152
+ format: "glb",
2153
+ bytes: data.byteLength,
2154
+ hash,
2155
+ producer: {
2156
+ provider: "authoring",
2157
+ jobId: `export_${suffix}`,
2158
+ operation: "authoring.export.glb.v1",
2159
+ stage: "authoring"
2160
+ },
2161
+ lineage: { parents: [] },
2162
+ createdAt: now,
2163
+ retention: { class: "project" },
2164
+ locations: []
2165
+ });
2166
+ if (!artifacts.byteStore.get(cacheKey)) {
2167
+ const writer = artifacts.byteStore.begin({
2168
+ artifactId,
2169
+ maxBytes: data.byteLength
2170
+ });
2171
+ try {
2172
+ await writer.write(data);
2173
+ await writer.commit({
2174
+ key: cacheKey,
2175
+ hash,
2176
+ mime: "model/gltf-binary",
2177
+ bytes: data.byteLength
2178
+ });
2179
+ } catch (error) {
2180
+ if (writer.state === "open") await writer.abort();
2181
+ throw error;
2182
+ }
2183
+ }
2184
+ artifacts.registry.updateLocation(artifactId, {
2185
+ id: `local_${artifactId}`,
2186
+ kind: "local-cache",
2187
+ scope: "application",
2188
+ state: "available",
2189
+ verifiedAt: now,
2190
+ access: {
2191
+ kind: "cache-key",
2192
+ key: cacheKey
2193
+ }
2194
+ });
2195
+ artifacts.registry.verifyIntegrity(artifactId, {
2196
+ hash,
2197
+ bytes: data.byteLength,
2198
+ mime: "model/gltf-binary",
2199
+ verifiedAt: now,
2200
+ method: "authoring-sha256-v1"
2201
+ });
2202
+ await artifacts.persistArtifact(artifactId, cacheKey);
2203
+ return assets.produceAsset({
2204
+ artifactId,
2205
+ assetId,
2206
+ label: definition?.label || "Authored object",
2207
+ authoringIntent: { usage },
2208
+ ...definition ? { definition } : {}
2209
+ });
2210
+ };
2211
+ }
2212
+ // application/programmatic-assets/ProgrammaticAssetContract.js
2213
+ const id = z.string().regex(/^[a-zA-Z0-9_-]{1,80}$/).refine((v) => ![
2214
+ "__proto__",
2215
+ "constructor",
2216
+ "prototype"
2217
+ ].includes(v));
2218
+ const finite = z.number().finite().min(-100).max(100);
2219
+ const vec = z.tuple([
2220
+ finite,
2221
+ finite,
2222
+ finite
2223
+ ]);
2224
+ const positive = z.number().min(1e-4).max(50);
2225
+ const actions = z.array(z.enum([
2226
+ "move",
2227
+ "pickup",
2228
+ "drop",
2229
+ "place",
2230
+ "open",
2231
+ "close"
2232
+ ])).max(8);
2233
+ const collider = z.object({
2234
+ shape: z.enum([
2235
+ "box",
2236
+ "cylinder",
2237
+ "capsule",
2238
+ "convexHull"
2239
+ ]),
2240
+ halfExtents: z.tuple([
2241
+ positive,
2242
+ positive,
2243
+ positive
2244
+ ]).optional(),
2245
+ halfHeight: positive.optional(),
2246
+ radius: positive.optional(),
2247
+ translation: vec.optional(),
2248
+ rotation: z.tuple([
2249
+ finite,
2250
+ finite,
2251
+ finite,
2252
+ finite
2253
+ ]).refine((q) => Math.abs(Math.hypot(...q) - 1) < 1e-4).optional(),
2254
+ vertices: z.array(finite).max(768).optional()
2255
+ }).strict();
2256
+ const physics = z.object({
2257
+ body: z.enum([
2258
+ "fixed",
2259
+ "dynamic",
2260
+ "kinematic"
2261
+ ]),
2262
+ mass: z.number().min(1e-4).max(1e4).optional(),
2263
+ friction: z.number().min(0).max(10).optional(),
2264
+ restitution: z.number().min(0).max(1).optional(),
2265
+ linearDamping: z.number().min(0).max(100).optional(),
2266
+ angularDamping: z.number().min(0).max(100).optional(),
2267
+ navigationObstacle: z.boolean().optional(),
2268
+ colliders: z.array(collider).min(1).max(32)
2269
+ }).strict();
2270
+ const part = z.object({
2271
+ node: id,
2272
+ semantic: z.string().max(100).optional(),
2273
+ parent: id.optional(),
2274
+ actions,
2275
+ targets: z.record(z.enum(["open", "close"]), finite).optional(),
2276
+ physics,
2277
+ joint: z.object({
2278
+ type: z.enum([
2279
+ "revolute",
2280
+ "prismatic",
2281
+ "fixed"
2282
+ ]),
2283
+ axis: vec.optional(),
2284
+ limits: z.tuple([finite, finite]).optional(),
2285
+ parentAnchor: vec,
2286
+ childAnchor: vec,
2287
+ motor: z.object({
2288
+ stiffness: z.number().min(0).max(1e4),
2289
+ damping: z.number().min(0).max(1e3)
2290
+ }).strict().optional()
2291
+ }).strict().optional()
2292
+ }).strict();
2293
+ const definitionSchema = z.object({
2294
+ id,
2295
+ type: id,
2296
+ label: z.string().min(1).max(100),
2297
+ description: z.string().max(500).optional(),
2298
+ tags: z.array(z.string().max(50)).max(20).optional(),
2299
+ aliases: z.array(z.string().max(50)).max(20).optional(),
2300
+ requiredNodes: z.array(id).max(64).optional(),
2301
+ actions,
2302
+ physics,
2303
+ parts: z.record(id, part).refine((v) => Object.keys(v).length <= 16).optional(),
2304
+ surfaces: z.array(z.object({
2305
+ id,
2306
+ localPosition: vec,
2307
+ size: z.tuple([positive, positive])
2308
+ }).strict()).max(16).optional(),
2309
+ receptacles: z.array(z.object({
2310
+ id,
2311
+ localPosition: vec,
2312
+ size: z.tuple([
2313
+ positive,
2314
+ positive,
2315
+ positive
2316
+ ])
2317
+ }).strict()).max(16).optional(),
2318
+ interactionContract: z.record(z.string(), z.unknown()).optional()
2319
+ }).strict();
2320
+ function parseDefinition(input) {
2321
+ let value;
2322
+ try {
2323
+ value = definitionSchema.parse(input);
2324
+ } catch {
2325
+ throw new Error("PROCEDURAL_MANIFEST_INVALID");
2326
+ }
2327
+ if (JSON.stringify(value).length > 24576) throw new Error("PROCEDURAL_MANIFEST_LIMIT");
2328
+ if (new Set((value.surfaces || []).map((s) => s.id)).size !== (value.surfaces || []).length) throw new Error("PROCEDURAL_MANIFEST_INVALID");
2329
+ const safe = (v, depth = 0) => {
2330
+ if (depth > 16) throw new Error("PROCEDURAL_MANIFEST_INVALID");
2331
+ if (!v || typeof v !== "object") return;
2332
+ for (const [k, item] of Object.entries(v)) {
2333
+ if ([
2334
+ "__proto__",
2335
+ "constructor",
2336
+ "prototype"
2337
+ ].includes(k)) throw new Error("PROCEDURAL_MANIFEST_INVALID");
2338
+ safe(item, depth + 1);
2339
+ }
2340
+ };
2341
+ safe(value);
2342
+ try {
2343
+ validateAssetManifest({
2344
+ ...value,
2345
+ source: {
2346
+ kind: "compiled",
2347
+ key: "pending"
2348
+ }
2349
+ });
2350
+ } catch {
2351
+ throw new Error("PROCEDURAL_MANIFEST_INVALID");
2352
+ }
2353
+ return value;
2354
+ }
2355
+ // application/programmatic-assets/ProgrammaticAssetBuilder.js
2356
+ var ProgrammaticAssetBuilder = class {
2357
+ constructor({ runner, gltfLoader }) {
2358
+ Object.assign(this, {
2359
+ runner,
2360
+ gltfLoader
2361
+ });
2362
+ }
2363
+ async build({ source, definition, assetId }, { signal } = {}) {
2364
+ const draft = definition == null ? null : parseDefinition(definition);
2365
+ let result;
2366
+ try {
2367
+ result = await this.runner.run({
2368
+ mode: "procedural",
2369
+ source
2370
+ }, { signal });
2371
+ } catch (error) {
2372
+ error.details = {
2373
+ ...error.details,
2374
+ stage: "source-execution"
2375
+ };
2376
+ throw error;
2377
+ }
2378
+ if (signal?.aborted) throw new Error("BUILD_CANCELLED");
2379
+ const authoring = createWorldAuthoringContext({ events: { emit() {} } }, { executeCode: () => {
2380
+ throw Error("SOURCE_EXECUTION_FORBIDDEN");
2381
+ } });
2382
+ const assets = createAssetModule({
2383
+ manifests: {},
2384
+ manifestStore: null,
2385
+ libraryStore: null,
2386
+ gltfLoader: this.gltfLoader
2387
+ });
2388
+ const artifacts = createArtifactModule({ persistentStore: null });
2389
+ assets.configureProduction({ artifacts });
2390
+ assets.configureVerification({ articulationVerifier: new ArticulationVerifier({
2391
+ assetRegistry: assets.registry,
2392
+ assetLoader: assets.loader
2393
+ }) });
2394
+ try {
2395
+ authoring.load(result.document);
2396
+ const object = authoring.get("asset-root");
2397
+ const names = /* @__PURE__ */ new Map();
2398
+ object.traverse((n) => {
2399
+ if (n.name) names.set(n.name, (names.get(n.name) || 0) + 1);
2400
+ });
2401
+ const required = [...draft?.requiredNodes || [], ...Object.values(draft?.parts || {}).map((p) => p.node)];
2402
+ if (required.some((name) => names.get(name) !== 1)) throw Object.assign(/* @__PURE__ */ new Error("PROCEDURAL_REQUIRED_NODE_INVALID"), { details: {
2403
+ invalidNodes: required.filter((name) => names.get(name) !== 1),
2404
+ nodeCounts: Object.fromEntries(required.map((name) => [name, names.get(name) || 0]))
2405
+ } });
2406
+ const box = new THREE.Box3().setFromObject(object), size = box.getSize(new THREE.Vector3());
2407
+ if (![
2408
+ size.x,
2409
+ size.y,
2410
+ size.z
2411
+ ].every((v) => Number.isFinite(v) && v > 0 && v <= 100)) throw new Error("PROCEDURAL_DIMENSIONS_INVALID");
2412
+ const captured = capturePromotionSource(authoring, "asset-root");
2413
+ if (!draft) {
2414
+ const bytes = await exportPromotionGLB(captured);
2415
+ const output = await assets.importPackageAsset({
2416
+ bytes,
2417
+ id: assetId,
2418
+ definition: {
2419
+ capabilityLevel: "visual",
2420
+ label: "Code asset"
2421
+ }
2422
+ });
2423
+ if (signal?.aborted) throw new Error("BUILD_CANCELLED");
2424
+ return {
2425
+ bytes: (await assets.compiledStore.get(assetId)).bytes,
2426
+ manifest: output.manifest,
2427
+ environment: result.environment,
2428
+ security: result.security,
2429
+ validation: {
2430
+ execution: "succeeded",
2431
+ runtime: { status: "not-requested" }
2432
+ },
2433
+ admission: assetAdmission(output.manifest)
2434
+ };
2435
+ }
2436
+ const resolved = {
2437
+ ...draft,
2438
+ id: assetId
2439
+ };
2440
+ if (resolved.interactionContract) resolved.interactionContract = {
2441
+ ...resolved.interactionContract,
2442
+ entityId: assetId
2443
+ };
2444
+ if ((await createAuthoringAssetProducer({
2445
+ assets,
2446
+ artifacts
2447
+ })(captured, {
2448
+ usage: "interactive",
2449
+ definition: resolved,
2450
+ assetId
2451
+ })).status === "asset-rejected") throw new Error("PROCEDURAL_ASSET_REJECTED");
2452
+ const runtime = await assets.verifyAndUpdateArticulation(assetId, { requireRegistration: true });
2453
+ if (!runtime.ok || !runtime.physicsRegistered) throw Object.assign(/* @__PURE__ */ new Error("PROCEDURAL_RUNTIME_VERIFICATION_FAILED"), { details: runtime });
2454
+ const manifest = assets.getManifest(assetId);
2455
+ const loaded = await assets.instantiate(assetId);
2456
+ disposeObject3D(loaded.object);
2457
+ const compiled = await assets.compiledStore.get(manifest.source.key);
2458
+ if (!compiled?.bytes || compiled.bytes.byteLength > 4194304) throw new Error("BUILD_OUTPUT_LIMIT");
2459
+ if (signal?.aborted) throw new Error("BUILD_CANCELLED");
2460
+ manifest.capabilityLevel = Object.keys(draft.parts || {}).length ? "interactive" : "physical";
2461
+ return {
2462
+ bytes: compiled.bytes,
2463
+ manifest,
2464
+ environment: result.environment,
2465
+ security: result.security,
2466
+ validation: {
2467
+ execution: "succeeded",
2468
+ nodes: [...names.keys()],
2469
+ bounds: {
2470
+ min: box.min.toArray(),
2471
+ max: box.max.toArray()
2472
+ },
2473
+ runtime
2474
+ },
2475
+ admission: assetAdmission(manifest)
2476
+ };
2477
+ } catch (error) {
2478
+ error.execution = { status: "succeeded" };
2479
+ error.details = {
2480
+ ...error.details,
2481
+ stage: "asset-admission"
2482
+ };
2483
+ throw error;
2484
+ } finally {
2485
+ authoring.dispose();
2486
+ }
2487
+ }
2488
+ };
2489
+ // application/programmatic-assets/ThreeCodeAsset.js
2490
+ async function prepareEmbeddedCodeAsset(assets, input, { gltfLoader } = {}) {
2491
+ const asset = `asset://sha256/${input.id.replace(/^(pa_|asset_)/, "")}`;
2492
+ const sourceHash = await assetDigest(input.bytes);
2493
+ const definitionHash = await assetDigest(new TextEncoder().encode(canonicalAssetJson(input.definition)));
2494
+ if (assets.hasAsset(input.id)) {
2495
+ const existing = assets.getManifest(input.id);
2496
+ if (existing.provenance?.codeTransport?.sourceHash !== sourceHash || existing.provenance?.codeTransport?.definitionHash !== definitionHash) throw new Error("ASSET_ID_CONFLICT");
2497
+ return {
2498
+ asset,
2499
+ install: (operation) => operation()
2500
+ };
2501
+ }
2502
+ const scratch = createAssetModule({
2503
+ volatile: true,
2504
+ manifests: {},
2505
+ manifestStore: null,
2506
+ libraryStore: null,
2507
+ gltfLoader
2508
+ });
2509
+ scratch.configureVerification({ articulationVerifier: new ArticulationVerifier({
2510
+ assetRegistry: scratch.registry,
2511
+ assetLoader: scratch.loader
2512
+ }) });
2513
+ const { manifest } = await scratch.importPackageAsset({
2514
+ id: input.id,
2515
+ bytes: input.bytes,
2516
+ definition: input.definition
2517
+ });
2518
+ manifest.provenance = {
2519
+ ...manifest.provenance,
2520
+ codeTransport: {
2521
+ sourceHash,
2522
+ definitionHash
2523
+ }
2524
+ };
2525
+ const bytes = (await scratch.compiledStore.get(manifest.source.key)).bytes;
2526
+ const expectedSourceHash = await assetDigest(bytes);
2527
+ return {
2528
+ asset,
2529
+ install: (operation) => assets.installPreparedAssets([{
2530
+ manifest,
2531
+ bytes,
2532
+ expectedDefinition: manifest,
2533
+ expectedSourceHash
2534
+ }], operation)
2535
+ };
2536
+ }
2537
+ async function prepareThreeCodeAsset(assets, executor, input, { signal, gltfLoader } = {}) {
2538
+ if (!executor) throw new Error("CODE_EXECUTION_DISABLED");
2539
+ const environment = await executor.environment();
2540
+ const version = await assetDigest(new TextEncoder().encode(canonicalAssetJson({
2541
+ source: input.source,
2542
+ definition: input.definition || null,
2543
+ environment,
2544
+ contract: "three-code-v1"
2545
+ })));
2546
+ const id = `asset_${version}`, asset = `asset://sha256/${version}`;
2547
+ if (signal?.aborted) throw new Error("BUILD_CANCELLED");
2548
+ if (assets.hasAsset(id)) return {
2549
+ asset,
2550
+ manifest: assets.getManifest(id),
2551
+ install: (operation) => operation()
2552
+ };
2553
+ const built = await new ProgrammaticAssetBuilder({
2554
+ runner: executor,
2555
+ gltfLoader
2556
+ }).build({
2557
+ ...input,
2558
+ assetId: id
2559
+ }, { signal });
2560
+ if (signal?.aborted) throw new Error("BUILD_CANCELLED");
2561
+ built.manifest.contentHash = version;
2562
+ const bytesHash = await assetDigest(built.bytes);
2563
+ return {
2564
+ asset,
2565
+ manifest: built.manifest,
2566
+ validation: built.validation,
2567
+ install: (operation) => assets.installPreparedAssets([{
2568
+ manifest: built.manifest,
2569
+ bytes: built.bytes,
2570
+ expectedDefinition: built.manifest,
2571
+ expectedSourceHash: bytesHash
2572
+ }], operation)
2573
+ };
2574
+ }
2575
+ // application/scene/SceneProject.js
2576
+ const sceneObjectIdSchema = z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/);
2577
+ const sceneVector3Schema = z.tuple([
2578
+ z.number().finite().min(-1e4).max(1e4),
2579
+ z.number().finite().min(-1e4).max(1e4),
2580
+ z.number().finite().min(-1e4).max(1e4)
2581
+ ]);
2582
+ const quaternionSchema = z.tuple([
2583
+ z.number().finite(),
2584
+ z.number().finite(),
2585
+ z.number().finite(),
2586
+ z.number().finite()
2587
+ ]).refine((value) => Math.abs(Math.hypot(...value) - 1) < 1e-4, "Quaternion must be normalized");
2588
+ const scaleSchema = z.number().finite().min(.05).max(20);
2589
+ const sceneTransformSchema = z.object({
2590
+ position: sceneVector3Schema.default(() => [
2591
+ 0,
2592
+ 0,
2593
+ 0
2594
+ ]),
2595
+ quaternion: quaternionSchema.default(() => [
2596
+ 0,
2597
+ 0,
2598
+ 0,
2599
+ 1
2600
+ ]),
2601
+ scale: scaleSchema.default(1)
2602
+ }).strict();
2603
+ const builtinAssetSchema = z.string().regex(/^builtin:\/\/[a-zA-Z][a-zA-Z0-9_-]{0,63}$/);
2604
+ const sceneResourcePathSchema = z.string().max(240).refine((value) => {
2605
+ if (!value.startsWith("./")) return false;
2606
+ return value.slice(2).split("/").every((part) => /^[a-zA-Z0-9_-][a-zA-Z0-9_.-]*$/.test(part) && !part.endsWith(".") && !/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part));
2607
+ }, "Expected a portable project-relative resource path");
2608
+ const sceneAssetRefSchema = z.union([
2609
+ builtinAssetSchema,
2610
+ z.string().regex(/^asset:\/\/sha256\/[a-f0-9]{64}$/),
2611
+ sceneResourcePathSchema
2612
+ ]);
2613
+ const sceneObjectSchema = z.object({
2614
+ id: sceneObjectIdSchema,
2615
+ asset: sceneAssetRefSchema,
2616
+ level: z.enum([
2617
+ "visual",
2618
+ "physical",
2619
+ "interactive"
2620
+ ]),
2621
+ transform: sceneTransformSchema.default(() => ({
2622
+ position: [
2623
+ 0,
2624
+ 0,
2625
+ 0
2626
+ ],
2627
+ quaternion: [
2628
+ 0,
2629
+ 0,
2630
+ 0,
2631
+ 1
2632
+ ],
2633
+ scale: 1
2634
+ }))
2635
+ }).strict();
2636
+ const sceneProjectSchema = z.object({
2637
+ schema: z.literal("agentscape.scene-project"),
2638
+ schemaVersion: z.literal(1),
2639
+ name: z.string().trim().min(1).max(100),
2640
+ environment: z.object({
2641
+ type: z.literal("builtin"),
2642
+ id: z.enum(BUILTIN_ENVIRONMENT_IDS)
2643
+ }).strict(),
2644
+ style: sceneAssetRefSchema.optional(),
2645
+ objects: z.array(sceneObjectSchema)
2646
+ }).strict().superRefine((project, ctx) => {
2647
+ const used = /* @__PURE__ */ new Set();
2648
+ for (let index = 0; index < project.objects.length; index++) {
2649
+ const id = project.objects[index].id;
2650
+ if (used.has(id)) ctx.addIssue({
2651
+ code: "custom",
2652
+ path: [
2653
+ "objects",
2654
+ index,
2655
+ "id"
2656
+ ],
2657
+ message: "Duplicate scene object ID"
2658
+ });
2659
+ used.add(id);
2660
+ }
2661
+ });
2662
+ function parseSceneProject(input) {
2663
+ if (typeof input === "string") {
2664
+ if (new TextEncoder().encode(input).byteLength > 262144) throw projectError("DOCUMENT_LIMIT");
2665
+ try {
2666
+ input = JSON.parse(input);
2667
+ } catch {
2668
+ throw projectError("INVALID_DOCUMENT");
2669
+ }
2670
+ }
2671
+ if (input?.schema === "agentscape.scene-project" && input.schemaVersion !== 1) throw projectError("UNSUPPORTED_VERSION");
2672
+ const result = sceneProjectSchema.safeParse(input);
2673
+ if (!result.success) throw projectError("INVALID_DOCUMENT", result.error.issues.map((issue) => ({
2674
+ path: issue.path,
2675
+ message: issue.message
2676
+ })));
2677
+ return result.data;
2678
+ }
2679
+ function projectError(code, diagnostics = []) {
2680
+ return Object.assign(new Error(code), {
2681
+ code,
2682
+ diagnostics
2683
+ });
2684
+ }
2685
+ export { prepareEmbeddedCodeAsset as a, sceneVector3Schema as i, sceneObjectIdSchema as n, prepareThreeCodeAsset as o, sceneTransformSchema as r, parseSceneProject as t };
2686
+
2687
+ //# sourceMappingURL=SceneProject-K7HH1s8o.js.map