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,2637 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D3KUYPsf.js";
2
+ import { n as compileRecipeGeometry } from "./AssetRecipe-g8dZBhgJ.js";
3
+ import { d as recipeSchema, l as interactionReviewSchema, n as assertEmbeddedGLB, o as canonicalAssetJson, r as assetDigest } from "./gltfIO-BzVKLyaL.js";
4
+ import { t as assetManifests } from "./manifests-D0LwbJ36.js";
5
+ import { r as Errors, t as validateAssetManifest } from "./schema-DT7K9NjP.js";
6
+ import { n as disposeObject3D, t as RELEASE_RESOURCE } from "./disposeObject3D-DIMzy0FA.js";
7
+ import { t as assetAdmission } from "./admission-CVEvsrdz.js";
8
+ import { r as thermalProperties, t as simulationProfileSchema } from "./SimulationProfile-DSYZbBLQ.js";
9
+ import * as z from "zod/v4";
10
+ import * as THREE from "three";
11
+ import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
12
+ import { KTX2Loader } from "three/examples/jsm/loaders/KTX2Loader.js";
13
+ import { MeshoptDecoder } from "three/examples/jsm/libs/meshopt_decoder.module.js";
14
+ import { clone as clone$5 } from "three/examples/jsm/utils/SkeletonUtils.js";
15
+ // modules/asset/model/MechanicalAssetDraft.js
16
+ const finite = z.number().finite().min(-100).max(100);
17
+ const positive = z.number().finite().positive().max(100);
18
+ const vec3 = z.tuple([
19
+ finite,
20
+ finite,
21
+ finite
22
+ ]);
23
+ const componentId = z.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/);
24
+ const component = z.object({
25
+ id: componentId,
26
+ parent: componentId.nullable().default(null),
27
+ shape: z.enum([
28
+ "group",
29
+ "box",
30
+ "sphere",
31
+ "cylinder"
32
+ ]),
33
+ position: vec3,
34
+ size: z.tuple([
35
+ positive,
36
+ positive,
37
+ positive
38
+ ]),
39
+ color: z.string().regex(/^#[a-fA-F0-9]{6}$/),
40
+ collision: z.boolean().default(true)
41
+ }).strict().superRefine((node, ctx) => {
42
+ if (node.shape === "sphere" && (node.size[0] !== node.size[1] || node.size[0] !== node.size[2])) ctx.addIssue({
43
+ code: "custom",
44
+ message: "Sphere dimensions must match on X, Y and Z"
45
+ });
46
+ if (node.shape === "cylinder" && node.size[0] !== node.size[2]) ctx.addIssue({
47
+ code: "custom",
48
+ message: "Cylinder diameter must match on X and Z"
49
+ });
50
+ });
51
+ const motion = z.object({
52
+ id: componentId,
53
+ node: componentId,
54
+ type: z.enum(["revolute", "prismatic"]),
55
+ axis: vec3.refine((v) => Math.hypot(...v) > 1e-6),
56
+ limits: z.tuple([finite, finite]).refine(([a, b]) => a < b && a <= 0 && b >= 0),
57
+ open: finite,
58
+ mass: positive,
59
+ friction: z.number().min(0).max(2).default(.6),
60
+ stiffness: z.number().positive().max(1e3).default(80),
61
+ damping: z.number().positive().max(100).default(12)
62
+ }).strict().refine((m) => m.open >= m.limits[0] && m.open <= m.limits[1] && m.open !== 0, "Open target must be inside limits and differ from zero");
63
+ const mechanicalDraftSchema = z.object({
64
+ schema: z.literal("agentscape.mechanical-draft"),
65
+ schemaVersion: z.literal(1),
66
+ name: z.string().trim().min(2).max(80),
67
+ type: componentId.default("mechanism"),
68
+ components: z.array(component).min(1).max(64),
69
+ motions: z.array(motion).max(12),
70
+ body: z.enum(["fixed", "dynamic"]).optional(),
71
+ simulation: simulationProfileSchema.optional()
72
+ }).strict().superRefine((draft, ctx) => {
73
+ const components = new Map(draft.components.map((node) => [node.id, node]));
74
+ if (components.size !== draft.components.length) ctx.addIssue({
75
+ code: "custom",
76
+ message: "Component names must be unique"
77
+ });
78
+ const ids = /* @__PURE__ */ new Set();
79
+ const nodes = /* @__PURE__ */ new Set();
80
+ if (draft.motions.length && draft.body === "dynamic") ctx.addIssue({
81
+ code: "custom",
82
+ message: "Articulated drafts require a fixed root body"
83
+ });
84
+ if (draft.simulation?.schemaVersion === 2) {
85
+ const allowed = new Set(draft.motions.map((m) => m.id));
86
+ for (const node of draft.simulation.nodes) if (node.partName !== "$root" && !allowed.has(node.partName)) ctx.addIssue({
87
+ code: "custom",
88
+ message: "Thermal node must reference a declared mechanical joint: " + node.partName
89
+ });
90
+ }
91
+ for (const entry of draft.motions) {
92
+ if (ids.has(entry.id) || nodes.has(entry.node)) ctx.addIssue({
93
+ code: "custom",
94
+ message: "Joint id and node must be unique"
95
+ });
96
+ ids.add(entry.id);
97
+ nodes.add(entry.node);
98
+ if (!components.has(entry.node) || components.get(entry.node).shape !== "group" || components.get(entry.node).parent) ctx.addIssue({
99
+ code: "custom",
100
+ message: "A joint must reference a root-level group pivot: " + entry.node
101
+ });
102
+ }
103
+ for (const entry of draft.components) {
104
+ if (entry.shape === "group" && !nodes.has(entry.id)) ctx.addIssue({
105
+ code: "custom",
106
+ message: "Group must be a named joint pivot: " + entry.id
107
+ });
108
+ if (entry.parent && (!nodes.has(entry.parent) || components.get(entry.parent)?.shape !== "group")) ctx.addIssue({
109
+ code: "custom",
110
+ message: "Parent must be a joint pivot: " + entry.id
111
+ });
112
+ if (entry.parent === entry.id) ctx.addIssue({
113
+ code: "custom",
114
+ message: "Component cannot parent itself"
115
+ });
116
+ }
117
+ if (!draft.components.some((part) => part.collision && !part.parent && part.shape !== "group")) ctx.addIssue({
118
+ code: "custom",
119
+ message: "At least one fixed-body collision component is required"
120
+ });
121
+ for (const joint of draft.motions) if (!draft.components.some((part) => part.parent === joint.node && part.collision && part.shape !== "group")) ctx.addIssue({
122
+ code: "custom",
123
+ message: "Joint requires a collision component: " + joint.id
124
+ });
125
+ });
126
+ const collider = (node) => ({
127
+ shape: "box",
128
+ halfExtents: node.shape === "sphere" ? [
129
+ node.size[0] / 2,
130
+ node.size[0] / 2,
131
+ node.size[0] / 2
132
+ ] : node.shape === "cylinder" ? [
133
+ node.size[0] / 2,
134
+ node.size[1] / 2,
135
+ node.size[0] / 2
136
+ ] : node.size.map((size) => size / 2),
137
+ translation: [...node.position]
138
+ });
139
+ function mechanicalDraftToAssetRecipe(input) {
140
+ const draft = mechanicalDraftSchema.parse(input);
141
+ return recipeSchema.parse({
142
+ schema: "agentscape.asset-recipe",
143
+ schemaVersion: 1,
144
+ id: "mechanical/" + draft.type,
145
+ parts: draft.components.map((node) => ({
146
+ id: node.id,
147
+ ...node.parent ? { parent: node.parent } : {},
148
+ ...node.shape === "group" ? {} : { geometry: node.shape === "box" ? {
149
+ type: "box",
150
+ size: [...node.size]
151
+ } : node.shape === "sphere" ? {
152
+ type: "sphere",
153
+ radius: node.size[0] / 2
154
+ } : {
155
+ type: "cylinder",
156
+ radius: node.size[0] / 2,
157
+ height: node.size[1]
158
+ } },
159
+ position: [...node.position],
160
+ material: {
161
+ color: node.color,
162
+ roughness: .48,
163
+ metalness: .6
164
+ }
165
+ }))
166
+ });
167
+ }
168
+ function mechanicalDraftToManifest(input) {
169
+ const draft = mechanicalDraftSchema.parse(input);
170
+ const rootColliders = draft.components.filter((node) => node.collision && !node.parent && node.shape !== "group").map(collider);
171
+ const parts = {};
172
+ for (const motion of draft.motions) {
173
+ const pivot = draft.components.find((node) => node.id === motion.node);
174
+ parts[motion.id] = {
175
+ node: motion.node,
176
+ actions: ["open", "close"],
177
+ targets: {
178
+ open: motion.open,
179
+ close: 0
180
+ },
181
+ physics: {
182
+ body: "dynamic",
183
+ mass: motion.mass,
184
+ friction: motion.friction,
185
+ colliders: draft.components.filter((node) => node.parent === motion.node && node.collision && node.shape !== "group").map(collider)
186
+ },
187
+ joint: {
188
+ type: motion.type,
189
+ axis: [...motion.axis],
190
+ limits: [...motion.limits],
191
+ parentAnchor: [...pivot.position],
192
+ childAnchor: [
193
+ 0,
194
+ 0,
195
+ 0
196
+ ],
197
+ motor: {
198
+ stiffness: motion.stiffness,
199
+ damping: motion.damping
200
+ }
201
+ }
202
+ };
203
+ }
204
+ return {
205
+ type: draft.type,
206
+ label: draft.name,
207
+ capabilityLevel: draft.motions.length ? "interactive" : "physical",
208
+ actions: draft.motions.length ? ["open", "close"] : ["move"],
209
+ requiredNodes: draft.motions.map((m) => m.node),
210
+ physics: {
211
+ body: draft.body || "fixed",
212
+ mass: draft.motions.length ? 1 : draft.simulation ? thermalProperties(draft.simulation).massKg : 1,
213
+ friction: .6,
214
+ colliders: rootColliders
215
+ },
216
+ ...draft.simulation ? { simulation: structuredClone(draft.simulation) } : {},
217
+ ...draft.motions.length ? { parts } : {}
218
+ };
219
+ }
220
+ // modules/asset/loading/GltfAssetLoader.js
221
+ var GltfAssetLoader = class {
222
+ constructor({ loader = new GLTFLoader(), meshoptDecoder = MeshoptDecoder, ktx2TranscoderPath = "/basis/", ktx2LoaderFactory = () => new KTX2Loader() } = {}) {
223
+ if (!loader || typeof loader.loadAsync !== "function") throw new TypeError("GltfAssetLoader requires a GLTF-compatible loader");
224
+ if (typeof ktx2LoaderFactory !== "function") throw new TypeError("GltfAssetLoader ktx2LoaderFactory must be a function");
225
+ this.loader = loader;
226
+ this.ktx2TranscoderPath = ktx2TranscoderPath;
227
+ this.ktx2LoaderFactory = ktx2LoaderFactory;
228
+ this.ktx2Loader = null;
229
+ this.loader.setMeshoptDecoder?.(meshoptDecoder);
230
+ }
231
+ configureRenderer(renderer) {
232
+ if (!renderer) throw new TypeError("GltfAssetLoader.configureRenderer requires a renderer");
233
+ if (typeof this.loader.setKTX2Loader !== "function" || !this.ktx2TranscoderPath) return false;
234
+ this.ktx2Loader?.dispose?.();
235
+ this.ktx2Loader = this.ktx2LoaderFactory().setTranscoderPath(this.ktx2TranscoderPath).detectSupport(renderer);
236
+ this.loader.setKTX2Loader(this.ktx2Loader);
237
+ return true;
238
+ }
239
+ async load(url) {
240
+ const gltf = await this.loader.loadAsync(url);
241
+ if (!gltf?.scene) throw new Error(`GLTF has no default scene: ${url}`);
242
+ return gltf;
243
+ }
244
+ async loadScene(url) {
245
+ const gltf = await this.load(url);
246
+ gltf.scene.animations = [...gltf.animations || []];
247
+ return gltf.scene;
248
+ }
249
+ async loadBytes(bytes) {
250
+ if (!globalThis.document && !globalThis.createImageBitmap && assertEmbeddedGLB(bytes).images?.length) throw Object.assign(/* @__PURE__ */ new Error("Headless texture decoder unavailable"), { code: "HEADLESS_TEXTURE_DECODER_UNAVAILABLE" });
251
+ const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
252
+ const gltf = await this.loader.parseAsync(buffer, "");
253
+ if (!gltf?.scene) throw new Error("GLTF has no default scene");
254
+ gltf.scene.animations = [...gltf.animations || []];
255
+ return gltf.scene;
256
+ }
257
+ dispose() {
258
+ this.ktx2Loader?.dispose?.();
259
+ this.ktx2Loader = null;
260
+ }
261
+ };
262
+ // modules/asset/registry/AssetCatalog.js
263
+ const normalize = (value = "") => String(value).trim().toLowerCase();
264
+ const SEARCH_STOPWORDS = /* @__PURE__ */ new Set([
265
+ "a",
266
+ "an",
267
+ "the",
268
+ "of",
269
+ "to",
270
+ "for",
271
+ "in",
272
+ "on",
273
+ "with",
274
+ "and",
275
+ "or"
276
+ ]);
277
+ const tokens = (value = "") => normalize(value).split(/[^a-z0-9\u4e00-\u9fff]+/).filter((token) => token && !SEARCH_STOPWORDS.has(token) && (/[^a-z0-9]/.test(token) || token.length >= 2));
278
+ function summarizeAsset(manifest) {
279
+ return {
280
+ id: manifest.id,
281
+ type: manifest.type,
282
+ label: manifest.label || manifest.id,
283
+ description: manifest.description || "",
284
+ tags: [...manifest.tags || []],
285
+ actions: [...manifest.actions],
286
+ source: manifest.source.kind
287
+ };
288
+ }
289
+ function searchAssetManifests(manifests, query, { limit = 8 } = {}) {
290
+ const all = [...manifests];
291
+ const q = normalize(query);
292
+ if (!q) return all.slice(0, limit).map(summarizeAsset);
293
+ const qTokens = tokens(q);
294
+ const scored = [];
295
+ for (const manifest of all) {
296
+ const fields = [
297
+ manifest.id,
298
+ manifest.type,
299
+ manifest.label,
300
+ manifest.description,
301
+ ...manifest.tags || [],
302
+ ...manifest.aliases || []
303
+ ].filter(Boolean).map(normalize);
304
+ let score = 0;
305
+ for (const field of fields) {
306
+ if (field === q) score += 12;
307
+ else if (field.includes(q)) score += 6;
308
+ for (const token of qTokens) if (field.includes(token)) score += 2;
309
+ }
310
+ if (score > 0) scored.push({
311
+ score,
312
+ asset: summarizeAsset(manifest)
313
+ });
314
+ }
315
+ return scored.sort((a, b) => b.score - a.score || a.asset.id.localeCompare(b.asset.id)).slice(0, limit).map(({ asset }) => asset);
316
+ }
317
+ var AssetCatalog = class {
318
+ constructor({ registry } = {}) {
319
+ this.registry = registry;
320
+ if (!this.registry?.listManifests || typeof this.registry.getManifest !== "function") throw new TypeError("AssetCatalog requires an AssetRegistry");
321
+ }
322
+ has(assetId) {
323
+ return this.registry.has(assetId);
324
+ }
325
+ get(assetId) {
326
+ return this.registry.getManifest(assetId);
327
+ }
328
+ list() {
329
+ return this.registry.listManifests().map(summarizeAsset);
330
+ }
331
+ search(query, options) {
332
+ return searchAssetManifests(this.registry.listManifests(), query, options);
333
+ }
334
+ summary(manifest) {
335
+ return summarizeAsset(manifest);
336
+ }
337
+ resolveExisting(query, { limit = 5, assetId = null } = {}) {
338
+ if (assetId && this.has(assetId)) return {
339
+ status: "found",
340
+ query,
341
+ assets: [this.summary(this.get(assetId))]
342
+ };
343
+ const assets = this.search(query, { limit });
344
+ if (!assets.length) return {
345
+ status: "missing",
346
+ query,
347
+ assets: []
348
+ };
349
+ if (assets.length > 1) return {
350
+ status: "ambiguous",
351
+ query,
352
+ assets
353
+ };
354
+ return {
355
+ status: "found",
356
+ query,
357
+ assets
358
+ };
359
+ }
360
+ };
361
+ // modules/asset/registry/AssetRegistry.js
362
+ const canonical = (value) => {
363
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
364
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
365
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;
366
+ };
367
+ var AssetRegistry = class {
368
+ constructor({ manifests = assetManifests } = {}) {
369
+ this.manifests = /* @__PURE__ */ new Map();
370
+ for (const manifest of Object.values(manifests || {})) this.registerManifest(manifest);
371
+ }
372
+ registerManifest(manifest, { replace = false } = {}) {
373
+ validateAssetManifest(manifest);
374
+ const existing = this.manifests.get(manifest.id);
375
+ if (existing && !replace) {
376
+ if (canonical(existing) === canonical(manifest)) return false;
377
+ throw Errors.invalidManifest(`Asset id conflict: ${manifest.id}`, { id: manifest.id });
378
+ }
379
+ this.manifests.set(manifest.id, structuredClone(manifest));
380
+ return true;
381
+ }
382
+ assertCompatibleManifest(manifest) {
383
+ const existing = this.manifests.get(manifest.id);
384
+ if (!existing) {
385
+ validateAssetManifest(manifest);
386
+ return true;
387
+ }
388
+ if (canonical(existing) !== canonical(manifest)) throw Errors.invalidManifest(`Asset id conflict: ${manifest.id}`, { id: manifest.id });
389
+ return false;
390
+ }
391
+ has(assetId) {
392
+ return this.manifests.has(assetId);
393
+ }
394
+ removeManifest(assetId) {
395
+ return this.manifests.delete(assetId);
396
+ }
397
+ getManifest(assetId) {
398
+ const manifest = this.manifests.get(assetId);
399
+ if (!manifest) throw Errors.assetNotFound(assetId);
400
+ return structuredClone(manifest);
401
+ }
402
+ listManifests() {
403
+ return [...this.manifests.values()].map((manifest) => structuredClone(manifest));
404
+ }
405
+ get size() {
406
+ return this.manifests.size;
407
+ }
408
+ };
409
+ // modules/asset/loading/builtins/HouseDoor.js
410
+ async function createHouseDoor() {
411
+ const root = new THREE.Group();
412
+ root.name = "HouseDoor";
413
+ const hinge = new THREE.Group();
414
+ hinge.name = "doorHinge";
415
+ hinge.position.set(-.6, .62, 0);
416
+ root.add(hinge);
417
+ const wood = new THREE.MeshStandardMaterial({
418
+ color: 8476219,
419
+ roughness: .64
420
+ });
421
+ const trim = new THREE.MeshStandardMaterial({
422
+ color: 5978407,
423
+ roughness: .72
424
+ });
425
+ const metal = new THREE.MeshStandardMaterial({
426
+ color: 13151860,
427
+ metalness: .65,
428
+ roughness: .3
429
+ });
430
+ const leaf = new THREE.Mesh(new THREE.BoxGeometry(1.18, 2.02, .075), wood);
431
+ leaf.name = "Door";
432
+ leaf.position.set(.59, 1.01, 0);
433
+ leaf.castShadow = leaf.receiveShadow = true;
434
+ hinge.add(leaf);
435
+ for (const y of [.37, 1.64]) {
436
+ const panel = new THREE.Mesh(new THREE.BoxGeometry(.92, .48, .017), trim);
437
+ panel.position.set(.59, y, .046);
438
+ panel.castShadow = true;
439
+ hinge.add(panel);
440
+ }
441
+ for (const side of [-1, 1]) {
442
+ const knob = new THREE.Mesh(new THREE.SphereGeometry(.057, 12, 8), metal);
443
+ knob.position.set(1.04, 1.03, side * .12);
444
+ hinge.add(knob);
445
+ }
446
+ return root;
447
+ }
448
+ // modules/asset/loading/builtins/IndustrialCabinet.js
449
+ const box = (parent, name, size, position, material) => {
450
+ const mesh = new THREE.Mesh(new THREE.BoxGeometry(...size), material);
451
+ mesh.name = name;
452
+ mesh.position.set(...position);
453
+ mesh.castShadow = true;
454
+ mesh.receiveShadow = true;
455
+ parent.add(mesh);
456
+ return mesh;
457
+ };
458
+ const cylinder = (parent, name, radius, height, position, material) => {
459
+ const mesh = new THREE.Mesh(new THREE.CylinderGeometry(radius, radius, height, 12), material);
460
+ mesh.name = name;
461
+ mesh.position.set(...position);
462
+ mesh.castShadow = true;
463
+ parent.add(mesh);
464
+ return mesh;
465
+ };
466
+ async function createIndustrialCabinet() {
467
+ const root = new THREE.Group();
468
+ root.name = "IndustrialCabinet";
469
+ const shell = new THREE.MeshStandardMaterial({
470
+ color: "#344451",
471
+ metalness: .7,
472
+ roughness: .4
473
+ });
474
+ const frame = new THREE.MeshStandardMaterial({
475
+ color: "#1a2833",
476
+ metalness: .78,
477
+ roughness: .36
478
+ });
479
+ const doorFinish = new THREE.MeshStandardMaterial({
480
+ color: "#526e82",
481
+ metalness: .63,
482
+ roughness: .42
483
+ });
484
+ const drawerFinish = new THREE.MeshStandardMaterial({
485
+ color: "#667d8c",
486
+ metalness: .68,
487
+ roughness: .4
488
+ });
489
+ const inset = new THREE.MeshStandardMaterial({
490
+ color: "#2b4050",
491
+ metalness: .46,
492
+ roughness: .53
493
+ });
494
+ const steel = new THREE.MeshStandardMaterial({
495
+ color: "#b5c2ca",
496
+ metalness: .9,
497
+ roughness: .27
498
+ });
499
+ const dark = new THREE.MeshStandardMaterial({
500
+ color: "#101c26",
501
+ metalness: .23,
502
+ roughness: .7
503
+ });
504
+ const accent = new THREE.MeshStandardMaterial({
505
+ color: "#e2a84b",
506
+ metalness: .55,
507
+ roughness: .33
508
+ });
509
+ box(root, "Body", [
510
+ 1.84,
511
+ .08,
512
+ .73
513
+ ], [
514
+ 0,
515
+ .18,
516
+ 0
517
+ ], shell);
518
+ box(root, "Roof", [
519
+ 1.84,
520
+ .08,
521
+ .73
522
+ ], [
523
+ 0,
524
+ 2.09,
525
+ 0
526
+ ], shell);
527
+ box(root, "LeftWall", [
528
+ .08,
529
+ 1.88,
530
+ .73
531
+ ], [
532
+ -.88,
533
+ 1.12,
534
+ 0
535
+ ], shell);
536
+ box(root, "RightWall", [
537
+ .08,
538
+ 1.88,
539
+ .73
540
+ ], [
541
+ .88,
542
+ 1.12,
543
+ 0
544
+ ], shell);
545
+ box(root, "RearWall", [
546
+ 1.76,
547
+ 1.88,
548
+ .056
549
+ ], [
550
+ 0,
551
+ 1.12,
552
+ -.35
553
+ ], frame);
554
+ box(root, "CabinetDivider", [
555
+ 1.72,
556
+ .08,
557
+ .68
558
+ ], [
559
+ 0,
560
+ 1.12,
561
+ 0
562
+ ], frame);
563
+ box(root, "UpperShelf", [
564
+ 1.72,
565
+ .045,
566
+ .66
567
+ ], [
568
+ 0,
569
+ 1.61,
570
+ -.01
571
+ ], shell);
572
+ for (const x of [-.74, .74]) for (const z of [-.25, .25]) {
573
+ box(root, "AdjustableFoot", [
574
+ .16,
575
+ .13,
576
+ .16
577
+ ], [
578
+ x,
579
+ .065,
580
+ z
581
+ ], dark);
582
+ box(root, "FootTrim", [
583
+ .17,
584
+ .025,
585
+ .17
586
+ ], [
587
+ x,
588
+ .14,
589
+ z
590
+ ], steel);
591
+ }
592
+ box(root, "UpperFrontTrim", [
593
+ 1.8,
594
+ .045,
595
+ .035
596
+ ], [
597
+ 0,
598
+ 2.04,
599
+ .345
600
+ ], frame);
601
+ box(root, "MiddleFrontTrim", [
602
+ 1.8,
603
+ .042,
604
+ .035
605
+ ], [
606
+ 0,
607
+ 1.105,
608
+ .345
609
+ ], frame);
610
+ box(root, "LowerFrontTrim", [
611
+ 1.8,
612
+ .038,
613
+ .035
614
+ ], [
615
+ 0,
616
+ .225,
617
+ .345
618
+ ], frame);
619
+ box(root, "BrandPlate", [
620
+ .38,
621
+ .065,
622
+ .008
623
+ ], [
624
+ 0,
625
+ 2.14,
626
+ .365
627
+ ], accent);
628
+ for (const [side, name] of [[-1, "LeftDoorHinge"], [1, "RightDoorHinge"]]) {
629
+ const door = new THREE.Group();
630
+ door.name = name;
631
+ door.position.set(side * .81, 1.59, .393);
632
+ root.add(door);
633
+ const direction = -side;
634
+ box(door, side === -1 ? "LeftDoor" : "RightDoor", [
635
+ .774,
636
+ .86,
637
+ .056
638
+ ], [
639
+ direction * .395,
640
+ 0,
641
+ 0
642
+ ], doorFinish);
643
+ box(door, "DoorInset", [
644
+ .67,
645
+ .67,
646
+ .011
647
+ ], [
648
+ direction * .395,
649
+ 0,
650
+ .034
651
+ ], inset);
652
+ box(door, "InsetHeader", [
653
+ .59,
654
+ .015,
655
+ .012
656
+ ], [
657
+ direction * .395,
658
+ .26,
659
+ .044
660
+ ], steel);
661
+ for (let n = 0; n < 5; n++) box(door, "VentSlot", [
662
+ .4,
663
+ .019,
664
+ .012
665
+ ], [
666
+ direction * .395,
667
+ -.12 + n * .048,
668
+ .044
669
+ ], dark);
670
+ const handleX = direction * .694;
671
+ box(door, "DoorHandle", [
672
+ .027,
673
+ .23,
674
+ .032
675
+ ], [
676
+ handleX,
677
+ -.02,
678
+ .1
679
+ ], steel);
680
+ for (const y of [-.135, .095]) box(door, "HandleMount", [
681
+ .045,
682
+ .038,
683
+ .065
684
+ ], [
685
+ handleX,
686
+ y,
687
+ .067
688
+ ], frame);
689
+ for (const y of [1.27, 1.91]) cylinder(root, "HingePin", .029, .15, [
690
+ side * .81,
691
+ y,
692
+ .407
693
+ ], steel);
694
+ }
695
+ for (const [name, y] of [["UpperDrawerSlide", .81], ["LowerDrawerSlide", .41]]) {
696
+ const drawer = new THREE.Group();
697
+ drawer.name = name;
698
+ drawer.position.set(0, y, 0);
699
+ root.add(drawer);
700
+ box(drawer, "DrawerFloor", [
701
+ 1.45,
702
+ .035,
703
+ .62
704
+ ], [
705
+ 0,
706
+ -.137,
707
+ .065
708
+ ], steel);
709
+ box(drawer, "DrawerRear", [
710
+ 1.45,
711
+ .25,
712
+ .035
713
+ ], [
714
+ 0,
715
+ -.002,
716
+ -.245
717
+ ], frame);
718
+ for (const side of [-1, 1]) box(drawer, "DrawerSide", [
719
+ .036,
720
+ .25,
721
+ .61
722
+ ], [
723
+ side * .716,
724
+ -.002,
725
+ .065
726
+ ], frame);
727
+ box(drawer, "DrawerFront", [
728
+ 1.55,
729
+ .32,
730
+ .054
731
+ ], [
732
+ 0,
733
+ 0,
734
+ .393
735
+ ], drawerFinish);
736
+ box(drawer, "DrawerInset", [
737
+ 1.37,
738
+ .226,
739
+ .012
740
+ ], [
741
+ 0,
742
+ 0,
743
+ .427
744
+ ], inset);
745
+ box(drawer, "DrawerPull", [
746
+ .35,
747
+ .033,
748
+ .035
749
+ ], [
750
+ 0,
751
+ .013,
752
+ .485
753
+ ], steel);
754
+ for (const x of [-.15, .15]) box(drawer, "PullMount", [
755
+ .04,
756
+ .058,
757
+ .07
758
+ ], [
759
+ x,
760
+ .013,
761
+ .453
762
+ ], steel);
763
+ box(drawer, "DrawerLabel", [
764
+ .19,
765
+ .035,
766
+ .013
767
+ ], [
768
+ .46,
769
+ .095,
770
+ .438
771
+ ], accent);
772
+ }
773
+ root.updateMatrixWorld(true);
774
+ return root;
775
+ }
776
+ // modules/asset/loading/builtins/BuiltinAssets.js
777
+ const createAgent = async () => {
778
+ const group = new THREE.Group();
779
+ const body = new THREE.Mesh(new THREE.CapsuleGeometry(.32, 1.06, 8, 16), new THREE.MeshStandardMaterial({
780
+ color: 5668797,
781
+ roughness: .28,
782
+ metalness: .48
783
+ }));
784
+ body.position.y = .85;
785
+ body.castShadow = body.receiveShadow = true;
786
+ group.add(body);
787
+ const visor = new THREE.Mesh(new THREE.BoxGeometry(.34, .12, .06), new THREE.MeshBasicMaterial({
788
+ color: 11130367,
789
+ toneMapped: false
790
+ }));
791
+ visor.position.set(0, 1.12, -.29);
792
+ group.add(visor);
793
+ const ring = new THREE.Mesh(new THREE.TorusGeometry(.42, .025, 8, 32), new THREE.MeshBasicMaterial({
794
+ color: 8238335,
795
+ toneMapped: false
796
+ }));
797
+ ring.position.y = .08;
798
+ ring.rotation.x = Math.PI / 2;
799
+ group.add(ring);
800
+ const hold = new THREE.Group();
801
+ hold.name = "HoldAnchor";
802
+ hold.position.set(0, .95, -.62);
803
+ group.add(hold);
804
+ return group;
805
+ };
806
+ const createChair = async () => {
807
+ const group = new THREE.Group();
808
+ const material = new THREE.MeshStandardMaterial({
809
+ color: 7438442,
810
+ roughness: .75
811
+ });
812
+ const seat = new THREE.Mesh(new THREE.BoxGeometry(.76, .1, .76), material);
813
+ seat.position.y = .72;
814
+ seat.castShadow = seat.receiveShadow = true;
815
+ group.add(seat);
816
+ const back = new THREE.Mesh(new THREE.BoxGeometry(.76, .9, .1), material);
817
+ back.position.set(0, 1.16, -.33);
818
+ back.castShadow = back.receiveShadow = true;
819
+ group.add(back);
820
+ for (const x of [-.3, .3]) for (const z of [-.3, .3]) {
821
+ const leg = new THREE.Mesh(new THREE.BoxGeometry(.08, .68, .08), material);
822
+ leg.position.set(x, .34, z);
823
+ leg.castShadow = leg.receiveShadow = true;
824
+ group.add(leg);
825
+ }
826
+ return group;
827
+ };
828
+ const createCup = async () => {
829
+ const group = new THREE.Group();
830
+ const body = new THREE.Mesh(new THREE.CylinderGeometry(.16, .13, .32, 28), new THREE.MeshStandardMaterial({
831
+ color: 15330805,
832
+ roughness: .35
833
+ }));
834
+ body.position.y = .16;
835
+ body.castShadow = body.receiveShadow = true;
836
+ group.add(body);
837
+ return group;
838
+ };
839
+ const createTable = async () => {
840
+ const group = new THREE.Group();
841
+ const material = new THREE.MeshStandardMaterial({
842
+ color: 10119747,
843
+ roughness: .72
844
+ });
845
+ const top = new THREE.Mesh(new THREE.BoxGeometry(2.4, .16, 1.25), material);
846
+ top.position.y = 1;
847
+ top.castShadow = top.receiveShadow = true;
848
+ group.add(top);
849
+ for (const x of [-1.02, 1.02]) for (const z of [-.46, .46]) {
850
+ const leg = new THREE.Mesh(new THREE.BoxGeometry(.14, .94, .14), material);
851
+ leg.position.set(x, .47, z);
852
+ leg.castShadow = leg.receiveShadow = true;
853
+ group.add(leg);
854
+ }
855
+ return group;
856
+ };
857
+ const builtinAssetFactories = Object.freeze({
858
+ agent: createAgent,
859
+ chair: createChair,
860
+ cup: createCup,
861
+ table: createTable,
862
+ house_door: createHouseDoor,
863
+ industrial_cabinet: createIndustrialCabinet
864
+ });
865
+ // modules/asset/loading/AssetLoader.js
866
+ var AssetLoader = class {
867
+ constructor({ registry, compiledStore = null, gltfLoader = new GltfAssetLoader(), factories = builtinAssetFactories, maxResidentBytes = 268435456 } = {}) {
868
+ if (!registry?.getManifest || !registry?.has) throw new TypeError("AssetLoader requires an AssetRegistry");
869
+ if (!gltfLoader || typeof gltfLoader.loadScene !== "function") throw new TypeError("AssetLoader requires a glTF asset loader");
870
+ this.registry = registry;
871
+ this.compiledStore = compiledStore;
872
+ this.gltfLoader = gltfLoader;
873
+ this.factories = new Map(Object.entries(factories || {}));
874
+ this.shared = /* @__PURE__ */ new Map();
875
+ this.residentBytes = 0;
876
+ this.maxResidentBytes = maxResidentBytes;
877
+ }
878
+ registerFactory(assetId, factory) {
879
+ if (typeof factory !== "function") throw new TypeError(`Asset factory for ${assetId} must be a function`);
880
+ this.factories.set(assetId, factory);
881
+ }
882
+ configureRenderer(renderer) {
883
+ return this.gltfLoader.configureRenderer?.(renderer) ?? false;
884
+ }
885
+ async instantiate(assetId, { signal } = {}) {
886
+ const manifest = this.registry.getManifest(assetId);
887
+ let object;
888
+ if (["glb", "compiled"].includes(manifest.source?.kind)) object = await this.instantiateShared(manifest, signal);
889
+ else {
890
+ const factory = this.factories.get(assetId);
891
+ if (!factory) throw Errors.assetNotFound(assetId);
892
+ object = await factory();
893
+ }
894
+ try {
895
+ this.validateNodes(object, manifest);
896
+ object.name ||= assetId;
897
+ object.userData.assetId = assetId;
898
+ object.userData.manifest = manifest;
899
+ return {
900
+ object,
901
+ manifest
902
+ };
903
+ } catch (error) {
904
+ disposeObject3D(object);
905
+ throw error;
906
+ }
907
+ }
908
+ stats() {
909
+ return {
910
+ resources: this.shared.size,
911
+ references: [...this.shared.values()].reduce((sum, entry) => sum + entry.users, 0),
912
+ estimatedResidentBytes: this.residentBytes,
913
+ maxResidentBytes: this.maxResidentBytes
914
+ };
915
+ }
916
+ async instantiateShared(manifest, signal) {
917
+ if (signal?.aborted) throw Object.assign(/* @__PURE__ */ new Error("ASSET_CANCELLED"), { code: "ASSET_CANCELLED" });
918
+ const source = manifest.source;
919
+ const key = source.kind === "compiled" ? `compiled:${source.key}` : `glb:${source.url}`;
920
+ let entry = this.shared.get(key);
921
+ if (!entry) {
922
+ entry = {
923
+ users: 0,
924
+ bytes: 0,
925
+ root: null,
926
+ promise: null
927
+ };
928
+ this.shared.set(key, entry);
929
+ entry.promise = (async () => {
930
+ const root = source.kind === "compiled" ? await this.loadCompiled(source) : await this.loadGLB(source.url);
931
+ const bytes = estimateResourceBytes(root);
932
+ if (this.residentBytes + bytes > this.maxResidentBytes) {
933
+ disposeObject3D(root);
934
+ throw Object.assign(/* @__PURE__ */ new Error("ASSET_RESIDENT_BUDGET"), { code: "ASSET_RESIDENT_BUDGET" });
935
+ }
936
+ entry.root = root;
937
+ entry.bytes = bytes;
938
+ this.residentBytes += bytes;
939
+ return root;
940
+ })();
941
+ }
942
+ entry.users++;
943
+ const release = () => {
944
+ entry.users--;
945
+ if (!entry.users) {
946
+ this.shared.delete(key);
947
+ this.residentBytes -= entry.bytes;
948
+ if (entry.root) disposeObject3D(entry.root);
949
+ }
950
+ };
951
+ try {
952
+ const root = await entry.promise;
953
+ if (signal?.aborted) throw Object.assign(/* @__PURE__ */ new Error("ASSET_CANCELLED"), { code: "ASSET_CANCELLED" });
954
+ this.validateNodes(root, manifest);
955
+ const object = clone$5(root), materials = /* @__PURE__ */ new Map();
956
+ object.traverse((node) => {
957
+ if (!node.material) return;
958
+ const copy = (material) => {
959
+ if (!materials.has(material)) materials.set(material, material.clone());
960
+ return materials.get(material);
961
+ };
962
+ node.material = Array.isArray(node.material) ? node.material.map(copy) : copy(node.material);
963
+ });
964
+ let released = false;
965
+ object[RELEASE_RESOURCE] = () => {
966
+ if (!released) {
967
+ released = true;
968
+ for (const material of materials.values()) material.dispose();
969
+ release();
970
+ }
971
+ return {
972
+ geometries: 0,
973
+ materials: materials.size,
974
+ textures: 0
975
+ };
976
+ };
977
+ return object;
978
+ } catch (error) {
979
+ release();
980
+ throw error;
981
+ }
982
+ }
983
+ validateNodes(object, manifest) {
984
+ const missing = (manifest.requiredNodes || []).filter((name) => !object.getObjectByName(name));
985
+ if (missing.length) throw Errors.invalidManifest(`Asset ${manifest.id} is missing required GLB nodes: ${missing.join(", ")}`, {
986
+ id: manifest.id,
987
+ missing
988
+ });
989
+ }
990
+ async loadCompiled(source) {
991
+ const stored = await this.compiledStore?.get(source.key);
992
+ if (!stored?.bytes) {
993
+ if (source.fallbackUrl) return this.loadGLB(source.fallbackUrl);
994
+ throw new Error(`Compiled asset binary missing: ${source.key}`);
995
+ }
996
+ if (this.gltfLoader.loadBytes) {
997
+ const object = await this.gltfLoader.loadBytes(stored.bytes);
998
+ object.traverse((node) => {
999
+ if (node.isMesh) {
1000
+ node.castShadow = true;
1001
+ node.receiveShadow = true;
1002
+ }
1003
+ });
1004
+ return object;
1005
+ }
1006
+ const blob = new Blob([stored.bytes], { type: "model/gltf-binary" });
1007
+ const url = URL.createObjectURL(blob);
1008
+ try {
1009
+ return await this.loadGLB(url);
1010
+ } finally {
1011
+ URL.revokeObjectURL(url);
1012
+ }
1013
+ }
1014
+ async loadGLB(url) {
1015
+ const scene = await this.gltfLoader.loadScene(url);
1016
+ scene.traverse((node) => {
1017
+ if (!node.isMesh) return;
1018
+ node.castShadow = true;
1019
+ node.receiveShadow = true;
1020
+ });
1021
+ return scene;
1022
+ }
1023
+ };
1024
+ function estimateResourceBytes(root) {
1025
+ const buffers = /* @__PURE__ */ new Set(), textures = /* @__PURE__ */ new Set();
1026
+ let total = 0;
1027
+ root.traverse((node) => {
1028
+ for (const attribute of [...Object.values(node.geometry?.attributes || {}), node.geometry?.index].filter(Boolean)) {
1029
+ const buffer = attribute.array?.buffer || attribute.data?.array?.buffer;
1030
+ if (buffer && !buffers.has(buffer)) {
1031
+ buffers.add(buffer);
1032
+ total += buffer.byteLength;
1033
+ }
1034
+ }
1035
+ for (const material of (Array.isArray(node.material) ? node.material : [node.material]).filter(Boolean)) for (const value of Object.values(material)) if (value?.isTexture && !textures.has(value)) {
1036
+ textures.add(value);
1037
+ total += (value.image?.width || 0) * (value.image?.height || 0) * 4;
1038
+ }
1039
+ });
1040
+ return total;
1041
+ }
1042
+ // modules/artifact/ArtifactDescriptor.js
1043
+ const HASH_RE = /^sha256:[0-9a-f]{64}$/;
1044
+ const SAFE_ID = /^[A-Za-z0-9_-]{1,160}$/;
1045
+ const SAFE_SLUG = /^[a-z0-9][a-z0-9._-]{0,95}$/i;
1046
+ const SAFE_SCHEMA_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
1047
+ const MIME_RE = /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i;
1048
+ const CONTROL_RE$1 = /[\u0000-\u001f\u007f]/;
1049
+ const UNSAFE_TEXT_RE$1 = /https?:\/\/|Bearer\s+|(?:^|\s)(?:[A-Za-z]:\\|\/)[^\s]+/i;
1050
+ const FORBIDDEN_KEY = /(authorization|api[-_]?key|access[-_]?token|refresh[-_]?token|secret|credential|signed[-_]?url|volume[-_]?path|file[-_]?path|(^|[_-])path($|[_-])|(^|[_-])url($|[_-])|traceback|stack|prompt|image[-_]?bytes|base64|remote[-_]?.*id|function[-_]?call[-_]?id)/i;
1051
+ Object.freeze([
1052
+ "declared",
1053
+ "verified",
1054
+ "rejected"
1055
+ ]);
1056
+ const ARTIFACT_LOCATION_KINDS = Object.freeze([
1057
+ "connector",
1058
+ "local-cache",
1059
+ "compiled-store",
1060
+ "legacy"
1061
+ ]);
1062
+ const ARTIFACT_LOCATION_SCOPES = Object.freeze([
1063
+ "session",
1064
+ "job",
1065
+ "project",
1066
+ "application"
1067
+ ]);
1068
+ const ARTIFACT_LOCATION_STATES = Object.freeze([
1069
+ "available",
1070
+ "unavailable",
1071
+ "expired",
1072
+ "evicted"
1073
+ ]);
1074
+ const ARTIFACT_RETENTION_CLASSES = Object.freeze([
1075
+ "ephemeral",
1076
+ "session",
1077
+ "project",
1078
+ "favorite",
1079
+ "persistent"
1080
+ ]);
1081
+ const ARTIFACT_LINEAGE_RELATIONS = Object.freeze([
1082
+ "derived_from",
1083
+ "input",
1084
+ "preview_of",
1085
+ "compiled_from"
1086
+ ]);
1087
+ const ARTIFACT_LEASE_HOLDER_KINDS = Object.freeze([
1088
+ "job",
1089
+ "project",
1090
+ "viewer",
1091
+ "transfer",
1092
+ "favorite",
1093
+ "application"
1094
+ ]);
1095
+ const LOCATION_KIND_SET = new Set(ARTIFACT_LOCATION_KINDS);
1096
+ const LOCATION_SCOPE_SET = new Set(ARTIFACT_LOCATION_SCOPES);
1097
+ const LOCATION_STATE_SET = new Set(ARTIFACT_LOCATION_STATES);
1098
+ const RETENTION_SET = new Set(ARTIFACT_RETENTION_CLASSES);
1099
+ const LINEAGE_RELATION_SET = new Set(ARTIFACT_LINEAGE_RELATIONS);
1100
+ const clone$4 = (value) => value == null ? value : structuredClone(value);
1101
+ var ArtifactContractError = class extends Error {
1102
+ constructor(code, message, details = {}) {
1103
+ super(message);
1104
+ this.name = "ArtifactContractError";
1105
+ this.code = code;
1106
+ this.details = clone$4(details);
1107
+ }
1108
+ };
1109
+ const requiredText = (value, field, max = 200) => {
1110
+ const text = String(value ?? "").trim();
1111
+ if (!text) throw new ArtifactContractError("ARTIFACT_DESCRIPTOR_INVALID", `Artifact descriptor requires ${field}`, { field });
1112
+ if (text.length > max || CONTROL_RE$1.test(text)) throw new ArtifactContractError("ARTIFACT_DESCRIPTOR_INVALID", `Artifact descriptor has invalid ${field}`, { field });
1113
+ return text;
1114
+ };
1115
+ const optionalText = (value, field, max = 200) => value == null || value === "" ? null : requiredText(value, field, max);
1116
+ const safeUiText = (value, field, max = 200) => {
1117
+ const text = requiredText(value, field, max);
1118
+ if (UNSAFE_TEXT_RE$1.test(text)) throw new ArtifactContractError("ARTIFACT_FORBIDDEN_VALUE", `Artifact ${field} contains unsafe transport/path text`, { field });
1119
+ return text;
1120
+ };
1121
+ const optionalSafeUiText = (value, field, max = 200) => value == null || value === "" ? null : safeUiText(value, field, max);
1122
+ function requireSafeArtifactId(value, field = "id") {
1123
+ const raw = String(value ?? "");
1124
+ const id = raw.trim();
1125
+ if (!id || raw !== id || id.length > 160 || CONTROL_RE$1.test(id) || !SAFE_ID.test(id)) throw new ArtifactContractError("ARTIFACT_ID_INVALID", "Artifact ID must be an opaque URL-safe identifier", { field });
1126
+ return id;
1127
+ }
1128
+ function normalizeArtifactHash(value, field = "hash") {
1129
+ const hash = requiredText(value, field, 80);
1130
+ if (!HASH_RE.test(hash)) throw new ArtifactContractError("ARTIFACT_HASH_INVALID", "Artifact hash must be canonical sha256:<64 lowercase hex>", { field });
1131
+ return hash;
1132
+ }
1133
+ function assertNoForbiddenFields(value, path = "artifact") {
1134
+ if (!value || typeof value !== "object") return;
1135
+ if (Array.isArray(value)) {
1136
+ value.forEach((item, index) => assertNoForbiddenFields(item, `${path}[${index}]`));
1137
+ return;
1138
+ }
1139
+ for (const [key, item] of Object.entries(value)) {
1140
+ if (FORBIDDEN_KEY.test(key)) throw new ArtifactContractError("ARTIFACT_FORBIDDEN_FIELD", "Artifact descriptor contains a forbidden trust-boundary field", { path: `${path}.${key}` });
1141
+ assertNoForbiddenFields(item, `${path}.${key}`);
1142
+ }
1143
+ }
1144
+ function normalizeTime(value, field, { required = false } = {}) {
1145
+ if (value == null || value === "") {
1146
+ if (required) throw new ArtifactContractError("ARTIFACT_DESCRIPTOR_INVALID", `Artifact descriptor requires ${field}`, { field });
1147
+ return null;
1148
+ }
1149
+ const time = Date.parse(String(value));
1150
+ if (!Number.isFinite(time)) throw new ArtifactContractError("ARTIFACT_DESCRIPTOR_INVALID", `Artifact descriptor has invalid ${field}`, { field });
1151
+ return new Date(time).toISOString();
1152
+ }
1153
+ function normalizeVersionedRef(value, field) {
1154
+ if (value == null) return null;
1155
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new ArtifactContractError("ARTIFACT_DESCRIPTOR_INVALID", `Artifact ${field} must be a versioned reference`);
1156
+ return {
1157
+ id: optionalText(value.id, `${field}.id`, 120),
1158
+ version: optionalText(value.version, `${field}.version`, 80),
1159
+ revision: optionalText(value.revision, `${field}.revision`, 120)
1160
+ };
1161
+ }
1162
+ function normalizeProducer(value = {}) {
1163
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new ArtifactContractError("ARTIFACT_DESCRIPTOR_INVALID", "Artifact producer must be an object");
1164
+ const provider = requiredText(value.provider, "producer.provider", 120);
1165
+ const operation = requiredText(value.operation, "producer.operation", 180);
1166
+ if (!operation.startsWith(`${provider}.`) || !/\.v\d+$/.test(operation)) throw new ArtifactContractError("ARTIFACT_DESCRIPTOR_INVALID", "Artifact producer operation must be a stable provider-scoped operation ID", {
1167
+ provider,
1168
+ operation
1169
+ });
1170
+ const attempt = Number(value.attempt ?? 1);
1171
+ if (!Number.isSafeInteger(attempt) || attempt < 1) throw new ArtifactContractError("ARTIFACT_DESCRIPTOR_INVALID", "Artifact producer attempt must be a positive integer");
1172
+ const stage = optionalText(value.stage, "producer.stage", 100);
1173
+ if (stage && !SAFE_SLUG.test(stage)) throw new ArtifactContractError("ARTIFACT_DESCRIPTOR_INVALID", "Artifact producer stage must be a stable slug");
1174
+ return {
1175
+ jobId: requireSafeArtifactId(value.jobId, "producer.jobId"),
1176
+ provider,
1177
+ operation,
1178
+ stage,
1179
+ attempt,
1180
+ revision: optionalText(value.revision, "producer.revision", 120),
1181
+ model: normalizeVersionedRef(value.model, "producer.model"),
1182
+ workflow: normalizeVersionedRef(value.workflow, "producer.workflow")
1183
+ };
1184
+ }
1185
+ function normalizeLineage(value = {}, selfId) {
1186
+ if (value == null) return { parents: [] };
1187
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new ArtifactContractError("ARTIFACT_DESCRIPTOR_INVALID", "Artifact lineage must be an object");
1188
+ const parents = Array.isArray(value.parents) ? value.parents : [];
1189
+ const seen = /* @__PURE__ */ new Set();
1190
+ return { parents: parents.map((parent) => {
1191
+ if (!parent || typeof parent !== "object" || Array.isArray(parent)) throw new ArtifactContractError("ARTIFACT_DESCRIPTOR_INVALID", "Artifact lineage parent must be an object");
1192
+ const artifactId = requireSafeArtifactId(parent.artifactId, "lineage.parents[].artifactId");
1193
+ if (artifactId === selfId) throw new ArtifactContractError("ARTIFACT_LINEAGE_INVALID", "Artifact cannot derive from itself", { artifactId });
1194
+ const relation = requiredText(parent.relation, "lineage.parents[].relation", 64);
1195
+ if (!LINEAGE_RELATION_SET.has(relation)) throw new ArtifactContractError("ARTIFACT_LINEAGE_INVALID", `Unsupported artifact lineage relation: ${relation}`);
1196
+ const key = `${artifactId}:${relation}`;
1197
+ if (seen.has(key)) throw new ArtifactContractError("ARTIFACT_LINEAGE_INVALID", "Duplicate artifact lineage edge", {
1198
+ artifactId,
1199
+ relation
1200
+ });
1201
+ seen.add(key);
1202
+ return {
1203
+ artifactId,
1204
+ hash: normalizeArtifactHash(parent.hash, "lineage.parents[].hash"),
1205
+ relation
1206
+ };
1207
+ }) };
1208
+ }
1209
+ function normalizeAccess(value, locationKind, artifactId) {
1210
+ if (value == null) return null;
1211
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new ArtifactContractError("ARTIFACT_LOCATION_INVALID", "Artifact location access must be an object");
1212
+ const kind = requiredText(value.kind, "locations[].access.kind", 80);
1213
+ if (locationKind === "connector") {
1214
+ if (kind !== "connector-artifact") throw new ArtifactContractError("ARTIFACT_LOCATION_INVALID", "Connector location must use connector-artifact access");
1215
+ const accessArtifactId = requireSafeArtifactId(value.artifactId, "locations[].access.artifactId");
1216
+ if (accessArtifactId !== artifactId) throw new ArtifactContractError("ARTIFACT_LOCATION_INVALID", "Connector access artifactId must match descriptor identity");
1217
+ if (!value.connector || typeof value.connector !== "object" || Array.isArray(value.connector)) throw new ArtifactContractError("ARTIFACT_LOCATION_INVALID", "Connector artifact access requires connector identity");
1218
+ return {
1219
+ kind,
1220
+ artifactId: accessArtifactId,
1221
+ connector: {
1222
+ id: requireSafeArtifactId(value.connector.id, "locations[].access.connector.id"),
1223
+ instance: requireSafeArtifactId(value.connector.instance, "locations[].access.connector.instance")
1224
+ }
1225
+ };
1226
+ }
1227
+ if (locationKind === "local-cache") {
1228
+ if (kind !== "cache-key") throw new ArtifactContractError("ARTIFACT_LOCATION_INVALID", "Local cache location must use cache-key access");
1229
+ return {
1230
+ kind,
1231
+ key: requireSafeArtifactId(value.key, "locations[].access.key")
1232
+ };
1233
+ }
1234
+ if (locationKind === "compiled-store") {
1235
+ if (kind !== "compiled-key") throw new ArtifactContractError("ARTIFACT_LOCATION_INVALID", "Compiled location must use compiled-key access");
1236
+ return {
1237
+ kind,
1238
+ key: requireSafeArtifactId(value.key, "locations[].access.key")
1239
+ };
1240
+ }
1241
+ if (value) throw new ArtifactContractError("ARTIFACT_LOCATION_INVALID", "Legacy location access is intentionally opaque and unavailable to browser code");
1242
+ return null;
1243
+ }
1244
+ function normalizeArtifactLocation(value = {}, artifactId) {
1245
+ assertNoForbiddenFields(value, "location");
1246
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new ArtifactContractError("ARTIFACT_LOCATION_INVALID", "Artifact location must be an object");
1247
+ const kind = requiredText(value.kind, "locations[].kind", 64);
1248
+ const scope = requiredText(value.scope, "locations[].scope", 64);
1249
+ const state = requiredText(value.state, "locations[].state", 64);
1250
+ if (!LOCATION_KIND_SET.has(kind)) throw new ArtifactContractError("ARTIFACT_LOCATION_INVALID", `Unsupported artifact location kind: ${kind}`);
1251
+ if (!LOCATION_SCOPE_SET.has(scope)) throw new ArtifactContractError("ARTIFACT_LOCATION_INVALID", `Unsupported artifact location scope: ${scope}`);
1252
+ if (!LOCATION_STATE_SET.has(state)) throw new ArtifactContractError("ARTIFACT_LOCATION_INVALID", `Unsupported artifact location state: ${state}`);
1253
+ const verifiedAt = normalizeTime(value.verifiedAt, "locations[].verifiedAt");
1254
+ const expiresAt = normalizeTime(value.expiresAt, "locations[].expiresAt");
1255
+ if (verifiedAt && expiresAt && Date.parse(expiresAt) < Date.parse(verifiedAt)) throw new ArtifactContractError("ARTIFACT_LOCATION_INVALID", "Artifact location expires before it was verified");
1256
+ const access = normalizeAccess(value.access, kind, artifactId);
1257
+ if (state === "available" && kind !== "legacy" && !access) throw new ArtifactContractError("ARTIFACT_LOCATION_INVALID", "Available artifact location requires a safe access handle", { kind });
1258
+ return {
1259
+ id: requireSafeArtifactId(value.id, "locations[].id"),
1260
+ kind,
1261
+ scope,
1262
+ state,
1263
+ verifiedAt,
1264
+ expiresAt,
1265
+ access
1266
+ };
1267
+ }
1268
+ function normalizeRetention(value = {}) {
1269
+ if (value == null) value = {};
1270
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new ArtifactContractError("ARTIFACT_DESCRIPTOR_INVALID", "Artifact retention must be an object");
1271
+ const retentionClass = String(value.class || "ephemeral");
1272
+ if (!RETENTION_SET.has(retentionClass)) throw new ArtifactContractError("ARTIFACT_DESCRIPTOR_INVALID", `Unsupported artifact retention class: ${retentionClass}`);
1273
+ return {
1274
+ class: retentionClass,
1275
+ expiresAt: normalizeTime(value.expiresAt, "retention.expiresAt")
1276
+ };
1277
+ }
1278
+ function normalizeWarnings(value = []) {
1279
+ if (!Array.isArray(value)) throw new ArtifactContractError("ARTIFACT_DESCRIPTOR_INVALID", "Artifact warnings must be an array");
1280
+ return [...new Set(value.map((warning, index) => safeUiText(warning, `warnings[${index}]`, 240)))];
1281
+ }
1282
+ function normalizeSchema(value = {}) {
1283
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new ArtifactContractError("ARTIFACT_DESCRIPTOR_INVALID", "Artifact schema must be an object");
1284
+ const id = requiredText(value.id, "schema.id", 128);
1285
+ if (!SAFE_SCHEMA_ID.test(id)) throw new ArtifactContractError("ARTIFACT_DESCRIPTOR_INVALID", "Artifact schema id is invalid");
1286
+ return {
1287
+ id,
1288
+ version: requiredText(value.version, "schema.version", 64)
1289
+ };
1290
+ }
1291
+ function normalizeArtifactDescriptor(payload = {}) {
1292
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) throw new ArtifactContractError("ARTIFACT_DESCRIPTOR_INVALID", "Artifact descriptor must be an object");
1293
+ assertNoForbiddenFields(payload);
1294
+ const id = requireSafeArtifactId(payload.id);
1295
+ const role = requiredText(payload.role, "role", 96);
1296
+ const type = requiredText(payload.type, "type", 96);
1297
+ const format = requiredText(payload.format, "format", 64);
1298
+ if (!SAFE_SLUG.test(role) || !SAFE_SLUG.test(type) || !SAFE_SLUG.test(format)) throw new ArtifactContractError("ARTIFACT_DESCRIPTOR_INVALID", "Artifact role/type/format must use stable slugs");
1299
+ const mime = requiredText(payload.mime, "mime", 120).toLowerCase();
1300
+ if (!MIME_RE.test(mime)) throw new ArtifactContractError("ARTIFACT_DESCRIPTOR_INVALID", "Artifact MIME is invalid");
1301
+ const bytes = Number(payload.bytes);
1302
+ if (!Number.isSafeInteger(bytes) || bytes < 0) throw new ArtifactContractError("ARTIFACT_BYTES_INVALID", "Artifact bytes must be a non-negative safe integer");
1303
+ const createdAt = normalizeTime(payload.createdAt, "createdAt", { required: true });
1304
+ const expiresAt = normalizeTime(payload.expiresAt, "expiresAt");
1305
+ if (expiresAt && Date.parse(expiresAt) < Date.parse(createdAt)) throw new ArtifactContractError("ARTIFACT_DESCRIPTOR_INVALID", "Artifact expires before it was created");
1306
+ if (payload.integrity?.state && payload.integrity.state !== "declared") throw new ArtifactContractError("ARTIFACT_INTEGRITY_EVIDENCE_REQUIRED", "Untrusted descriptor cannot self-promote integrity beyond declared");
1307
+ const locations = Array.isArray(payload.locations) ? payload.locations.map((location) => normalizeArtifactLocation(location, id)) : [];
1308
+ const locationIds = /* @__PURE__ */ new Set();
1309
+ for (const location of locations) {
1310
+ if (locationIds.has(location.id)) throw new ArtifactContractError("ARTIFACT_LOCATION_INVALID", "Duplicate artifact location ID", { locationId: location.id });
1311
+ locationIds.add(location.id);
1312
+ }
1313
+ return {
1314
+ id,
1315
+ role,
1316
+ type,
1317
+ schema: normalizeSchema(payload.schema),
1318
+ displayName: optionalSafeUiText(payload.displayName, "displayName", 160),
1319
+ mime,
1320
+ format,
1321
+ bytes,
1322
+ hash: normalizeArtifactHash(payload.hash),
1323
+ producer: normalizeProducer(payload.producer),
1324
+ lineage: normalizeLineage(payload.lineage, id),
1325
+ createdAt,
1326
+ expiresAt,
1327
+ integrity: {
1328
+ state: "declared",
1329
+ verifiedAt: null,
1330
+ method: null,
1331
+ rejection: null
1332
+ },
1333
+ warnings: normalizeWarnings(payload.warnings || []),
1334
+ retention: (() => {
1335
+ const retention = normalizeRetention(payload.retention);
1336
+ if (retention.expiresAt && Date.parse(retention.expiresAt) < Date.parse(createdAt)) throw new ArtifactContractError("ARTIFACT_DESCRIPTOR_INVALID", "Artifact retention expires before artifact creation");
1337
+ return retention;
1338
+ })(),
1339
+ locations
1340
+ };
1341
+ }
1342
+ function artifactImmutableSignature(descriptor) {
1343
+ return JSON.stringify({
1344
+ id: descriptor.id,
1345
+ role: descriptor.role,
1346
+ type: descriptor.type,
1347
+ schema: descriptor.schema,
1348
+ mime: descriptor.mime,
1349
+ format: descriptor.format,
1350
+ bytes: descriptor.bytes,
1351
+ hash: descriptor.hash,
1352
+ producer: descriptor.producer,
1353
+ lineage: descriptor.lineage,
1354
+ createdAt: descriptor.createdAt
1355
+ });
1356
+ }
1357
+ // modules/asset/model/AssetRef.js
1358
+ const clean = (value) => String(value ?? "").trim();
1359
+ function createAssetRef(assetId) {
1360
+ const id = clean(assetId);
1361
+ if (!id) throw new TypeError("AssetRef requires assetId");
1362
+ return { assetId: id };
1363
+ }
1364
+ // modules/asset/production/AssetProductionPipeline.js
1365
+ const SAFE_ASSET_ID = /^[A-Za-z0-9_-]{1,160}$/;
1366
+ const CONTROL_RE = /[\u0000-\u001f\u007f]/;
1367
+ const UNSAFE_TEXT_RE = /https?:\/\/|Bearer\s+|(?:^|\s)(?:[A-Za-z]:\\|\/)[^\s]+/i;
1368
+ const clone$3 = (value) => value == null ? value : structuredClone(value);
1369
+ let fallbackSequence = 0;
1370
+ var AssetProductionError = class extends Error {
1371
+ constructor(code, message, details = {}) {
1372
+ super(message);
1373
+ this.name = "AssetProductionError";
1374
+ this.code = code;
1375
+ this.details = clone$3(details);
1376
+ }
1377
+ };
1378
+ function requireAssetId(value) {
1379
+ const id = String(value ?? "").trim();
1380
+ if (!SAFE_ASSET_ID.test(id)) throw new AssetProductionError("ASSET_ID_INVALID", "Asset production requires a URL-safe AgentScape assetId");
1381
+ return id;
1382
+ }
1383
+ function safeLabel(value, fallback) {
1384
+ const text = String(value ?? fallback ?? "").trim();
1385
+ if (!text || text.length > 160 || CONTROL_RE.test(text) || UNSAFE_TEXT_RE.test(text)) throw new AssetProductionError("ASSET_LABEL_INVALID", "Asset production label is invalid or contains transport/path detail");
1386
+ return text;
1387
+ }
1388
+ const defaultIdFactory = (kind) => {
1389
+ return `${kind}_${globalThis.crypto?.randomUUID?.()?.replaceAll("-", "") || `${Date.now()}_${++fallbackSequence}`}`;
1390
+ };
1391
+ function selectVerifiedCacheLocation(artifact) {
1392
+ return [...artifact.locations || []].filter((location) => location.kind === "local-cache" && location.state === "available" && location.access?.kind === "cache-key").sort((a, b) => a.id.localeCompare(b.id))[0] || null;
1393
+ }
1394
+ function safeProducer(artifact) {
1395
+ const producer = artifact.producer || {};
1396
+ return {
1397
+ jobId: producer.jobId || null,
1398
+ provider: producer.provider || null,
1399
+ operation: producer.operation || null,
1400
+ stage: producer.stage || null,
1401
+ attempt: producer.attempt || null,
1402
+ revision: producer.revision || null,
1403
+ model: clone$3(producer.model || null),
1404
+ workflow: clone$3(producer.workflow || null)
1405
+ };
1406
+ }
1407
+ function buildProvenance({ artifact, assetId, admission }) {
1408
+ return {
1409
+ sourceArtifact: {
1410
+ id: artifact.id,
1411
+ hash: artifact.hash,
1412
+ bytes: artifact.bytes,
1413
+ mime: artifact.mime,
1414
+ producer: safeProducer(artifact)
1415
+ },
1416
+ assetId,
1417
+ admission: admission ? {
1418
+ status: admission.status,
1419
+ reasons: [...admission.reasons || []]
1420
+ } : null
1421
+ };
1422
+ }
1423
+ var AssetProductionPipeline = class {
1424
+ constructor({ artifactRegistry, byteStore, assetCompiler, assetRegistry, onManifestRegistered = null, events = null, now = () => Date.now(), idFactory = defaultIdFactory } = {}) {
1425
+ if (!artifactRegistry?.get || !artifactRegistry?.acquireLease || !artifactRegistry?.releaseLease) throw new AssetProductionError("ASSET_PIPELINE_INVALID", "AssetProductionPipeline requires ArtifactRegistry");
1426
+ if (!byteStore?.get) throw new AssetProductionError("ASSET_PIPELINE_INVALID", "AssetProductionPipeline requires a readable Artifact byte store");
1427
+ if (!assetCompiler?.compile) throw new AssetProductionError("ASSET_PIPELINE_INVALID", "AssetProductionPipeline requires AssetCompiler");
1428
+ if (!assetRegistry?.registerManifest) throw new AssetProductionError("ASSET_PIPELINE_INVALID", "AssetProductionPipeline requires AssetRegistry");
1429
+ this.artifactRegistry = artifactRegistry;
1430
+ this.byteStore = byteStore;
1431
+ this.assetCompiler = assetCompiler;
1432
+ this.assetRegistry = assetRegistry;
1433
+ this.onManifestRegistered = typeof onManifestRegistered === "function" ? onManifestRegistered : null;
1434
+ this.events = events;
1435
+ this.now = now;
1436
+ this.idFactory = idFactory;
1437
+ }
1438
+ inspectInput({ artifactId, assetId, label } = {}) {
1439
+ const sourceArtifactId = requireSafeArtifactId(artifactId);
1440
+ const targetAssetId = requireAssetId(assetId);
1441
+ if (sourceArtifactId === targetAssetId) throw new AssetProductionError("ASSET_IDENTITY_COLLISION", "Artifact ID and AgentScape assetId must remain distinct identities", {
1442
+ artifactId: sourceArtifactId,
1443
+ assetId: targetAssetId
1444
+ });
1445
+ const artifact = this.artifactRegistry.get(sourceArtifactId);
1446
+ if (!artifact) throw new AssetProductionError("ARTIFACT_NOT_FOUND", "Source Artifact does not exist", { artifactId: sourceArtifactId });
1447
+ if (artifact.integrity?.state !== "verified") throw new AssetProductionError("ARTIFACT_NOT_VERIFIED", "Source Artifact must be independently verified before compilation", {
1448
+ artifactId: sourceArtifactId,
1449
+ integrity: artifact.integrity?.state || null
1450
+ });
1451
+ if (artifact.mime !== "model/gltf-binary" || artifact.format !== "glb") throw new AssetProductionError("ARTIFACT_FORMAT_UNSUPPORTED", "AS-05 accepts verified GLB artifacts only", {
1452
+ artifactId: sourceArtifactId,
1453
+ mime: artifact.mime,
1454
+ format: artifact.format
1455
+ });
1456
+ const location = selectVerifiedCacheLocation(artifact);
1457
+ if (!location) throw new AssetProductionError("ARTIFACT_LOCAL_BYTES_UNAVAILABLE", "Verified Artifact has no available local-cache location", { artifactId: sourceArtifactId });
1458
+ const entry = this.byteStore.get(location.access.key);
1459
+ if (!entry?.data) throw new AssetProductionError("ARTIFACT_LOCAL_BYTES_UNAVAILABLE", "Artifact local-cache entry is missing", {
1460
+ artifactId: sourceArtifactId,
1461
+ cacheKey: location.access.key
1462
+ });
1463
+ if (!(entry.data instanceof Uint8Array)) throw new AssetProductionError("ARTIFACT_CACHE_IDENTITY_MISMATCH", "Artifact cache entry does not expose Uint8Array bytes", { artifactId: sourceArtifactId });
1464
+ const mismatches = [];
1465
+ if (entry.artifactId !== artifact.id) mismatches.push("artifactId");
1466
+ if (entry.hash !== artifact.hash) mismatches.push("hash");
1467
+ if (entry.bytes !== artifact.bytes || entry.data.byteLength !== artifact.bytes) mismatches.push("bytes");
1468
+ if (String(entry.mime || "").toLowerCase() !== artifact.mime) mismatches.push("mime");
1469
+ if (mismatches.length) throw new AssetProductionError("ARTIFACT_CACHE_IDENTITY_MISMATCH", "Artifact local-cache identity does not match verified descriptor", {
1470
+ artifactId: sourceArtifactId,
1471
+ cacheKey: location.access.key,
1472
+ mismatches
1473
+ });
1474
+ return {
1475
+ artifact,
1476
+ location,
1477
+ entry,
1478
+ assetId: targetAssetId,
1479
+ label: safeLabel(label, artifact.displayName || targetAssetId),
1480
+ sourceName: `${artifact.id}.glb`
1481
+ };
1482
+ }
1483
+ async produce(request = {}) {
1484
+ const authoringIntent = request.authoringIntent == null ? null : { usage: request.authoringIntent.usage };
1485
+ if (authoringIntent && ![
1486
+ "static",
1487
+ "movable",
1488
+ "interactive"
1489
+ ].includes(authoringIntent.usage)) throw new AssetProductionError("AUTHORING_INTENT_INVALID", "Unsupported authored asset usage");
1490
+ const input = this.inspectInput(request);
1491
+ if (this.assetRegistry.has?.(input.assetId)) {
1492
+ const existing = this.assetRegistry.getManifest(input.assetId);
1493
+ const source = existing?.provenance?.assetProduction?.sourceArtifact;
1494
+ if (source?.id === input.artifact.id && source?.hash === input.artifact.hash && JSON.stringify(existing.provenance?.authoringIntent || null) === JSON.stringify(authoringIntent)) {
1495
+ const admission = assetAdmission(existing, { generated: true });
1496
+ return {
1497
+ status: admission.status === "ready" ? "asset-ready" : admission.status === "provisional" ? "asset-provisional" : "asset-rejected",
1498
+ stage: "registered",
1499
+ registered: false,
1500
+ reused: true,
1501
+ artifactId: input.artifact.id,
1502
+ assetId: input.assetId,
1503
+ manifest: existing,
1504
+ compiler: { quality: clone$3(existing.compiler?.quality || null) },
1505
+ admission,
1506
+ provenance: buildProvenance({
1507
+ artifact: input.artifact,
1508
+ assetId: input.assetId,
1509
+ admission
1510
+ })
1511
+ };
1512
+ }
1513
+ throw new AssetProductionError("ASSET_ID_CONFLICT", "AgentScape assetId is already registered from different provenance", {
1514
+ assetId: input.assetId,
1515
+ artifactId: input.artifact.id,
1516
+ existingArtifactId: source?.id || null,
1517
+ existingArtifactHash: source?.hash || null
1518
+ });
1519
+ }
1520
+ const leaseId = requireSafeArtifactId(this.idFactory("lease", input.artifact, input.assetId), "leaseId");
1521
+ let leaseHeld = false;
1522
+ try {
1523
+ this.artifactRegistry.acquireLease(input.artifact.id, {
1524
+ id: leaseId,
1525
+ holder: {
1526
+ kind: "application",
1527
+ id: input.assetId
1528
+ },
1529
+ reason: "asset-compile",
1530
+ createdAt: new Date(this.now()).toISOString()
1531
+ });
1532
+ leaseHeld = true;
1533
+ this.events?.emit?.("assetProduction.started", {
1534
+ artifactId: input.artifact.id,
1535
+ assetId: input.assetId,
1536
+ provider: input.artifact.producer?.provider || null
1537
+ });
1538
+ let compiled;
1539
+ try {
1540
+ compiled = await this.assetCompiler.compile({
1541
+ bytes: new Uint8Array(input.entry.data),
1542
+ sourceName: input.sourceName,
1543
+ assetId: input.assetId,
1544
+ label: input.label,
1545
+ ...authoringIntent ? { authoringIntent } : {},
1546
+ ...request.definition ? { definition: request.definition } : {}
1547
+ });
1548
+ } catch (error) {
1549
+ if (error?.code === "ASSET_COMPILE_REJECTED") {
1550
+ const admission = {
1551
+ status: "rejected",
1552
+ reasons: ["COMPILER_REJECTED"]
1553
+ };
1554
+ const result = {
1555
+ status: "asset-rejected",
1556
+ stage: "compiler",
1557
+ registered: false,
1558
+ artifactId: input.artifact.id,
1559
+ assetId: input.assetId,
1560
+ compiler: { quality: clone$3(error.details || null) },
1561
+ admission,
1562
+ provenance: buildProvenance({
1563
+ artifact: input.artifact,
1564
+ assetId: input.assetId,
1565
+ admission
1566
+ })
1567
+ };
1568
+ this.events?.emit?.("assetProduction.rejected", clone$3(result));
1569
+ return result;
1570
+ }
1571
+ throw new AssetProductionError("COMPILER_FAILED", "AssetCompiler failed for a verified Artifact", {
1572
+ artifactId: input.artifact.id,
1573
+ assetId: input.assetId,
1574
+ cause: error?.code || error?.name || "Error"
1575
+ });
1576
+ }
1577
+ if (!compiled?.manifest) throw new AssetProductionError("COMPILER_FAILED", "AssetCompiler returned no manifest", {
1578
+ artifactId: input.artifact.id,
1579
+ assetId: input.assetId
1580
+ });
1581
+ const manifest = clone$3(compiled.manifest);
1582
+ if (manifest.id !== input.assetId) throw new AssetProductionError("COMPILER_IDENTITY_MISMATCH", "AssetCompiler manifest id does not match requested assetId", {
1583
+ expected: input.assetId,
1584
+ actual: manifest.id || null
1585
+ });
1586
+ const admission = assetAdmission(manifest, { generated: true });
1587
+ manifest.provenance = {
1588
+ ...manifest.provenance || {},
1589
+ assetProduction: buildProvenance({
1590
+ artifact: input.artifact,
1591
+ assetId: input.assetId,
1592
+ admission
1593
+ }),
1594
+ admission: admission ? {
1595
+ status: admission.status,
1596
+ reasons: [...admission.reasons || []]
1597
+ } : null
1598
+ };
1599
+ validateAssetManifest(manifest);
1600
+ if (admission.status === "rejected") {
1601
+ const result = {
1602
+ status: "asset-rejected",
1603
+ stage: "admission",
1604
+ registered: false,
1605
+ artifactId: input.artifact.id,
1606
+ assetId: input.assetId,
1607
+ manifest,
1608
+ compiler: { quality: clone$3(compiled.quality || null) },
1609
+ admission,
1610
+ provenance: buildProvenance({
1611
+ artifact: input.artifact,
1612
+ assetId: input.assetId,
1613
+ admission
1614
+ })
1615
+ };
1616
+ this.events?.emit?.("assetProduction.rejected", clone$3(result));
1617
+ return result;
1618
+ }
1619
+ let registered;
1620
+ try {
1621
+ registered = this.assetRegistry.registerManifest(manifest);
1622
+ } catch (error) {
1623
+ throw new AssetProductionError("MANIFEST_REGISTRATION_FAILED", "Compiled manifest could not be registered", {
1624
+ artifactId: input.artifact.id,
1625
+ assetId: input.assetId,
1626
+ cause: error?.code || error?.name || "Error"
1627
+ });
1628
+ }
1629
+ if (registered && this.onManifestRegistered) await this.onManifestRegistered(manifest);
1630
+ const status = admission.status === "ready" ? "asset-ready" : "asset-provisional";
1631
+ const result = {
1632
+ status,
1633
+ stage: "registered",
1634
+ registered: Boolean(registered),
1635
+ artifactId: input.artifact.id,
1636
+ assetId: input.assetId,
1637
+ manifest: this.assetRegistry.getManifest?.(input.assetId) || clone$3(manifest),
1638
+ compiler: { quality: clone$3(compiled.quality || null) },
1639
+ admission,
1640
+ provenance: buildProvenance({
1641
+ artifact: input.artifact,
1642
+ assetId: input.assetId,
1643
+ admission
1644
+ })
1645
+ };
1646
+ this.events?.emit?.("assetProduction.registered", {
1647
+ artifactId: input.artifact.id,
1648
+ assetId: input.assetId,
1649
+ status,
1650
+ admission: admission.status,
1651
+ provider: input.artifact.producer?.provider || null
1652
+ });
1653
+ return result;
1654
+ } finally {
1655
+ if (leaseHeld) this.artifactRegistry.releaseLease(leaseId);
1656
+ }
1657
+ }
1658
+ };
1659
+ function createAssetProducer({ artifactRegistry, byteStore, getAssetCompiler, assetRegistry, onManifestRegistered = null, events = null, now = () => Date.now(), idFactory = defaultIdFactory } = {}) {
1660
+ if (typeof getAssetCompiler !== "function") throw new AssetProductionError("ASSET_PRODUCTION_INVALID", "Asset production requires getAssetCompiler()");
1661
+ let pipeline = null;
1662
+ return async function produceAsset(request = {}) {
1663
+ if (!pipeline) pipeline = new AssetProductionPipeline({
1664
+ artifactRegistry,
1665
+ byteStore,
1666
+ assetCompiler: await getAssetCompiler(),
1667
+ assetRegistry,
1668
+ onManifestRegistered,
1669
+ events,
1670
+ now,
1671
+ idFactory
1672
+ });
1673
+ const result = await pipeline.produce(request);
1674
+ if (result.status === "asset-ready" || result.status === "asset-provisional") return {
1675
+ ...result,
1676
+ assetRef: createAssetRef(result.assetId)
1677
+ };
1678
+ return result;
1679
+ };
1680
+ }
1681
+ // foundation/JsonGateway.js
1682
+ var JsonGateway = class {
1683
+ constructor({ endpoint = "", fetchImpl = fetch, timeoutMs = 3e4, label = "Gateway" } = {}) {
1684
+ this.endpoint = String(endpoint || "").trim();
1685
+ this.fetchImpl = (...args) => fetchImpl(...args);
1686
+ this.timeoutMs = timeoutMs;
1687
+ this.label = label;
1688
+ }
1689
+ setEndpoint(endpoint) {
1690
+ this.endpoint = String(endpoint || "").trim();
1691
+ }
1692
+ isConfigured() {
1693
+ return Boolean(this.endpoint);
1694
+ }
1695
+ async postForm(form) {
1696
+ if (!this.endpoint) throw new Error(`${this.label} endpoint is not configured`);
1697
+ const controller = new AbortController();
1698
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
1699
+ try {
1700
+ const response = await this.fetchImpl(this.endpoint, {
1701
+ method: "POST",
1702
+ body: form,
1703
+ signal: controller.signal
1704
+ });
1705
+ if (!response.ok) throw new Error(`${this.label} HTTP ${response.status}`);
1706
+ return await response.json();
1707
+ } finally {
1708
+ clearTimeout(timer);
1709
+ }
1710
+ }
1711
+ async post(payload, { signal } = {}) {
1712
+ if (!this.endpoint) throw new Error(`${this.label} endpoint is not configured`);
1713
+ const controller = new AbortController();
1714
+ const abort = () => controller.abort(signal.reason);
1715
+ if (signal?.aborted) abort();
1716
+ else signal?.addEventListener("abort", abort, { once: true });
1717
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
1718
+ try {
1719
+ const response = await this.fetchImpl(this.endpoint, {
1720
+ method: "POST",
1721
+ headers: { "content-type": "application/json" },
1722
+ body: JSON.stringify(payload),
1723
+ signal: controller.signal
1724
+ });
1725
+ if (!response.ok) throw new Error(`${this.label} HTTP ${response.status}`);
1726
+ return await response.json();
1727
+ } finally {
1728
+ clearTimeout(timer);
1729
+ signal?.removeEventListener("abort", abort);
1730
+ }
1731
+ }
1732
+ };
1733
+ // modules/asset/production/compiler/providers/HttpCompilerProvider.js
1734
+ var HttpCompilerProvider = class extends JsonGateway {
1735
+ constructor(options = {}) {
1736
+ super({
1737
+ timeoutMs: 12e4,
1738
+ label: "Compiler provider",
1739
+ ...options
1740
+ });
1741
+ }
1742
+ async run(stage, payload) {
1743
+ return this.post({
1744
+ stage,
1745
+ ...payload
1746
+ });
1747
+ }
1748
+ async runPartGeometry(bytes, parts) {
1749
+ const form = new FormData();
1750
+ form.set("stage", "part-geometry");
1751
+ form.set("metadata", JSON.stringify({ parts }));
1752
+ form.set("asset", new Blob([bytes], { type: "model/gltf-binary" }), "asset.glb");
1753
+ return this.postForm(form);
1754
+ }
1755
+ async runUrdfProposal(bytes) {
1756
+ const data = bytes instanceof Uint8Array ? bytes : bytes instanceof ArrayBuffer ? new Uint8Array(bytes) : null;
1757
+ if (!data?.byteLength) throw new Error("URDF proposal requires non-empty bytes");
1758
+ const form = new FormData();
1759
+ form.set("stage", "urdf-proposal");
1760
+ form.set("asset", new Blob([data], { type: "application/xml" }), "asset.urdf");
1761
+ return this.postForm(form);
1762
+ }
1763
+ };
1764
+ // modules/asset/persistence/CompiledAssetStore.js
1765
+ const DB_NAME$2 = "agentscape-assets";
1766
+ const STORE_NAME$2 = "compiled-glb";
1767
+ const DB_VERSION$2 = 1;
1768
+ var CompiledAssetStore = class {
1769
+ constructor({ indexedDBImpl = globalThis.indexedDB, maxDecodeBytes = 33554432 } = {}) {
1770
+ this.indexedDB = indexedDBImpl;
1771
+ this.memory = /* @__PURE__ */ new Map();
1772
+ this.sources = /* @__PURE__ */ new Map();
1773
+ this.maxDecodeBytes = maxDecodeBytes;
1774
+ }
1775
+ registerSource(key, { bytes, read }) {
1776
+ if (!Number.isSafeInteger(bytes) || bytes < 0 || typeof read !== "function" || this.sources.has(key)) throw new TypeError("Invalid compiled resource source");
1777
+ this.sources.set(key, {
1778
+ bytes,
1779
+ read
1780
+ });
1781
+ }
1782
+ async open() {
1783
+ if (!this.indexedDB) return null;
1784
+ return new Promise((resolve, reject) => {
1785
+ const request = this.indexedDB.open(DB_NAME$2, DB_VERSION$2);
1786
+ request.onupgradeneeded = () => {
1787
+ const db = request.result;
1788
+ if (!db.objectStoreNames.contains(STORE_NAME$2)) db.createObjectStore(STORE_NAME$2);
1789
+ };
1790
+ request.onsuccess = () => resolve(request.result);
1791
+ request.onerror = () => reject(request.error);
1792
+ });
1793
+ }
1794
+ async put(key, bytes, metadata = {}) {
1795
+ const value = {
1796
+ bytes: bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes),
1797
+ metadata,
1798
+ savedAt: (/* @__PURE__ */ new Date()).toISOString()
1799
+ };
1800
+ const db = await this.open();
1801
+ if (!db) {
1802
+ this.memory.set(key, value);
1803
+ return key;
1804
+ }
1805
+ await new Promise((resolve, reject) => {
1806
+ const tx = db.transaction(STORE_NAME$2, "readwrite");
1807
+ tx.objectStore(STORE_NAME$2).put(value, key);
1808
+ tx.oncomplete = resolve;
1809
+ tx.onerror = () => reject(tx.error);
1810
+ });
1811
+ db.close();
1812
+ return key;
1813
+ }
1814
+ async get(key) {
1815
+ const source = this.sources.get(key);
1816
+ if (source) {
1817
+ if (source.bytes > this.maxDecodeBytes) throw Object.assign(/* @__PURE__ */ new Error("ASSET_DECODE_BUDGET"), { code: "ASSET_DECODE_BUDGET" });
1818
+ const bytes = new Uint8Array(source.bytes);
1819
+ let offset = 0;
1820
+ for await (const chunk of source.read()) {
1821
+ if (!(chunk instanceof Uint8Array) || offset + chunk.length > bytes.length) throw new Error("ASSET_RESOURCE_SIZE_MISMATCH");
1822
+ bytes.set(chunk, offset);
1823
+ offset += chunk.length;
1824
+ }
1825
+ if (offset !== bytes.length) throw new Error("ASSET_RESOURCE_SIZE_MISMATCH");
1826
+ return {
1827
+ bytes,
1828
+ metadata: { contentAddressed: true }
1829
+ };
1830
+ }
1831
+ const db = await this.open();
1832
+ if (!db) return this.memory.get(key) || null;
1833
+ const value = await new Promise((resolve, reject) => {
1834
+ const request = db.transaction(STORE_NAME$2, "readonly").objectStore(STORE_NAME$2).get(key);
1835
+ request.onsuccess = () => resolve(request.result || null);
1836
+ request.onerror = () => reject(request.error);
1837
+ });
1838
+ db.close();
1839
+ return value;
1840
+ }
1841
+ async has(key) {
1842
+ return Boolean(await this.get(key));
1843
+ }
1844
+ async delete(key) {
1845
+ if (this.sources.delete(key)) return true;
1846
+ const db = await this.open();
1847
+ if (!db) return this.memory.delete(key);
1848
+ await new Promise((resolve, reject) => {
1849
+ const tx = db.transaction(STORE_NAME$2, "readwrite");
1850
+ tx.objectStore(STORE_NAME$2).delete(key);
1851
+ tx.oncomplete = resolve;
1852
+ tx.onerror = () => reject(tx.error);
1853
+ });
1854
+ db.close();
1855
+ return true;
1856
+ }
1857
+ };
1858
+ // modules/asset/persistence/AssetManifestStore.js
1859
+ const DB_NAME$1 = "agentscape-asset-manifests";
1860
+ const DB_VERSION$1 = 1;
1861
+ const STORE_NAME$1 = "manifests";
1862
+ const clone$2 = (value) => value == null ? value : structuredClone(value);
1863
+ var AssetManifestStore = class {
1864
+ constructor({ indexedDBImpl = globalThis.indexedDB } = {}) {
1865
+ this.indexedDB = indexedDBImpl;
1866
+ this.memory = /* @__PURE__ */ new Map();
1867
+ }
1868
+ async open() {
1869
+ if (!this.indexedDB) return null;
1870
+ return new Promise((resolve, reject) => {
1871
+ const request = this.indexedDB.open(DB_NAME$1, DB_VERSION$1);
1872
+ request.onupgradeneeded = () => {
1873
+ const db = request.result;
1874
+ if (!db.objectStoreNames.contains(STORE_NAME$1)) db.createObjectStore(STORE_NAME$1);
1875
+ };
1876
+ request.onsuccess = () => resolve(request.result);
1877
+ request.onerror = () => reject(request.error);
1878
+ });
1879
+ }
1880
+ async put(manifest) {
1881
+ const value = clone$2(manifest);
1882
+ const db = await this.open();
1883
+ if (!db) {
1884
+ this.memory.set(value.id, value);
1885
+ return value.id;
1886
+ }
1887
+ try {
1888
+ await new Promise((resolve, reject) => {
1889
+ const tx = db.transaction(STORE_NAME$1, "readwrite");
1890
+ tx.objectStore(STORE_NAME$1).put(value, value.id);
1891
+ tx.oncomplete = resolve;
1892
+ tx.onerror = () => reject(tx.error);
1893
+ tx.onabort = () => reject(tx.error);
1894
+ });
1895
+ return value.id;
1896
+ } finally {
1897
+ db.close();
1898
+ }
1899
+ }
1900
+ async list() {
1901
+ const db = await this.open();
1902
+ if (!db) return [...this.memory.values()].map(clone$2);
1903
+ try {
1904
+ return await new Promise((resolve, reject) => {
1905
+ const request = db.transaction(STORE_NAME$1, "readonly").objectStore(STORE_NAME$1).getAll();
1906
+ request.onsuccess = () => resolve((request.result || []).map(clone$2));
1907
+ request.onerror = () => reject(request.error);
1908
+ });
1909
+ } finally {
1910
+ db.close();
1911
+ }
1912
+ }
1913
+ async delete(id) {
1914
+ const db = await this.open();
1915
+ if (!db) return this.memory.delete(id);
1916
+ try {
1917
+ await new Promise((resolve, reject) => {
1918
+ const tx = db.transaction(STORE_NAME$1, "readwrite");
1919
+ tx.objectStore(STORE_NAME$1).delete(id);
1920
+ tx.oncomplete = resolve;
1921
+ tx.onerror = () => reject(tx.error);
1922
+ tx.onabort = () => reject(tx.error);
1923
+ });
1924
+ return true;
1925
+ } finally {
1926
+ db.close();
1927
+ }
1928
+ }
1929
+ };
1930
+ // modules/asset/persistence/LocalAssetLibraryStore.js
1931
+ const DB_NAME = "agentscape-asset-library";
1932
+ const DB_VERSION = 1;
1933
+ const STORE_NAME = "entries";
1934
+ const clone$1 = (value) => value == null ? value : structuredClone(value);
1935
+ var LocalAssetLibraryStore = class {
1936
+ constructor({ indexedDBImpl = globalThis.indexedDB } = {}) {
1937
+ this.indexedDB = indexedDBImpl;
1938
+ this.memory = /* @__PURE__ */ new Map();
1939
+ }
1940
+ async open() {
1941
+ if (!this.indexedDB) return null;
1942
+ return new Promise((resolve, reject) => {
1943
+ const request = this.indexedDB.open(DB_NAME, DB_VERSION);
1944
+ request.onupgradeneeded = () => {
1945
+ const db = request.result;
1946
+ if (!db.objectStoreNames.contains(STORE_NAME)) db.createObjectStore(STORE_NAME);
1947
+ };
1948
+ request.onsuccess = () => resolve(request.result);
1949
+ request.onerror = () => reject(request.error);
1950
+ });
1951
+ }
1952
+ async put(entry) {
1953
+ const value = clone$1(entry);
1954
+ const db = await this.open();
1955
+ if (!db) {
1956
+ this.memory.set(value.assetId, value);
1957
+ return value.assetId;
1958
+ }
1959
+ try {
1960
+ await new Promise((resolve, reject) => {
1961
+ const tx = db.transaction(STORE_NAME, "readwrite");
1962
+ tx.objectStore(STORE_NAME).put(value, value.assetId);
1963
+ tx.oncomplete = resolve;
1964
+ tx.onerror = () => reject(tx.error);
1965
+ tx.onabort = () => reject(tx.error);
1966
+ });
1967
+ return value.assetId;
1968
+ } finally {
1969
+ db.close();
1970
+ }
1971
+ }
1972
+ async get(assetId) {
1973
+ const db = await this.open();
1974
+ if (!db) return clone$1(this.memory.get(assetId) || null);
1975
+ try {
1976
+ return await new Promise((resolve, reject) => {
1977
+ const request = db.transaction(STORE_NAME, "readonly").objectStore(STORE_NAME).get(assetId);
1978
+ request.onsuccess = () => resolve(clone$1(request.result || null));
1979
+ request.onerror = () => reject(request.error);
1980
+ });
1981
+ } finally {
1982
+ db.close();
1983
+ }
1984
+ }
1985
+ async list() {
1986
+ const db = await this.open();
1987
+ if (!db) return [...this.memory.values()].map(clone$1);
1988
+ try {
1989
+ return await new Promise((resolve, reject) => {
1990
+ const request = db.transaction(STORE_NAME, "readonly").objectStore(STORE_NAME).getAll();
1991
+ request.onsuccess = () => resolve((request.result || []).map(clone$1));
1992
+ request.onerror = () => reject(request.error);
1993
+ });
1994
+ } finally {
1995
+ db.close();
1996
+ }
1997
+ }
1998
+ async delete(assetId) {
1999
+ const db = await this.open();
2000
+ if (!db) return this.memory.delete(assetId);
2001
+ try {
2002
+ await new Promise((resolve, reject) => {
2003
+ const tx = db.transaction(STORE_NAME, "readwrite");
2004
+ tx.objectStore(STORE_NAME).delete(assetId);
2005
+ tx.oncomplete = resolve;
2006
+ tx.onerror = () => reject(tx.error);
2007
+ tx.onabort = () => reject(tx.error);
2008
+ });
2009
+ return true;
2010
+ } finally {
2011
+ db.close();
2012
+ }
2013
+ }
2014
+ };
2015
+ // modules/asset/persistence/LocalAssetLibrary.js
2016
+ const clone = (value) => value == null ? value : structuredClone(value);
2017
+ var LocalAssetLibrary = class {
2018
+ constructor({ assetRegistry, compiledStore, store = null, now = () => (/* @__PURE__ */ new Date()).toISOString() } = {}) {
2019
+ this.assetRegistry = assetRegistry;
2020
+ if (!this.assetRegistry?.getManifest || !this.assetRegistry?.has) throw new TypeError("LocalAssetLibrary requires AssetRegistry");
2021
+ if (!compiledStore || typeof compiledStore.has !== "function" && typeof compiledStore.get !== "function") throw new TypeError("LocalAssetLibrary requires CompiledAssetStore");
2022
+ this.compiledStore = compiledStore;
2023
+ this.store = store || new LocalAssetLibraryStore();
2024
+ this.now = now;
2025
+ this.entries = /* @__PURE__ */ new Map();
2026
+ this.hydrated = false;
2027
+ }
2028
+ async hydrate() {
2029
+ if (this.hydrated) return { restored: this.entries.size };
2030
+ const entries = await this.store.list();
2031
+ this.entries.clear();
2032
+ for (const entry of entries) if (entry?.assetId) this.entries.set(entry.assetId, clone(entry));
2033
+ this.hydrated = true;
2034
+ return { restored: this.entries.size };
2035
+ }
2036
+ async approve(assetId, metadata = {}) {
2037
+ const manifest = this.assetRegistry.getManifest(assetId);
2038
+ if (manifest.source?.kind !== "compiled" || !manifest.source?.key) {
2039
+ const error = /* @__PURE__ */ new Error(`Only compiled assets can enter the persistent local library: ${assetId}`);
2040
+ error.code = "ASSET_LIBRARY_COMPILED_REQUIRED";
2041
+ throw error;
2042
+ }
2043
+ if (!(typeof this.compiledStore.has === "function" ? await this.compiledStore.has(manifest.source.key) : Boolean(await this.compiledStore.get(manifest.source.key)))) {
2044
+ const error = /* @__PURE__ */ new Error(`Compiled GLB bytes are missing for asset: ${assetId}`);
2045
+ error.code = "ASSET_LIBRARY_BYTES_MISSING";
2046
+ throw error;
2047
+ }
2048
+ const previous = await this.store.get(assetId);
2049
+ const entry = {
2050
+ assetId,
2051
+ status: "approved",
2052
+ approvedAt: previous?.approvedAt || this.now(),
2053
+ updatedAt: this.now(),
2054
+ sourceKey: manifest.source.key,
2055
+ label: String(metadata.label || manifest.label || assetId),
2056
+ sourceImageArtifactId: metadata.sourceImageArtifactId || previous?.sourceImageArtifactId || null,
2057
+ notes: metadata.notes || previous?.notes || null
2058
+ };
2059
+ await this.store.put(entry);
2060
+ this.entries.set(assetId, clone(entry));
2061
+ this.hydrated = true;
2062
+ return clone(entry);
2063
+ }
2064
+ async get(assetId) {
2065
+ if (!this.hydrated) await this.hydrate();
2066
+ const entry = this.entries.get(assetId) || null;
2067
+ if (!entry || !this.assetRegistry.has(assetId)) return null;
2068
+ return clone(entry);
2069
+ }
2070
+ async isApproved(assetId) {
2071
+ return (await this.get(assetId))?.status === "approved";
2072
+ }
2073
+ async list() {
2074
+ if (!this.hydrated) await this.hydrate();
2075
+ return this.listSync();
2076
+ }
2077
+ listSync() {
2078
+ return [...this.entries.values()].filter((entry) => entry?.status === "approved" && this.assetRegistry.has(entry.assetId)).sort((a, b) => String(b.updatedAt || "").localeCompare(String(a.updatedAt || ""))).map(clone);
2079
+ }
2080
+ async remove(assetId) {
2081
+ const removed = await this.store.delete(assetId);
2082
+ this.entries.delete(assetId);
2083
+ return removed;
2084
+ }
2085
+ };
2086
+ // modules/asset/AssetModule.js
2087
+ var AssetModule_exports = /* @__PURE__ */ __exportAll({
2088
+ createAssetModule: () => createAssetModule,
2089
+ createRecipeMaterialSample: () => createRecipeMaterialSample,
2090
+ verifyAndUpdateAssetArticulation: () => verifyAndUpdateAssetArticulation
2091
+ });
2092
+ /** Detached visual sample, owned and disposed by the caller. No registry or world writes. */
2093
+ async function createRecipeMaterialSample(material) {
2094
+ const { bytes } = await compileRecipeGeometry({
2095
+ schema: "agentscape.asset-recipe",
2096
+ schemaVersion: 1,
2097
+ id: "preview/material",
2098
+ parts: [{
2099
+ id: "sample",
2100
+ geometry: {
2101
+ type: "sphere",
2102
+ radius: 1
2103
+ },
2104
+ material
2105
+ }]
2106
+ });
2107
+ const loader = new GltfAssetLoader();
2108
+ try {
2109
+ return await loader.loadBytes(bytes);
2110
+ } finally {
2111
+ loader.dispose();
2112
+ }
2113
+ }
2114
+ async function verifyAndUpdateAssetArticulation(assets, assetId, options) {
2115
+ const report = await assets.verifyArticulation(assetId, options);
2116
+ const manifest = assets.getManifest(assetId);
2117
+ manifest.verification = {
2118
+ ...manifest.verification || {},
2119
+ articulation: report
2120
+ };
2121
+ const quality = manifest.compiler?.quality;
2122
+ if (quality) {
2123
+ quality.advisory = (quality.advisory || []).filter((item) => !["ARTICULATION_UNVERIFIED", "ARTICULATION_VERIFICATION_FAILED"].includes(item.code));
2124
+ if (!report.ok) quality.advisory.push({
2125
+ code: "ARTICULATION_VERIFICATION_FAILED",
2126
+ message: "运行时运动验证失败"
2127
+ });
2128
+ quality.status = quality.hard?.length ? "rejected" : quality.advisory.length ? "provisional" : "ready";
2129
+ }
2130
+ await assets.registerManifest(manifest, { replace: true });
2131
+ const admission = assetAdmission(manifest);
2132
+ return {
2133
+ ...report,
2134
+ readiness: admission.status,
2135
+ admission
2136
+ };
2137
+ }
2138
+ function createAssetModule({ manifests, volatile = false, compiledStore = null, manifestStore = void 0, libraryStore = void 0, gltfLoader = void 0, now = () => Date.now() } = {}) {
2139
+ const store = compiledStore || new CompiledAssetStore({ indexedDBImpl: volatile ? null : globalThis.indexedDB });
2140
+ const durableManifests = manifestStore === void 0 ? globalThis.indexedDB ? new AssetManifestStore() : null : manifestStore;
2141
+ const registry = new AssetRegistry({ manifests });
2142
+ const loader = new AssetLoader({
2143
+ registry,
2144
+ compiledStore: store,
2145
+ ...gltfLoader ? { gltfLoader } : {}
2146
+ });
2147
+ const catalog = new AssetCatalog({ registry });
2148
+ const library = new LocalAssetLibrary({
2149
+ assetRegistry: registry,
2150
+ compiledStore: store,
2151
+ store: libraryStore === void 0 ? new LocalAssetLibraryStore() : libraryStore || new LocalAssetLibraryStore({ indexedDBImpl: null }),
2152
+ now: () => new Date(now()).toISOString()
2153
+ });
2154
+ let producer = null;
2155
+ let hydrated = false;
2156
+ let hydrationPromise;
2157
+ let configuredCompilerProvider = null;
2158
+ let configuredCompiler = null;
2159
+ let configuredCompilerGetter = null;
2160
+ let articulationVerifier = null;
2161
+ const persistManifest = async (manifest) => {
2162
+ if (manifest?.source?.kind !== "compiled" || !durableManifests?.put) return false;
2163
+ await durableManifests.put(manifest);
2164
+ return true;
2165
+ };
2166
+ const configureCompiler = ({ provider = null, endpoint = "", events = null, version = "dev" } = {}) => {
2167
+ configuredCompilerProvider = provider || new HttpCompilerProvider({ endpoint: String(endpoint || "").trim() });
2168
+ configuredCompiler = null;
2169
+ configuredCompilerGetter = async () => {
2170
+ if (!configuredCompiler) {
2171
+ const { AssetCompiler } = await import("./AssetCompiler-BLj09iu1.js");
2172
+ configuredCompiler = new AssetCompiler({
2173
+ store,
2174
+ provider: configuredCompilerProvider,
2175
+ events,
2176
+ version
2177
+ });
2178
+ }
2179
+ return configuredCompiler;
2180
+ };
2181
+ return configuredCompilerGetter;
2182
+ };
2183
+ const module = {
2184
+ async readAssetBytes(id) {
2185
+ const manifest = registry.getManifest(id);
2186
+ if (manifest.source.kind === "compiled") {
2187
+ const entry = await store.get(manifest.source.key);
2188
+ if (!entry?.bytes) throw new Error("RESOURCE_UNAVAILABLE");
2189
+ return entry.bytes.slice();
2190
+ }
2191
+ if (manifest.source.kind !== "glb") throw new Error("RESOURCE_UNAVAILABLE");
2192
+ const { AssetCompiler } = await import("./AssetCompiler-BLj09iu1.js");
2193
+ return new AssetCompiler({ store }).fetchBytes(manifest.source.url);
2194
+ },
2195
+ async installPreparedAssets(entries, operation) {
2196
+ const added = [];
2197
+ try {
2198
+ const durableIds = new Set((await durableManifests?.list?.() || []).map((manifest) => manifest.id));
2199
+ for (const entry of entries) if (!registry.has(entry.manifest.id) && durableIds.has(entry.manifest.id)) throw new Error("ASSET_ID_CONFLICT");
2200
+ for (const entry of entries) if (registry.has(entry.manifest.id)) {
2201
+ const existing = registry.getManifest(entry.manifest.id);
2202
+ const definition = Object.fromEntries(Object.keys(entry.expectedDefinition).map((key) => [key, existing[key]]));
2203
+ if (canonicalAssetJson(definition) !== canonicalAssetJson(entry.expectedDefinition) || await assetDigest(await module.readAssetBytes(existing.id)) !== entry.expectedSourceHash) throw new Error("ASSET_ID_CONFLICT");
2204
+ }
2205
+ for (const entry of entries) {
2206
+ if (registry.has(entry.manifest.id)) continue;
2207
+ const key = entry.manifest.source.key, previous = await store.get(key);
2208
+ if (previous && await assetDigest(previous.bytes) !== await assetDigest(entry.bytes)) throw new Error("ASSET_ID_CONFLICT");
2209
+ added.push({
2210
+ id: entry.manifest.id,
2211
+ key,
2212
+ bytesAdded: !previous
2213
+ });
2214
+ await store.put(key, entry.bytes, { manifestId: entry.manifest.id });
2215
+ await module.registerManifest(entry.manifest);
2216
+ }
2217
+ return await operation();
2218
+ } catch (error) {
2219
+ const failures = [];
2220
+ for (const entry of added.reverse()) try {
2221
+ registry.removeManifest(entry.id);
2222
+ await durableManifests?.delete?.(entry.id);
2223
+ if (entry.bytesAdded) await store.delete(entry.key);
2224
+ } catch (failure) {
2225
+ failures.push(failure);
2226
+ }
2227
+ if (failures.length) throw Object.assign(new AggregateError([error, ...failures], "Project resource rollback failed"), { code: "PROJECT_ROLLBACK_FAILED" });
2228
+ throw error;
2229
+ }
2230
+ },
2231
+ async importMechanicalDraft(input) {
2232
+ const draft = mechanicalDraftSchema.parse(input);
2233
+ const id = "asset_" + await assetDigest(new TextEncoder().encode(canonicalAssetJson({
2234
+ draft,
2235
+ compiler: "mechanical-draft-v1"
2236
+ })));
2237
+ if (registry.has(id)) {
2238
+ const manifest = registry.getManifest(id);
2239
+ return {
2240
+ manifest,
2241
+ admission: assetAdmission(manifest)
2242
+ };
2243
+ }
2244
+ const { compileRecipeGeometry } = await import("./AssetRecipe-g8dZBhgJ.js").then((n) => n.t);
2245
+ const { bytes } = await compileRecipeGeometry(mechanicalDraftToAssetRecipe(draft));
2246
+ return module.importPackageAsset({
2247
+ id,
2248
+ bytes,
2249
+ definition: mechanicalDraftToManifest(draft)
2250
+ });
2251
+ },
2252
+ async importPackageAsset({ id, bytes, definition }) {
2253
+ assertEmbeddedGLB(bytes);
2254
+ if (registry.has(id)) throw Object.assign(/* @__PURE__ */ new Error("Asset id already exists"), { code: "ASSET_ID_CONFLICT" });
2255
+ const { AssetCompiler } = await import("./AssetCompiler-BLj09iu1.js");
2256
+ const compiler = new AssetCompiler({
2257
+ store,
2258
+ version: "v2-input-1"
2259
+ });
2260
+ const output = definition.capabilityLevel === "visual" ? await compiler.compileVisual({
2261
+ bytes,
2262
+ assetId: id,
2263
+ label: definition.label,
2264
+ persist: false
2265
+ }) : await compiler.compile({
2266
+ bytes,
2267
+ assetId: id,
2268
+ sourceName: "package.glb",
2269
+ definition,
2270
+ authoringIntent: { usage: "interactive" },
2271
+ persist: false
2272
+ });
2273
+ output.manifest.capabilityLevel = definition.capabilityLevel;
2274
+ if (Object.values(output.manifest.parts || {}).some((part) => part.joint && part.joint.type !== "fixed")) {
2275
+ if (!articulationVerifier) throw Object.assign(/* @__PURE__ */ new Error("Runtime verification unavailable"), { code: "RUNTIME_VERIFICATION_UNAVAILABLE" });
2276
+ const report = await articulationVerifier.verify(id, {
2277
+ manifest: output.manifest,
2278
+ requireRegistration: true,
2279
+ requireSettled: true,
2280
+ instantiate: async () => ({ object: await loader.gltfLoader.loadBytes(output.optimizedBytes) })
2281
+ });
2282
+ if (!report.ok) throw Object.assign(/* @__PURE__ */ new Error("Package articulation failed validation"), {
2283
+ code: "ASSET_PHYSICS_VERIFICATION_FAILED",
2284
+ details: report
2285
+ });
2286
+ output.manifest.verification = { articulation: report };
2287
+ output.manifest.compiler.quality.advisory = output.manifest.compiler.quality.advisory.filter((item) => item.code !== "ARTICULATION_UNVERIFIED");
2288
+ output.manifest.compiler.quality.status = output.manifest.compiler.quality.advisory.length ? "provisional" : "ready";
2289
+ }
2290
+ if (await store.get(id)) throw Object.assign(/* @__PURE__ */ new Error("Compiled asset id already exists"), { code: "ASSET_ID_CONFLICT" });
2291
+ try {
2292
+ await store.put(id, output.optimizedBytes, {
2293
+ manifestId: id,
2294
+ quality: output.manifest.compiler.quality.status
2295
+ });
2296
+ await module.registerManifest(output.manifest);
2297
+ } catch (error) {
2298
+ registry.removeManifest(id);
2299
+ try {
2300
+ await durableManifests?.delete?.(id);
2301
+ await store.delete(id);
2302
+ } catch (rollbackError) {
2303
+ throw Object.assign(new AggregateError([error, rollbackError], "Package publish rollback failed"), { code: "ASSET_PUBLISH_ROLLBACK_FAILED" });
2304
+ }
2305
+ throw error;
2306
+ }
2307
+ return {
2308
+ manifest: output.manifest,
2309
+ admission: assetAdmission(output.manifest)
2310
+ };
2311
+ },
2312
+ async prepareInteraction({ bytes, urdfBytes, name = "import.glb" }) {
2313
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength > 33554432) throw Object.assign(/* @__PURE__ */ new Error("Invalid GLB input"), { code: "ASSET_INPUT_INVALID" });
2314
+ bytes = bytes.slice();
2315
+ assertEmbeddedGLB(bytes);
2316
+ let partProposal = null, urdfHash = null;
2317
+ if (urdfBytes) {
2318
+ if (!(urdfBytes instanceof Uint8Array) || !urdfBytes.length || urdfBytes.length > 1048576) throw Object.assign(/* @__PURE__ */ new Error("Invalid URDF input"), { code: "ASSET_INPUT_INVALID" });
2319
+ urdfBytes = urdfBytes.slice();
2320
+ urdfHash = await assetDigest(urdfBytes);
2321
+ if (!configuredCompilerProvider?.runUrdfProposal || configuredCompilerProvider.isConfigured?.() === false) throw Object.assign(/* @__PURE__ */ new Error("URDF requires the configured compiler provider"), { code: "URDF_PROVIDER_UNAVAILABLE" });
2322
+ partProposal = (await configuredCompilerProvider.runUrdfProposal(urdfBytes)).partProposal;
2323
+ if (partProposal?.version !== 1 || !Array.isArray(partProposal.parts) || partProposal.parts.length > 32) throw Object.assign(/* @__PURE__ */ new Error("Invalid URDF proposal"), { code: "CAPABILITY_PROPOSAL_INVALID" });
2324
+ }
2325
+ const { AssetCompiler } = await import("./AssetCompiler-BLj09iu1.js");
2326
+ return new AssetCompiler({
2327
+ store,
2328
+ version: "interaction-v1"
2329
+ }).proposeInteraction({
2330
+ bytes,
2331
+ sourceName: name,
2332
+ partProposal,
2333
+ urdfHash
2334
+ });
2335
+ },
2336
+ async screenInteraction({ bytes, urdfBytes, name = "import.glb", proposalId, hypothesisIds } = {}) {
2337
+ assertEmbeddedGLB(bytes);
2338
+ if (!/^[a-f0-9]{64}$/.test(String(proposalId || ""))) throw Object.assign(/* @__PURE__ */ new Error("Invalid proposal ID"), { code: "PROPOSAL_MISMATCH" });
2339
+ if (!articulationVerifier) throw Object.assign(/* @__PURE__ */ new Error("Runtime verification unavailable"), { code: "RUNTIME_VERIFICATION_UNAVAILABLE" });
2340
+ const proposal = await module.prepareInteraction({
2341
+ bytes,
2342
+ urdfBytes,
2343
+ name
2344
+ });
2345
+ if (proposal.proposalId !== proposalId) throw Object.assign(/* @__PURE__ */ new Error("Review does not match the imported source"), { code: "PROPOSAL_MISMATCH" });
2346
+ const hypotheses = proposal.kinematics?.hypotheses || [];
2347
+ const ids = hypothesisIds || hypotheses.slice(0, 4).map((item) => item.id);
2348
+ if (!Array.isArray(ids) || ids.length > 4 || ids.some((id) => typeof id !== "string")) throw Object.assign(/* @__PURE__ */ new Error("Invalid hypothesis selection"), { code: "HYPOTHESIS_SELECTION_INVALID" });
2349
+ if (!ids.length) return {
2350
+ schema: "agentscape.kinematic-screen",
2351
+ schemaVersion: 1,
2352
+ proposalId,
2353
+ sourceHash: proposal.sourceHash,
2354
+ results: [],
2355
+ admission: "not-granted",
2356
+ interpretation: "simulation-only; no semantic authorization or real-world mechanism proof"
2357
+ };
2358
+ const { screenKinematicHypotheses } = await import("./KinematicHypothesisScreen-C3TKiuYR.js");
2359
+ return screenKinematicHypotheses({
2360
+ bytes,
2361
+ proposal,
2362
+ ids,
2363
+ loader: loader.gltfLoader,
2364
+ verifier: articulationVerifier
2365
+ });
2366
+ },
2367
+ async importReviewedGLB({ bytes, urdfBytes, name = "import.glb", review, level = "physical" }) {
2368
+ review = interactionReviewSchema.parse(review);
2369
+ bytes = bytes.slice();
2370
+ urdfBytes = urdfBytes?.slice();
2371
+ const proposal = await module.prepareInteraction({
2372
+ bytes,
2373
+ urdfBytes,
2374
+ name
2375
+ });
2376
+ if (review.proposalId !== proposal.proposalId) throw Object.assign(/* @__PURE__ */ new Error("Review does not match the imported source"), { code: "PROPOSAL_MISMATCH" });
2377
+ const hash = await assetDigest(new TextEncoder().encode(canonicalAssetJson({
2378
+ source: proposal.sourceHash,
2379
+ review,
2380
+ compiler: "interaction-v1"
2381
+ }))), assetId = `asset_${hash}`;
2382
+ if (registry.has(assetId)) return {
2383
+ asset: `asset://sha256/${hash}`,
2384
+ manifest: registry.getManifest(assetId),
2385
+ admission: assetAdmission(registry.getManifest(assetId))
2386
+ };
2387
+ if (!articulationVerifier) throw Object.assign(/* @__PURE__ */ new Error("Runtime verification unavailable"), { code: "RUNTIME_VERIFICATION_UNAVAILABLE" });
2388
+ const { AssetCompiler } = await import("./AssetCompiler-BLj09iu1.js");
2389
+ const output = await new AssetCompiler({
2390
+ store,
2391
+ version: "interaction-v1"
2392
+ }).compile({
2393
+ bytes,
2394
+ assetId,
2395
+ sourceName: name,
2396
+ authoringIntent: { usage: "interactive" },
2397
+ interactionReview: review,
2398
+ partProposal: review.parts.length ? {
2399
+ version: 1,
2400
+ source: "reviewed-capability-proposal",
2401
+ parts: review.parts.map((part) => ({
2402
+ ...part,
2403
+ actions: [],
2404
+ targets: {}
2405
+ }))
2406
+ } : null
2407
+ });
2408
+ try {
2409
+ if (Object.keys(output.manifest.parts || {}).length !== review.parts.length) throw Object.assign(/* @__PURE__ */ new Error("Part review did not compile"), { code: "CAPABILITY_REVIEW_INVALID" });
2410
+ const report = await articulationVerifier.verify(assetId, {
2411
+ manifest: output.manifest,
2412
+ requireRegistration: true,
2413
+ verifyRigidBody: true,
2414
+ requireSettled: true,
2415
+ instantiate: async () => ({ object: await loader.loadCompiled(output.manifest.source) })
2416
+ });
2417
+ if (!report.ok || !report.physicsRegistered || report.tested !== review.parts.length || report.parts.some((part) => !part.actions?.some((action) => action.moved))) throw Object.assign(/* @__PURE__ */ new Error("Imported physics failed validation"), {
2418
+ code: "ASSET_PHYSICS_VERIFICATION_FAILED",
2419
+ details: report
2420
+ });
2421
+ output.manifest.verification = { articulation: report };
2422
+ output.manifest.capabilityLevel = level;
2423
+ output.manifest.contentHash = hash;
2424
+ output.manifest.compiler.quality.advisory = output.manifest.compiler.quality.advisory.filter((item) => item.code !== "ARTICULATION_UNVERIFIED");
2425
+ output.manifest.compiler.quality.status = output.manifest.compiler.quality.advisory.length ? "provisional" : "ready";
2426
+ output.manifest.provenance.interactionSource = {
2427
+ sourceHash: proposal.sourceHash,
2428
+ urdfHash: proposal.urdfHash,
2429
+ proposalId: proposal.proposalId
2430
+ };
2431
+ await module.registerManifest(output.manifest);
2432
+ return {
2433
+ asset: `asset://sha256/${hash}`,
2434
+ manifest: output.manifest,
2435
+ admission: assetAdmission(output.manifest)
2436
+ };
2437
+ } catch (error) {
2438
+ await store.delete?.(assetId);
2439
+ throw error;
2440
+ }
2441
+ },
2442
+ async importGLB({ bytes, level = "visual", label = "Imported model", review = null, urdfBytes, name }) {
2443
+ if (review) return module.importReviewedGLB({
2444
+ bytes,
2445
+ level,
2446
+ review,
2447
+ urdfBytes,
2448
+ name
2449
+ });
2450
+ if (level !== "visual") throw Object.assign(/* @__PURE__ */ new Error("GLB physical import requires an explicit compiled definition"), { code: "CAPABILITY_UNAVAILABLE" });
2451
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength > 33554432) throw Object.assign(/* @__PURE__ */ new Error("Invalid GLB input"), { code: "ASSET_INPUT_INVALID" });
2452
+ bytes = bytes.slice();
2453
+ assertEmbeddedGLB(bytes);
2454
+ const hash = await assetDigest(bytes), assetId = `asset_${hash}`;
2455
+ if (registry.has(assetId)) return {
2456
+ asset: `asset://sha256/${hash}`,
2457
+ manifest: registry.getManifest(assetId),
2458
+ admission: assetAdmission(registry.getManifest(assetId))
2459
+ };
2460
+ const { AssetCompiler } = await import("./AssetCompiler-BLj09iu1.js");
2461
+ const output = await new AssetCompiler({
2462
+ store,
2463
+ version: "v2-input-1"
2464
+ }).compileVisual({
2465
+ bytes,
2466
+ assetId,
2467
+ label
2468
+ });
2469
+ output.manifest.contentHash = hash;
2470
+ await module.registerManifest(output.manifest);
2471
+ return {
2472
+ asset: `asset://sha256/${hash}`,
2473
+ manifest: output.manifest,
2474
+ admission: assetAdmission(output.manifest)
2475
+ };
2476
+ },
2477
+ async importRecipe(input) {
2478
+ const recipe = recipeSchema.parse(input);
2479
+ const hash = await assetDigest(new TextEncoder().encode(canonicalAssetJson({
2480
+ recipe,
2481
+ compiler: "v2-input-1"
2482
+ }))), assetId = `asset_${hash}`;
2483
+ if (registry.has(assetId)) return {
2484
+ asset: `asset://sha256/${hash}`,
2485
+ manifest: registry.getManifest(assetId),
2486
+ admission: assetAdmission(registry.getManifest(assetId))
2487
+ };
2488
+ const { compileRecipeGeometry } = await import("./AssetRecipe-g8dZBhgJ.js").then((n) => n.t);
2489
+ const { AssetCompiler } = await import("./AssetCompiler-BLj09iu1.js");
2490
+ const { bytes } = await compileRecipeGeometry(recipe);
2491
+ const compiler = new AssetCompiler({
2492
+ store,
2493
+ version: "v2-input-1"
2494
+ });
2495
+ const output = recipe.capabilities.level === "visual" ? await compiler.compileVisual({
2496
+ bytes,
2497
+ assetId,
2498
+ label: recipe.id
2499
+ }) : await compiler.compile({
2500
+ bytes,
2501
+ assetId,
2502
+ sourceName: "recipe.glb",
2503
+ label: recipe.id,
2504
+ authoringIntent: { usage: recipe.capabilities.physics.body === "dynamic" ? "movable" : "static" },
2505
+ definition: {
2506
+ type: "prop",
2507
+ label: recipe.id,
2508
+ actions: recipe.capabilities.actions,
2509
+ physics: recipe.capabilities.physics,
2510
+ surfaces: recipe.capabilities.surfaces
2511
+ }
2512
+ });
2513
+ output.manifest.capabilityLevel = recipe.capabilities.level;
2514
+ output.manifest.contentHash = hash;
2515
+ output.manifest.provenance = {
2516
+ ...output.manifest.provenance,
2517
+ recipe
2518
+ };
2519
+ const admission = assetAdmission(output.manifest);
2520
+ if (admission.status === "rejected") throw Object.assign(/* @__PURE__ */ new Error("Recipe rejected"), { code: "ASSET_REJECTED" });
2521
+ await module.registerManifest(output.manifest);
2522
+ return {
2523
+ asset: `asset://sha256/${hash}`,
2524
+ manifest: output.manifest,
2525
+ admission
2526
+ };
2527
+ },
2528
+ registry,
2529
+ loader,
2530
+ catalog,
2531
+ compiledStore: store,
2532
+ manifestStore: durableManifests,
2533
+ library,
2534
+ getManifest(assetId) {
2535
+ return registry.getManifest(assetId);
2536
+ },
2537
+ hasAsset(assetId) {
2538
+ return registry.has(assetId);
2539
+ },
2540
+ assertCompatibleManifest(manifest) {
2541
+ return registry.assertCompatibleManifest(manifest);
2542
+ },
2543
+ configureRenderer(renderer) {
2544
+ return loader.configureRenderer?.(renderer);
2545
+ },
2546
+ instantiate(assetId, options) {
2547
+ return loader.instantiate(assetId, options);
2548
+ },
2549
+ configureVerification({ articulationVerifier: verifier = null } = {}) {
2550
+ if (verifier != null && typeof verifier.verify !== "function") throw new TypeError("Asset articulation verifier must provide verify(assetId)");
2551
+ articulationVerifier = verifier;
2552
+ return module;
2553
+ },
2554
+ async verifyArticulation(assetId, options) {
2555
+ if (!articulationVerifier) {
2556
+ const error = /* @__PURE__ */ new Error("Asset articulation verification is not configured");
2557
+ error.code = "ASSET_ARTICULATION_VERIFIER_UNAVAILABLE";
2558
+ throw error;
2559
+ }
2560
+ return options == null ? articulationVerifier.verify(assetId) : articulationVerifier.verify(assetId, options);
2561
+ },
2562
+ async verifyAndUpdateArticulation(assetId, options) {
2563
+ return verifyAndUpdateAssetArticulation(module, assetId, options);
2564
+ },
2565
+ async hydrate() {
2566
+ if (hydrated) return {
2567
+ manifests: registry.size,
2568
+ restored: false
2569
+ };
2570
+ if (!hydrationPromise) hydrationPromise = (async () => {
2571
+ if (!durableManifests?.list) {
2572
+ await library.hydrate();
2573
+ hydrated = true;
2574
+ return {
2575
+ manifests: registry.size,
2576
+ restored: false
2577
+ };
2578
+ }
2579
+ const persisted = await durableManifests.list();
2580
+ let restored = 0;
2581
+ for (const manifest of persisted) if (registry.registerManifest(manifest)) restored += 1;
2582
+ await library.hydrate();
2583
+ hydrated = true;
2584
+ return {
2585
+ manifests: persisted.length,
2586
+ restored
2587
+ };
2588
+ })().finally(() => {
2589
+ hydrationPromise = void 0;
2590
+ });
2591
+ return hydrationPromise;
2592
+ },
2593
+ async registerManifest(manifest, options = {}) {
2594
+ const changed = registry.registerManifest(manifest, options);
2595
+ await persistManifest(registry.getManifest(manifest.id));
2596
+ return changed;
2597
+ },
2598
+ async approveAsset(assetId, metadata = {}) {
2599
+ return library.approve(assetId, metadata);
2600
+ },
2601
+ async listApprovedAssets() {
2602
+ return library.list();
2603
+ },
2604
+ configureProduction({ artifacts, getAssetCompiler = null, compilerProvider = null, compilerEndpoint = "", events = null, version = "dev", idFactory = void 0 } = {}) {
2605
+ if (!artifacts?.registry || !artifacts?.byteStore) throw new AssetProductionError("ASSET_PRODUCTION_INVALID", "Asset production requires an ArtifactModule boundary");
2606
+ const compilerGetter = getAssetCompiler || configureCompiler({
2607
+ provider: compilerProvider,
2608
+ endpoint: compilerEndpoint,
2609
+ events,
2610
+ version
2611
+ });
2612
+ producer = createAssetProducer({
2613
+ artifactRegistry: artifacts.registry,
2614
+ byteStore: artifacts.byteStore,
2615
+ getAssetCompiler: compilerGetter,
2616
+ assetRegistry: registry,
2617
+ onManifestRegistered: persistManifest,
2618
+ events,
2619
+ now,
2620
+ ...idFactory ? { idFactory } : {}
2621
+ });
2622
+ return module;
2623
+ },
2624
+ setCompilerEndpoint(endpoint = "") {
2625
+ configuredCompilerProvider?.setEndpoint?.(String(endpoint || "").trim());
2626
+ return module;
2627
+ },
2628
+ async produceAsset(request = {}) {
2629
+ if (!producer) throw new AssetProductionError("ASSET_PRODUCTION_NOT_CONFIGURED", "Asset production requires composition-time compiler configuration");
2630
+ return producer(request);
2631
+ }
2632
+ };
2633
+ return module;
2634
+ }
2635
+ export { artifactImmutableSignature as a, normalizeArtifactLocation as c, ArtifactContractError as i, requireSafeArtifactId as l, createAssetModule as n, normalizeArtifactDescriptor as o, ARTIFACT_LEASE_HOLDER_KINDS as r, normalizeArtifactHash as s, AssetModule_exports as t, mechanicalDraftSchema as u };
2636
+
2637
+ //# sourceMappingURL=AssetModule-DME-XaFS.js.map