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,2207 @@
1
+ import { t as assetAdmission } from "./admission-CVEvsrdz.js";
2
+ import { t as physicsManifestForUniformScale } from "./ObjectTransform-BlQUNK7c.js";
3
+ import { t as inferCarryCapability } from "./CarryCapability-CXwHU5ay.js";
4
+ import * as THREE from "three";
5
+ import { ConvexGeometry } from "three/addons/geometries/ConvexGeometry.js";
6
+ // modules/world/runtime/interaction/ManipulationActions.js
7
+ const rigidBodyActions = Object.freeze([
8
+ "push",
9
+ "drag",
10
+ "rotate"
11
+ ]);
12
+ /** The same parameter contract for native and managed rigid bodies. */
13
+ function manipulationParameters(action) {
14
+ return action === "rotate" ? {
15
+ axis: {
16
+ type: "array",
17
+ length: 3,
18
+ nonzero: true,
19
+ required: true
20
+ },
21
+ angle: {
22
+ type: "number",
23
+ minimum: -Math.PI,
24
+ maximum: Math.PI,
25
+ unit: "radian",
26
+ required: true
27
+ },
28
+ maxTorque: {
29
+ type: "number",
30
+ minimum: 0,
31
+ exclusiveMinimum: true,
32
+ maximum: 1e3,
33
+ default: 100,
34
+ unit: "newton-meter"
35
+ }
36
+ } : {
37
+ direction: {
38
+ type: "array",
39
+ length: 3,
40
+ nonzero: true,
41
+ horizontal: true,
42
+ required: true
43
+ },
44
+ distance: {
45
+ type: "number",
46
+ minimum: 0,
47
+ exclusiveMinimum: true,
48
+ maximum: 5,
49
+ unit: "meter",
50
+ required: true
51
+ },
52
+ maxForce: {
53
+ type: "number",
54
+ minimum: 0,
55
+ exclusiveMinimum: true,
56
+ maximum: 1e3,
57
+ default: 100,
58
+ unit: "newton"
59
+ }
60
+ };
61
+ }
62
+ // modules/world/runtime/interaction/NativePhysicalTarget.js
63
+ /** The registry owns identity/state; the live physics entry owns collider data. */
64
+ function nativePhysicalTarget(entities, physics, id) {
65
+ const entity = entities?.get?.(id), entry = physics?.entries?.get(id);
66
+ if (entity?.source !== "native" || !entry || entry.root !== entity.object || !entity.capabilities.includes("physics")) return null;
67
+ if (entry.nativeArticulation) {
68
+ const parts = entity.manifest?.parts || {};
69
+ if (entry.parts.size !== Object.keys(parts).length) return null;
70
+ for (const [name, part] of entry.parts) {
71
+ const parent = part.parentName === "$root" ? entity.object : entry.parts.get(part.parentName)?.node;
72
+ if (!parent || part.node.parent !== parent || part.node.name !== parts[name]?.node || part.node.uuid !== entity.metadata.articulationNodeUuids?.[name]) return null;
73
+ }
74
+ }
75
+ for (let node = entity.object; node; node = node.parent) if (node.uuid === entity.metadata.hostSceneUuid) return entity;
76
+ return null;
77
+ }
78
+ function nativeCarryRecord(entities, physics, id) {
79
+ const entity = nativePhysicalTarget(entities, physics, id);
80
+ if (!entity) return null;
81
+ const spec = physics.entries.get(id).rootSpec;
82
+ return {
83
+ id,
84
+ object: entity.object,
85
+ state: entity.state,
86
+ source: "native",
87
+ manifest: {
88
+ physics: spec,
89
+ surfaces: entity.metadata.surfaces || [],
90
+ parts: entity.manifest.parts || {},
91
+ actions: []
92
+ },
93
+ physicsScale: 1
94
+ };
95
+ }
96
+ /** Normal is oriented from the source collider toward the other collider.
97
+ * Require a downward contact with the named support, not a ceiling or side.
98
+ */
99
+ function nativeSupportContacts(physics, subjectId, targetId) {
100
+ return (physics.articulationContacts(subjectId, "$root") || []).filter((contact) => contact.external && contact.target?.objectId === targetId && contact.activeContactCount > 0 && contact.normal?.[1] < -.7 && Number.isFinite(contact.minDistance) && contact.minDistance >= -.03);
101
+ }
102
+ // modules/world/runtime/semantic/NativePhysicsState.js
103
+ /** Read the same live rigid body that drives the host object, never a semantic guess. */
104
+ function inspectNativePhysics(runtime, id) {
105
+ const entity = nativePhysicalTarget(runtime?.entities, runtime?.physics, id);
106
+ if (!entity) return null;
107
+ const body = runtime.physics?.manipulationBody?.(id);
108
+ const registered = Boolean(body?.registered && body.colliderCount > 0);
109
+ const position = registered ? runtime.physics.getPosition(id) : null;
110
+ const rotation = registered ? runtime.physics.getRotation(id) : null;
111
+ const motion = registered ? runtime.physics.getMotion(id) : null;
112
+ const state = {
113
+ registered,
114
+ manipulable: entity.metadata.manipulable === true,
115
+ carryable: entity.metadata.carryable === true,
116
+ held: !!entity.state?.heldBy,
117
+ heldById: entity.state?.heldBy?.id ?? null,
118
+ body: body?.body ?? null,
119
+ mass: body?.mass ?? null,
120
+ colliderCount: body?.colliderCount ?? 0,
121
+ ...position ? {
122
+ positionX: position[0],
123
+ positionY: position[1],
124
+ positionZ: position[2]
125
+ } : {},
126
+ ...motion ? {
127
+ linearSpeed: motion.linearSpeed,
128
+ angularSpeed: motion.angularSpeed,
129
+ sleeping: motion.sleeping
130
+ } : {}
131
+ };
132
+ const joints = Object.entries(entity.manifest?.parts || {}).map(([partName, part]) => {
133
+ const live = runtime.physics.getArticulationState(id, partName);
134
+ const pending = runtime.interactions?.articulationTasks?.get(id + ":" + partName);
135
+ const motorTarget = runtime.physics.entries.get(id)?.parts.get(partName)?.motorTarget ?? null;
136
+ return {
137
+ partName,
138
+ node: part.node,
139
+ parent: part.parent,
140
+ type: part.joint.type,
141
+ axis: [...part.joint.axis],
142
+ limits: [...part.joint.limits],
143
+ coordinate: live?.coordinate ?? null,
144
+ motorTarget,
145
+ moving: !!pending
146
+ };
147
+ });
148
+ for (const joint of joints) state["joint:" + joint.partName] = joint.coordinate;
149
+ return {
150
+ source: "native-physics",
151
+ colliderSource: entity.metadata.colliderSource || "declared",
152
+ joints,
153
+ transformAuthority: entity.transformAuthority,
154
+ state,
155
+ position,
156
+ rotation,
157
+ surfaces: structuredClone(entity.metadata.surfaces || []),
158
+ physicsVerified: false
159
+ };
160
+ }
161
+ /** Discovery reads live availability; registration alone is not successful execution. */
162
+ function nativeManipulationActions(runtime, id, actor = null) {
163
+ const record = nativeCarryRecord(runtime.entities, runtime.physics, id);
164
+ if (!record) return [];
165
+ const manipulable = Boolean(runtime.interactions?.nativeManipulationTarget?.(id));
166
+ let access = {
167
+ available: null,
168
+ reason: "ACTOR_REQUIRED_FOR_REACH_CHECK"
169
+ };
170
+ if (actor) {
171
+ if (!runtime.store.has(actor)) access = {
172
+ available: false,
173
+ reason: "ACTOR_NOT_FOUND"
174
+ };
175
+ else if (runtime.store.get(actor).manifest.type !== "agent") access = {
176
+ available: false,
177
+ reason: "ACTOR_NOT_AGENT"
178
+ };
179
+ else try {
180
+ const reach = runtime.interactions.interactionStatus(actor, id);
181
+ access = {
182
+ available: reach.interactable,
183
+ reason: reach.interactable ? null : reach.inRange ? "OCCLUDED" : "OUT_OF_REACH"
184
+ };
185
+ } catch (error) {
186
+ access = {
187
+ available: false,
188
+ reason: error.details?.reason || error.code || "CAPABILITY_CHECK_FAILED"
189
+ };
190
+ }
191
+ }
192
+ const reachAccess = access;
193
+ if (actor && runtime.interactions.heldByAgent(actor)) access = {
194
+ available: false,
195
+ reason: "HANDS_FULL"
196
+ };
197
+ const actions = manipulable ? rigidBodyActions.map((action) => {
198
+ const capability = runtime.interactions.manipulationCapability(id, action);
199
+ const live = capability.available ? access : capability;
200
+ return {
201
+ action,
202
+ source: "native-physics",
203
+ execution: "interaction",
204
+ parameters: manipulationParameters(action),
205
+ ...live,
206
+ canApproach: ["OUT_OF_REACH", "OCCLUDED"].includes(live.reason) && Boolean(runtime.navigation?.findPath && runtime.locomotion?.navigate),
207
+ verification: action === "rotate" ? "rigid-body-torque" : "rigid-body-force",
208
+ graspVerified: false
209
+ };
210
+ }) : [];
211
+ const descriptor = (action, live, parameters, verification) => ({
212
+ action,
213
+ source: "native-physics",
214
+ execution: "interaction",
215
+ parameters,
216
+ ...live,
217
+ canApproach: ["OUT_OF_REACH", "OCCLUDED"].includes(live.reason) && Boolean(runtime.navigation?.findPath && runtime.locomotion?.navigate),
218
+ verification,
219
+ graspVerified: false
220
+ });
221
+ for (const [partName, part] of Object.entries(record.manifest.parts || {})) {
222
+ const action = part.joint.type === "prismatic" ? "slide" : "rotateJoint", relative = action === "slide" ? "distance" : "angle", unit = action === "slide" ? "meter" : "radian";
223
+ const capability = runtime.interactions.manipulationCapability(id, action, partName);
224
+ let live = capability.available ? access : capability;
225
+ if (capability.available && actor && runtime.store.has(actor) && runtime.store.get(actor).manifest.type === "agent" && !runtime.interactions.heldByAgent(actor)) {
226
+ const aimPoint = runtime.physics.manipulationBody(id, partName, { contacts: true }).contactCandidates[0]?.center;
227
+ if (aimPoint) {
228
+ const reach = runtime.interactions.interactionStatus(actor, id, {
229
+ aimPoint,
230
+ aimPart: partName
231
+ });
232
+ live = {
233
+ available: reach.interactable,
234
+ reason: reach.interactable ? null : reach.inRange ? "OCCLUDED" : "OUT_OF_REACH"
235
+ };
236
+ }
237
+ }
238
+ actions.push({
239
+ ...descriptor(action, live, {
240
+ part: {
241
+ type: "string",
242
+ enum: [partName],
243
+ required: true
244
+ },
245
+ target: {
246
+ type: "number",
247
+ required: false,
248
+ alternative: relative,
249
+ unit,
250
+ limits: [...part.joint.limits]
251
+ },
252
+ [relative]: {
253
+ type: "number",
254
+ required: false,
255
+ alternative: "target",
256
+ relative: true,
257
+ unit
258
+ }
259
+ }, "joint-motor"),
260
+ partName
261
+ });
262
+ }
263
+ const held = record.state.heldBy, owned = held?.kind === "agent" && held.id === actor;
264
+ if (record.manifest.physics.carryable === true) {
265
+ const assessment = inferCarryCapability(record.manifest);
266
+ const live = assessment.eligible ? held && !owned ? {
267
+ available: false,
268
+ reason: "OBJECT_ALREADY_HELD"
269
+ } : owned ? { available: true } : access : {
270
+ available: false,
271
+ reason: assessment.reason
272
+ };
273
+ actions.push(descriptor("pickup", live, {}, "kinematic-anchor"));
274
+ actions.push(descriptor("drop", actor ? {
275
+ available: Boolean(owned),
276
+ reason: owned ? null : "NOT_HOLDING_OBJECT"
277
+ } : {
278
+ available: null,
279
+ reason: "ACTOR_REQUIRED_FOR_REACH_CHECK"
280
+ }, {}, "dynamic-settle"));
281
+ }
282
+ if (record.manifest.surfaces.length) {
283
+ const heldId = actor && runtime.interactions?.heldByAgent(actor);
284
+ const heldRecord = heldId ? runtime.store.has(heldId) ? runtime.store.get(heldId) : nativeCarryRecord(runtime.entities, runtime.physics, heldId) : null;
285
+ const live = actor && !heldId ? {
286
+ available: false,
287
+ reason: "NOT_HOLDING_OBJECT"
288
+ } : heldId ? heldRecord && runtime.interactions.supports(heldRecord, "place") ? reachAccess : {
289
+ available: false,
290
+ reason: "ACTION_UNSUPPORTED"
291
+ } : reachAccess;
292
+ actions.push(descriptor("place", live, { surfaceId: {
293
+ type: "string",
294
+ enum: record.manifest.surfaces.map((s) => s.id),
295
+ required: false
296
+ } }, "solver-contact+spatial-geometry"));
297
+ }
298
+ return actions;
299
+ }
300
+ // modules/world/verification/InteractionEvidence.js
301
+ const INTERACTION_EVIDENCE_SCHEMA = "agentscape.interaction-evidence";
302
+ const clean$1 = (value) => typeof value === "string" ? value.trim() : "";
303
+ const clone = (value) => structuredClone(value);
304
+ const key = (revisionId, targetId, capability, source, partName = null) => [
305
+ revisionId,
306
+ targetId,
307
+ capability,
308
+ source,
309
+ ...partName ? [partName] : []
310
+ ].join("\0");
311
+ const store = (runtime) => runtime.interactionEvidence ||= /* @__PURE__ */ new Map();
312
+ const summarizeResult = (result) => {
313
+ if (!result || typeof result !== "object") return null;
314
+ const summary = {};
315
+ for (const field of [
316
+ "status",
317
+ "action",
318
+ "targetId",
319
+ "actorId",
320
+ "supportId",
321
+ "heldId",
322
+ "stateKey",
323
+ "evidenceKind",
324
+ "partName"
325
+ ]) {
326
+ const value = clean$1(result[field]);
327
+ if (value) summary[field] = value;
328
+ }
329
+ for (const field of [
330
+ "targetReached",
331
+ "settled",
332
+ "supportVerified",
333
+ "heldRequired",
334
+ "physicsVerified"
335
+ ]) if (typeof result[field] === "boolean") summary[field] = result[field];
336
+ for (const field of ["coordinate", "target"]) if (Number.isFinite(result[field])) summary[field] = result[field];
337
+ if (Object.prototype.hasOwnProperty.call(result, "value") && (result.value === null || [
338
+ "string",
339
+ "number",
340
+ "boolean"
341
+ ].includes(typeof result.value))) summary.value = result.value;
342
+ return Object.keys(summary).length ? summary : null;
343
+ };
344
+ function clearInteractionEvidenceForTarget(runtime, targetId, { source = null, capability = null, partName = null } = {}) {
345
+ const target = clean$1(targetId);
346
+ if (!target || !runtime?.interactionEvidence?.size) return;
347
+ for (const [entryKey, evidence] of runtime.interactionEvidence) if ((evidence?.targetId === target || evidence?.result?.heldId === target) && (!source || evidence.source === source) && (!capability || evidence.capability === capability.toUpperCase()) && (!partName || evidence.partName === partName)) runtime.interactionEvidence.delete(entryKey);
348
+ }
349
+ function recordInteractionEvidence(runtime, { targetId, capability, verified, source = "runtime", commandId = null, result = null, partName = null } = {}) {
350
+ if (verified !== true) return null;
351
+ const worldRevisionId = clean$1(runtime?.currentWorldRevision?.revision?.id) || (runtime.interactionEvidenceScope ||= "session:" + crypto.randomUUID());
352
+ const target = clean$1(targetId), normalizedCapability = clean$1(capability).toUpperCase();
353
+ if (!worldRevisionId || !target || !normalizedCapability) return null;
354
+ const resultSummary = summarizeResult(result);
355
+ const evidence = {
356
+ schema: INTERACTION_EVIDENCE_SCHEMA,
357
+ schemaVersion: 1,
358
+ worldRevisionId,
359
+ targetId: target,
360
+ capability: normalizedCapability,
361
+ verified: true,
362
+ source,
363
+ ...partName ? { partName } : {},
364
+ ...clean$1(commandId) ? { commandId: clean$1(commandId) } : {},
365
+ ...resultSummary ? { result: resultSummary } : {}
366
+ };
367
+ const evidenceKey = key(worldRevisionId, target, normalizedCapability, source, partName);
368
+ store(runtime).delete(evidenceKey);
369
+ store(runtime).set(evidenceKey, evidence);
370
+ runtime.trace?.emit?.("interaction.verified", { evidence: clone(evidence) }, { actor: "runtime" });
371
+ return clone(evidence);
372
+ }
373
+ function getInteractionEvidence(runtime, targetId, capability, { worldRevisionId = null, source = null, partName = null } = {}) {
374
+ const revisionId = clean$1(worldRevisionId) || clean$1(runtime?.currentWorldRevision?.revision?.id) || runtime?.interactionEvidenceScope;
375
+ const target = clean$1(targetId), normalizedCapability = clean$1(capability).toUpperCase();
376
+ if (!revisionId || !target || !normalizedCapability) return null;
377
+ if (source && partName) {
378
+ const evidence = runtime?.interactionEvidence?.get?.(key(revisionId, target, normalizedCapability, source, partName));
379
+ return evidence?.verified === true ? clone(evidence) : null;
380
+ }
381
+ const matches = [...runtime?.interactionEvidence?.values?.() || []].filter((item) => item?.verified === true && item.worldRevisionId === revisionId && item.targetId === target && item.capability === normalizedCapability && (!source || item.source === source) && (!partName || item.partName === partName));
382
+ return matches.length ? clone(matches[matches.length - 1]) : null;
383
+ }
384
+ // modules/world/runtime/interaction/InteractionContract.js
385
+ const INTERACTION_CONTRACT_SCHEMA = "agentscape.interaction-contract";
386
+ const clean = (v) => typeof v === "string" ? v.trim() : "";
387
+ const plain = (v) => Boolean(v && typeof v === "object" && !Array.isArray(v));
388
+ const assertObject = (v, label) => {
389
+ if (!plain(v)) throw new TypeError(`${label} must be an object`);
390
+ return v;
391
+ };
392
+ const assertFinite = (v) => {
393
+ if (!Number.isFinite(v)) throw new TypeError("Interaction target must be finite");
394
+ return Number(v);
395
+ };
396
+ const requiredPartTargets = /* @__PURE__ */ new Set(["open", "close"]);
397
+ function compileInteractionContract(manifest) {
398
+ assertObject(manifest, "Manifest");
399
+ const entityId = clean(manifest.id) || "$anonymous";
400
+ const contracts = [];
401
+ const parts = manifest.parts || {};
402
+ for (const action of manifest.actions || []) {
403
+ const candidates = Object.entries(parts).filter(([partName, part]) => part?.actions?.includes(action) && Number.isFinite(part?.targets?.[action]));
404
+ if (requiredPartTargets.has(action) && !candidates.length) throw new TypeError(`Action ${action} has no executable part target`);
405
+ for (const [partName, part] of candidates) {
406
+ const target = assertFinite(part.targets[action]);
407
+ contracts.push({
408
+ id: `${entityId}:${partName}:${action}`,
409
+ capability: action.toUpperCase(),
410
+ action,
411
+ target: {
412
+ entityId,
413
+ partName
414
+ },
415
+ preconditions: [{
416
+ kind: "supports-action",
417
+ action
418
+ }, {
419
+ kind: "runtime-authorized",
420
+ capability: action.toUpperCase()
421
+ }],
422
+ effects: [{
423
+ kind: "set-articulation-target",
424
+ target
425
+ }],
426
+ stateTransition: {
427
+ kind: "articulation-completion",
428
+ from: [
429
+ "unknown",
430
+ "open",
431
+ "closed",
432
+ "moving"
433
+ ],
434
+ to: action
435
+ },
436
+ verifierTarget: {
437
+ type: "articulation-state",
438
+ entityId: manifest.id,
439
+ partName,
440
+ target,
441
+ settledRequired: true
442
+ }
443
+ });
444
+ }
445
+ }
446
+ return {
447
+ schema: INTERACTION_CONTRACT_SCHEMA,
448
+ schemaVersion: 1,
449
+ entityId,
450
+ contracts
451
+ };
452
+ }
453
+ function getInteractionContract(manifest, partName, action) {
454
+ const contract = compileInteractionContract(manifest).contracts.find((item) => item.target.partName === partName && item.action === action);
455
+ if (!contract) throw new Error(`Interaction contract not found: ${manifest.id}:${partName}:${action}`);
456
+ return structuredClone(contract);
457
+ }
458
+ function verifyInteractionResult(contract, result) {
459
+ const verifier = contract?.verifierTarget;
460
+ if (!verifier) return {
461
+ verified: false,
462
+ reason: "VERIFIER_TARGET_MISSING"
463
+ };
464
+ return result?.status === "action-completed" && result?.targetReached === true && result?.settled === true && result?.part === verifier.partName && Number.isFinite(result?.target) && Math.abs(result.target - verifier.target) <= .08 ? { verified: true } : {
465
+ verified: false,
466
+ reason: "POST_CONDITION_NOT_VERIFIED"
467
+ };
468
+ }
469
+ // modules/world/runtime/NativeNavigationGeometry.js
470
+ const fail = (code) => Object.assign(new Error(code), { code });
471
+ const unit = [
472
+ 0,
473
+ 0,
474
+ 0,
475
+ 1
476
+ ];
477
+ const origin = [
478
+ 0,
479
+ 0,
480
+ 0
481
+ ];
482
+ function colliderMesh(spec) {
483
+ if (spec.shape === "box") return new THREE.BoxGeometry(...spec.halfExtents.map((n) => 2 * n));
484
+ if (spec.shape === "cylinder") return new THREE.CylinderGeometry(spec.radius, spec.radius, 2 * spec.halfHeight, 24);
485
+ if (spec.shape === "capsule") return new THREE.CapsuleGeometry(spec.radius, 2 * spec.halfHeight, 8, 16);
486
+ if (spec.shape === "convexHull") {
487
+ if (!Array.isArray(spec.vertices) || spec.vertices.length % 3 || spec.vertices.length < 12 || spec.vertices.length > 6e4) throw fail("NATIVE_NAVIGATION_GEOMETRY_INVALID");
488
+ const points = [];
489
+ for (let i = 0; i < spec.vertices.length; i += 3) points.push(new THREE.Vector3(...spec.vertices.slice(i, i + 3)));
490
+ return new ConvexGeometry(points);
491
+ }
492
+ throw fail("NATIVE_NAVIGATION_COLLIDER_UNSUPPORTED");
493
+ }
494
+ /** Exact registered box/trimesh inputs; curved primitives are tessellated.
495
+ * No host-render geometry or ObjectStore identity is created or changed.
496
+ */
497
+ function nativeColliderNavigationInputs(colliders, bodyPose = {
498
+ position: origin,
499
+ rotation: unit
500
+ }, budget = {
501
+ triangles: 0,
502
+ vertices: 0,
503
+ colliders: 0
504
+ }) {
505
+ if (!Array.isArray(colliders)) throw fail("NATIVE_NAVIGATION_GEOMETRY_INVALID");
506
+ const body = new THREE.Matrix4().compose(new THREE.Vector3(...bodyPose.position), new THREE.Quaternion(...bodyPose.rotation), new THREE.Vector3(1, 1, 1));
507
+ const result = [];
508
+ for (const spec of colliders) {
509
+ if (++budget.colliders > 2048) throw fail("NATIVE_NAVIGATION_BUILD_LIMIT");
510
+ if (!spec || typeof spec !== "object") throw fail("NATIVE_NAVIGATION_GEOMETRY_INVALID");
511
+ const matrix = body.clone().multiply(new THREE.Matrix4().compose(new THREE.Vector3(...spec.translation || origin), new THREE.Quaternion(...spec.rotation || unit), new THREE.Vector3(1, 1, 1)));
512
+ let geometry = null;
513
+ try {
514
+ if (spec.shape !== "trimesh") geometry = colliderMesh(spec);
515
+ const attribute = geometry?.getAttribute("position"), source = attribute?.array || spec.vertices;
516
+ const sourceIndices = geometry ? geometry.getIndex()?.array || Uint32Array.from({ length: attribute.count }, (_, i) => i) : spec.indices;
517
+ if (!source || !sourceIndices || source.length % 3 || sourceIndices.length % 3 || source.length < 9 || source.length > 6e5 || sourceIndices.length > 3e5) throw fail("NATIVE_NAVIGATION_GEOMETRY_INVALID");
518
+ budget.triangles += sourceIndices.length / 3;
519
+ budget.vertices += source.length / 3;
520
+ if (budget.triangles > 2e5 || budget.vertices > 4e5) throw fail("NATIVE_NAVIGATION_BUILD_LIMIT");
521
+ const positions = new Float32Array(source.length), indices = new Uint32Array(sourceIndices.length);
522
+ const vertex = new THREE.Vector3();
523
+ for (let i = 0; i < source.length; i += 3) {
524
+ vertex.fromArray(source, i).applyMatrix4(matrix);
525
+ if (![
526
+ vertex.x,
527
+ vertex.y,
528
+ vertex.z
529
+ ].every(Number.isFinite)) throw fail("NATIVE_NAVIGATION_GEOMETRY_INVALID");
530
+ vertex.toArray(positions, i);
531
+ }
532
+ for (let i = 0; i < sourceIndices.length; i++) {
533
+ const index = sourceIndices[i];
534
+ if (!Number.isSafeInteger(index) || index < 0 || index >= source.length / 3) throw fail("NATIVE_NAVIGATION_GEOMETRY_INVALID");
535
+ indices[i] = index;
536
+ }
537
+ result.push({
538
+ positions,
539
+ indices
540
+ });
541
+ } finally {
542
+ geometry?.dispose();
543
+ }
544
+ }
545
+ return result;
546
+ }
547
+ function nativeFixedNavigationInputs(physics, budget = {
548
+ triangles: 0,
549
+ vertices: 0,
550
+ colliders: 0
551
+ }) {
552
+ const inputs = [];
553
+ for (const entry of physics?.entries?.values?.() || []) {
554
+ if (!entry.nativeNavigation || entry.rootSpec?.body !== "fixed") continue;
555
+ const pose = physics.backend.bodyPose(entry.body);
556
+ if (!pose) throw fail("NATIVE_NAVIGATION_BODY_UNAVAILABLE");
557
+ inputs.push(...nativeColliderNavigationInputs(entry.rootSpec.colliders, pose, budget));
558
+ }
559
+ return inputs;
560
+ }
561
+ /** Bound native build inputs before the WASM tile generator allocates a grid. */
562
+ function validateNativeNavigationInputs(inputs) {
563
+ let triangles = 0, vertices = 0, minX = 1e400, maxX = -1e400, minZ = 1e400, maxZ = -1e400;
564
+ for (const { positions, indices } of inputs) {
565
+ triangles += indices.length / 3;
566
+ vertices += positions.length / 3;
567
+ if (triangles > 2e5 || vertices > 4e5) throw fail("NATIVE_NAVIGATION_BUILD_LIMIT");
568
+ for (let i = 0; i < positions.length; i += 3) {
569
+ const x = positions[i], y = positions[i + 1], z = positions[i + 2];
570
+ if (![
571
+ x,
572
+ y,
573
+ z
574
+ ].every(Number.isFinite) || Math.max(Math.abs(x), Math.abs(y), Math.abs(z)) > 1e4) throw fail("NATIVE_NAVIGATION_GEOMETRY_INVALID");
575
+ minX = Math.min(minX, x);
576
+ maxX = Math.max(maxX, x);
577
+ minZ = Math.min(minZ, z);
578
+ maxZ = Math.max(maxZ, z);
579
+ }
580
+ }
581
+ if (maxX - minX > 256 || maxZ - minZ > 256) throw fail("NATIVE_NAVIGATION_EXTENT_LIMIT");
582
+ }
583
+ // modules/world/runtime/systems/NavigationSystem.js
584
+ const DEFAULT_CONFIG = Object.freeze({
585
+ agentRadius: .3,
586
+ agentHeight: 1.7,
587
+ maxClimb: .3,
588
+ maxSlope: 45,
589
+ maxSnapDistance: .75,
590
+ endTolerance: .3
591
+ });
592
+ const round = (value) => Number(value.toFixed(3));
593
+ const roundPoint = (point) => [
594
+ round(point.x),
595
+ round(point.y),
596
+ round(point.z)
597
+ ];
598
+ const point = (value) => ({
599
+ x: value[0],
600
+ y: value[1],
601
+ z: value[2]
602
+ });
603
+ const finitePoint = (value) => Array.isArray(value) && value.length === 3 && value.every(Number.isFinite);
604
+ const distance = (a, b) => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
605
+ const pathCost = (path) => path.slice(1).reduce((sum, current, index) => sum + distance(path[index], current), 0);
606
+ const geometryInputs = (meshes) => {
607
+ const vertex = new THREE.Vector3();
608
+ const inputs = [];
609
+ for (const mesh of meshes) {
610
+ mesh.updateWorldMatrix(true, false);
611
+ const attribute = mesh.geometry.getAttribute("position");
612
+ if (!attribute || attribute.itemSize !== 3) continue;
613
+ const positions = new Float32Array(attribute.count * 3);
614
+ for (let i = 0; i < attribute.count; i++) vertex.fromBufferAttribute(attribute, i).applyMatrix4(mesh.matrixWorld).toArray(positions, i * 3);
615
+ const indices = mesh.geometry.getIndex()?.array || Uint32Array.from({ length: attribute.count }, (_, i) => i);
616
+ inputs.push({
617
+ positions,
618
+ indices
619
+ });
620
+ }
621
+ return inputs;
622
+ };
623
+ const obstacleDistanceXZ = (position, descriptor) => {
624
+ const dx = position[0] - descriptor.position[0];
625
+ const dz = position[2] - descriptor.position[2];
626
+ if (descriptor.shape === "cylinder") return Math.max(0, Math.hypot(dx, dz) - descriptor.radius);
627
+ const angle = -(descriptor.angle || 0);
628
+ const localX = Math.cos(angle) * dx - Math.sin(angle) * dz;
629
+ const localZ = Math.sin(angle) * dx + Math.cos(angle) * dz;
630
+ const outsideX = Math.max(0, Math.abs(localX) - descriptor.halfExtents[0]);
631
+ const outsideZ = Math.max(0, Math.abs(localZ) - descriptor.halfExtents[2]);
632
+ return Math.hypot(outsideX, outsideZ);
633
+ };
634
+ function partialRouteProgress(current, route, minimumGain) {
635
+ if (current.reason !== "PARTIAL_PATH" || route.reason !== "PARTIAL_PATH" || !current.path.length || !route.path.length || !current.start?.snapped || !route.start?.snapped || !current.end?.snapped || !route.end?.snapped) return null;
636
+ const delta = (a, b) => distance(point(a), point(b));
637
+ if (delta(current.start.snapped, route.start.snapped) > .1 || delta(current.end.snapped, route.end.snapped) > .1) return null;
638
+ const before = current.path.at(-1), after = route.path.at(-1), goal = current.end.snapped;
639
+ const remainingBefore = delta(before, goal), remainingAfter = delta(after, goal), gain = remainingBefore - remainingAfter;
640
+ if (!Number.isFinite(gain) || gain < minimumGain || delta(before, after) < minimumGain) return null;
641
+ return {
642
+ kind: "partial-route-progress",
643
+ endpointBefore: [...before],
644
+ endpointAfter: [...after],
645
+ remainingBefore: round(remainingBefore),
646
+ remainingAfter: round(remainingAfter),
647
+ gain: round(gain),
648
+ minimumGain: round(minimumGain)
649
+ };
650
+ }
651
+ const navigationRecoveryCandidate = (c) => Boolean(c.eligibility.eligible && !c.alreadyRequested && (c.counterfactual.reachable || c.counterfactual.progress?.kind === "partial-route-progress"));
652
+ const routePriority = (c) => c.counterfactual.reachable ? 2 : c.counterfactual.progress ? 1 : 0;
653
+ const articulationEligibility = (record, partName, action) => {
654
+ const part = record?.manifest?.parts?.[partName];
655
+ if (!part?.actions?.includes(action) || !Number.isFinite(part.targets?.[action]) || !part.physics || !part.joint) return {
656
+ eligible: false,
657
+ status: "not-executable",
658
+ reason: "ACTION_NOT_EXECUTABLE"
659
+ };
660
+ if (record.manifest.source?.kind !== "compiled") return {
661
+ eligible: true,
662
+ status: "declared-executable",
663
+ evidence: "manifest"
664
+ };
665
+ const verification = record.manifest.verification?.articulation;
666
+ const partReport = verification?.parts?.find((item) => item.part === partName);
667
+ const actionReport = partReport?.actions?.find((item) => item.action === action);
668
+ if (verification?.ok && partReport?.ok && actionReport?.ok) return {
669
+ eligible: true,
670
+ status: "runtime-verified",
671
+ evidence: "verification.articulation"
672
+ };
673
+ return {
674
+ eligible: false,
675
+ status: "unverified",
676
+ reason: "ARTICULATION_UNVERIFIED"
677
+ };
678
+ };
679
+ var NavigationSystem = class {
680
+ constructor({ store, physics = null, environmentRoots = [], nativeEnvironmentColliders = null, config = {}, backend } = {}) {
681
+ if (!backend) throw new TypeError("NavigationSystem requires a navigation backend");
682
+ this.store = store;
683
+ this.physics = physics;
684
+ this.environmentRoots = [...environmentRoots];
685
+ this.nativeEnvironmentColliders = nativeEnvironmentColliders;
686
+ this.config = {
687
+ ...DEFAULT_CONFIG,
688
+ ...config
689
+ };
690
+ this.backend = backend;
691
+ this.obstacles = /* @__PURE__ */ new Map();
692
+ this.obstacleSyncVersion = 0;
693
+ this.lastObstacleSync = null;
694
+ this.dirty = true;
695
+ this.revision = 0;
696
+ this.buildVersion = 0;
697
+ this.buildPromise = null;
698
+ this.lastInvalidation = "initial";
699
+ this.lastBuild = null;
700
+ this.disposed = false;
701
+ }
702
+ isStaticRecord(record) {
703
+ return record?.manifest?.physics?.body === "fixed";
704
+ }
705
+ invalidate(reason = "world-changed") {
706
+ this.dirty = true;
707
+ this.revision += 1;
708
+ this.lastInvalidation = reason;
709
+ }
710
+ invalidateIfStatic(record, reason) {
711
+ if (!this.isStaticRecord(record)) return false;
712
+ this.invalidate(reason);
713
+ return true;
714
+ }
715
+ runtimeCapabilities() {
716
+ const capabilities = ["action-aware-diagnostics"];
717
+ if (typeof this.physics?.getNavigationObstacles === "function" && this.backend.hasCapability?.("dynamic-obstacles") && this.backend.hasCapability?.("obstacle-suppression")) capabilities.push("counterfactual-routing");
718
+ return capabilities;
719
+ }
720
+ profile() {
721
+ const backendProfile = this.backend.profile?.() || {
722
+ identity: "unknown",
723
+ capabilities: []
724
+ };
725
+ const backendCapabilities = [...backendProfile.capabilities || []];
726
+ const runtimeCapabilities = this.runtimeCapabilities();
727
+ return {
728
+ identity: backendProfile.identity,
729
+ backendCapabilities,
730
+ runtimeCapabilities,
731
+ capabilities: [.../* @__PURE__ */ new Set([...backendCapabilities, ...runtimeCapabilities])]
732
+ };
733
+ }
734
+ status() {
735
+ const backendProfile = this.profile();
736
+ const backendReady = this.backend.isReady?.() === true;
737
+ const hasObstacleSource = typeof this.physics?.getNavigationObstacles === "function" || this.physics?.hasCapability?.("collision") === true;
738
+ const dynamicObstacles = this.backend.hasCapability?.("dynamic-obstacles") === true && hasObstacleSource;
739
+ return {
740
+ state: !backendReady ? this.lastBuild?.success === false ? "failed" : "unbuilt" : this.dirty ? "dirty" : "ready",
741
+ dirty: this.dirty,
742
+ buildVersion: this.buildVersion,
743
+ lastInvalidation: this.lastInvalidation,
744
+ config: { ...this.config },
745
+ backend: backendProfile,
746
+ capabilities: {
747
+ staticRouting: this.backend.hasCapability?.("static-routing") === true,
748
+ dynamicObstacles,
749
+ routeQuery: this.backend.hasCapability?.("route-query") === true,
750
+ obstacleSuppression: this.backend.hasCapability?.("obstacle-suppression") === true,
751
+ obstacleSource: dynamicObstacles ? `physics:${this.physics?.profile?.().identity || "unknown"}:colliders` : "none",
752
+ synchronization: "query-time",
753
+ actionAwareDiagnostics: this.runtimeCapabilities().includes("action-aware-diagnostics"),
754
+ counterfactual: this.runtimeCapabilities().includes("counterfactual-routing") ? "single-obstacle-suppression" : "none"
755
+ },
756
+ dynamicObstacles: {
757
+ tracked: this.obstacles.size,
758
+ syncVersion: this.obstacleSyncVersion,
759
+ lastSync: this.lastObstacleSync ? structuredClone(this.lastObstacleSync) : null
760
+ },
761
+ lastBuild: this.lastBuild ? structuredClone(this.lastBuild) : null
762
+ };
763
+ }
764
+ collectStaticMeshes() {
765
+ const meshes = [];
766
+ const skipped = [];
767
+ const seen = /* @__PURE__ */ new Set();
768
+ const collect = (root, source, excludedPartNodes = /* @__PURE__ */ new Set()) => {
769
+ root.updateWorldMatrix?.(true, true);
770
+ root.traverse?.((node) => {
771
+ if (!node.isMesh || seen.has(node) || node.userData?.navigationIgnore) return;
772
+ seen.add(node);
773
+ for (let current = node; current && current !== root.parent; current = current.parent) {
774
+ if (excludedPartNodes.has(current.name)) {
775
+ skipped.push({
776
+ source,
777
+ node: node.name || null,
778
+ reason: "dynamic-part"
779
+ });
780
+ return;
781
+ }
782
+ if (current === root) break;
783
+ }
784
+ if (!node.visible || node.isSkinnedMesh || node.isInstancedMesh || !node.geometry?.getAttribute?.("position")) {
785
+ skipped.push({
786
+ source,
787
+ node: node.name || null,
788
+ reason: node.isSkinnedMesh ? "skinned" : node.isInstancedMesh ? "instanced" : "unsupported"
789
+ });
790
+ return;
791
+ }
792
+ meshes.push(node);
793
+ });
794
+ };
795
+ this.environmentRoots.forEach((root, index) => collect(root, `environment:${index}`));
796
+ for (const [id, record] of this.store?.entries?.() || []) {
797
+ if (record.active === false || !this.isStaticRecord(record)) continue;
798
+ const excludedPartNodes = new Set(Object.values(record.manifest.parts || {}).filter((part) => part?.joint || part?.physics?.body && part.physics.body !== "fixed").map((part) => part.node).filter(Boolean));
799
+ collect(record.object, id, excludedPartNodes);
800
+ }
801
+ return {
802
+ meshes,
803
+ skipped
804
+ };
805
+ }
806
+ async rebuild() {
807
+ if (this.disposed) return {
808
+ success: false,
809
+ code: "NAVIGATION_DISPOSED"
810
+ };
811
+ const revision = this.revision;
812
+ const startedAt = Date.now();
813
+ const { meshes, skipped } = this.collectStaticMeshes();
814
+ let inputs, nativeInputCount = 0;
815
+ try {
816
+ const budget = {
817
+ triangles: 0,
818
+ vertices: 0,
819
+ colliders: 0
820
+ };
821
+ const nativeInputs = [...nativeColliderNavigationInputs(this.nativeEnvironmentColliders || [], void 0, budget), ...nativeFixedNavigationInputs(this.physics, budget)];
822
+ nativeInputCount = nativeInputs.length;
823
+ inputs = [...geometryInputs(meshes), ...nativeInputs];
824
+ if (this.nativeEnvironmentColliders !== null || nativeInputCount) validateNativeNavigationInputs(inputs);
825
+ } catch (error) {
826
+ this.backend.clear?.();
827
+ this.obstacles.clear();
828
+ this.lastBuild = {
829
+ success: false,
830
+ code: error.code || "NATIVE_NAVIGATION_GEOMETRY_INVALID",
831
+ meshCount: meshes.length,
832
+ skipped,
833
+ at: (/* @__PURE__ */ new Date()).toISOString()
834
+ };
835
+ return this.lastBuild;
836
+ }
837
+ if (!inputs.length) {
838
+ this.backend.clear?.();
839
+ this.obstacles.clear();
840
+ this.lastBuild = {
841
+ success: false,
842
+ code: "NAVMESH_EMPTY",
843
+ meshCount: 0,
844
+ skipped,
845
+ at: (/* @__PURE__ */ new Date()).toISOString()
846
+ };
847
+ return this.lastBuild;
848
+ }
849
+ const result = await this.backend.build(inputs, this.config);
850
+ if (this.disposed || revision !== this.revision) {
851
+ this.backend.clear?.();
852
+ this.obstacles.clear();
853
+ return {
854
+ success: false,
855
+ code: "NAVMESH_CHANGED_DURING_BUILD"
856
+ };
857
+ }
858
+ if (!result?.success) {
859
+ this.obstacles.clear();
860
+ this.lastBuild = {
861
+ success: false,
862
+ code: result?.code || "NAVMESH_BUILD_FAILED",
863
+ ...result?.error ? { error: result.error } : {},
864
+ meshCount: meshes.length + nativeInputCount,
865
+ ...nativeInputCount ? { nativeColliderCount: nativeInputCount } : {},
866
+ skipped,
867
+ at: (/* @__PURE__ */ new Date()).toISOString()
868
+ };
869
+ return this.lastBuild;
870
+ }
871
+ this.obstacles.clear();
872
+ this.dirty = false;
873
+ this.buildVersion += 1;
874
+ this.lastBuild = {
875
+ success: true,
876
+ buildVersion: this.buildVersion,
877
+ meshCount: meshes.length + nativeInputCount,
878
+ ...nativeInputCount ? { nativeColliderCount: nativeInputCount } : {},
879
+ skipped,
880
+ durationMs: Date.now() - startedAt,
881
+ at: (/* @__PURE__ */ new Date()).toISOString()
882
+ };
883
+ return this.lastBuild;
884
+ }
885
+ async ensureBuilt() {
886
+ if (this.disposed) return {
887
+ success: false,
888
+ code: "NAVIGATION_DISPOSED"
889
+ };
890
+ if (!this.dirty && this.backend.isReady?.()) return this.lastBuild;
891
+ if (!this.buildPromise) this.buildPromise = this.rebuild().finally(() => {
892
+ this.buildPromise = null;
893
+ });
894
+ return this.buildPromise;
895
+ }
896
+ reconcileDynamicObstacles() {
897
+ if (!this.backend.hasCapability?.("dynamic-obstacles") || typeof this.physics?.getNavigationObstacles !== "function") {
898
+ if (this.backend.isReady?.()) this.backend.syncObstacles?.([]);
899
+ this.obstacles.clear();
900
+ const result = {
901
+ success: true,
902
+ coverage: "none",
903
+ tracked: 0,
904
+ skipped: [],
905
+ changed: 0,
906
+ operations: 0,
907
+ updates: 0,
908
+ syncVersion: this.obstacleSyncVersion
909
+ };
910
+ this.lastObstacleSync = result;
911
+ return result;
912
+ }
913
+ const snapshot = this.physics.getNavigationObstacles();
914
+ const synced = this.backend.syncObstacles(snapshot.items || []);
915
+ this.obstacles = new Map((synced.descriptors || []).map((descriptor) => [descriptor.id, structuredClone(descriptor)]));
916
+ if (!synced.success) return this.obstacleSyncFailure(synced.code, snapshot, synced.changed || 0, synced.operations || 0, synced.updates || 0);
917
+ if (synced.changed) this.obstacleSyncVersion += 1;
918
+ const result = {
919
+ success: true,
920
+ coverage: snapshot.skipped?.length ? "partial" : "complete",
921
+ tracked: this.obstacles.size,
922
+ skipped: structuredClone(snapshot.skipped || []),
923
+ changed: synced.changed || 0,
924
+ operations: synced.operations || 0,
925
+ updates: synced.updates || 0,
926
+ syncVersion: this.obstacleSyncVersion
927
+ };
928
+ this.lastObstacleSync = result;
929
+ return result;
930
+ }
931
+ obstacleSyncFailure(code, snapshot, changed, operations, updates) {
932
+ const result = {
933
+ success: false,
934
+ code,
935
+ coverage: "partial",
936
+ tracked: this.obstacles.size,
937
+ skipped: structuredClone(snapshot.skipped || []),
938
+ changed,
939
+ operations,
940
+ updates,
941
+ syncVersion: this.obstacleSyncVersion
942
+ };
943
+ this.lastObstacleSync = result;
944
+ return result;
945
+ }
946
+ async ensureCurrent() {
947
+ const build = await this.ensureBuilt();
948
+ if (!build?.success || !this.backend.isReady?.()) return {
949
+ success: false,
950
+ code: build?.code || "NAVMESH_UNAVAILABLE",
951
+ build
952
+ };
953
+ const obstacles = this.reconcileDynamicObstacles();
954
+ if (!obstacles.success) return {
955
+ success: false,
956
+ code: obstacles.code,
957
+ build,
958
+ obstacles
959
+ };
960
+ return {
961
+ success: true,
962
+ build,
963
+ obstacles
964
+ };
965
+ }
966
+ queryHalfExtents(maxSnapDistance) {
967
+ const horizontal = Math.max(maxSnapDistance, this.config.agentRadius * 2);
968
+ return {
969
+ x: horizontal,
970
+ y: Math.max(this.config.agentHeight, maxSnapDistance),
971
+ z: horizontal
972
+ };
973
+ }
974
+ queryReadyPath(start, end, { maxSnapDistance, endTolerance, scope, build, dynamicObstacles, suppressedObstacleIds = [], replacementObstacles = null }) {
975
+ const raw = this.backend.queryPath(start, end, {
976
+ halfExtents: this.queryHalfExtents(maxSnapDistance),
977
+ suppressedObstacleIds,
978
+ ...replacementObstacles ? { replacementObstacles } : {}
979
+ });
980
+ if (!raw?.success) return {
981
+ reachable: false,
982
+ scope,
983
+ reason: raw?.code || "NAVIGATION_QUERY_FAILED",
984
+ sameIsland: null,
985
+ path: [],
986
+ cost: null,
987
+ buildVersion: build?.buildVersion || this.buildVersion,
988
+ dynamicObstacles
989
+ };
990
+ const project = (input, result) => {
991
+ if (!result?.success) return {
992
+ success: false,
993
+ input: point(input),
994
+ reason: "NAVMESH_QUERY_FAILED"
995
+ };
996
+ const inputPoint = point(input);
997
+ const snapDistance = distance(inputPoint, result.point);
998
+ if (snapDistance > maxSnapDistance) return {
999
+ success: false,
1000
+ reason: "OFF_NAVMESH",
1001
+ input: inputPoint,
1002
+ point: result.point,
1003
+ snapDistance
1004
+ };
1005
+ return {
1006
+ success: true,
1007
+ input: inputPoint,
1008
+ point: result.point,
1009
+ snapDistance
1010
+ };
1011
+ };
1012
+ const projectedStart = project(start, raw.start);
1013
+ if (!projectedStart.success) return this.offMeshResult("START_OFF_NAVMESH", projectedStart, build, scope, dynamicObstacles);
1014
+ const projectedEnd = project(end, raw.end);
1015
+ if (!projectedEnd.success) return this.offMeshResult("END_OFF_NAVMESH", projectedEnd, build, scope, dynamicObstacles);
1016
+ const computed = raw.computed || {
1017
+ success: false,
1018
+ path: []
1019
+ };
1020
+ const rawPath = computed.path || [];
1021
+ const finalDistance = rawPath.length ? distance(rawPath.at(-1), projectedEnd.point) : 1e400;
1022
+ const reachable = computed.success && rawPath.length > 0 && finalDistance <= endTolerance;
1023
+ const reason = reachable ? null : computed.success && rawPath.length ? "PARTIAL_PATH" : "NO_PATH";
1024
+ return {
1025
+ reachable,
1026
+ scope,
1027
+ reason,
1028
+ sameIsland: reachable ? true : reason === "PARTIAL_PATH" ? false : null,
1029
+ start: {
1030
+ input: [...start],
1031
+ snapped: roundPoint(projectedStart.point),
1032
+ snapDistance: round(projectedStart.snapDistance)
1033
+ },
1034
+ end: {
1035
+ input: [...end],
1036
+ snapped: roundPoint(projectedEnd.point),
1037
+ snapDistance: round(projectedEnd.snapDistance)
1038
+ },
1039
+ path: rawPath.map(roundPoint),
1040
+ cost: rawPath.length ? round(pathCost(rawPath)) : null,
1041
+ finalDistance: Number.isFinite(finalDistance) ? round(finalDistance) : null,
1042
+ buildVersion: this.buildVersion,
1043
+ dynamicObstacles,
1044
+ ...computed.error ? { error: computed.error } : {}
1045
+ };
1046
+ }
1047
+ async findPath(start, end, { maxSnapDistance = this.config.maxSnapDistance, endTolerance = this.config.endTolerance } = {}) {
1048
+ const scope = this.physics?.getNavigationObstacles ? "current" : "static";
1049
+ if (!finitePoint(start) || !finitePoint(end) || !Number.isFinite(maxSnapDistance) || maxSnapDistance < 0) return {
1050
+ reachable: false,
1051
+ scope,
1052
+ reason: "INVALID_INPUT",
1053
+ path: [],
1054
+ cost: null,
1055
+ sameIsland: null
1056
+ };
1057
+ const current = await this.ensureCurrent();
1058
+ if (!current.success || !this.backend.isReady?.()) return {
1059
+ reachable: false,
1060
+ scope,
1061
+ reason: current.code,
1062
+ path: [],
1063
+ cost: null,
1064
+ sameIsland: null,
1065
+ build: current.build,
1066
+ dynamicObstacles: current.obstacles || null
1067
+ };
1068
+ return this.queryReadyPath(start, end, {
1069
+ maxSnapDistance,
1070
+ endTolerance,
1071
+ scope,
1072
+ build: current.build,
1073
+ dynamicObstacles: current.obstacles
1074
+ });
1075
+ }
1076
+ actionableObstacleGroups() {
1077
+ const groups = /* @__PURE__ */ new Map();
1078
+ for (const [obstacleId, descriptor] of this.obstacles) {
1079
+ if (!descriptor?.objectId || !descriptor?.part || descriptor.part === "$root") continue;
1080
+ const record = this.store?.has?.(descriptor.objectId) ? this.store.get(descriptor.objectId) : null;
1081
+ const nativeEntry = this.physics?.entries?.get(descriptor.objectId);
1082
+ const nativePart = nativeEntry?.nativeArticulation ? nativeEntry.parts.get(descriptor.part) : null;
1083
+ const part = record?.manifest.parts?.[descriptor.part];
1084
+ if (!nativePart && (!part?.actions?.includes("open") || !Number.isFinite(part.targets?.open))) continue;
1085
+ if (nativePart && !this.backend.hasCapability?.("obstacle-replacement")) continue;
1086
+ const key = `${descriptor.objectId}:${descriptor.part}`;
1087
+ if (!groups.has(key)) groups.set(key, {
1088
+ objectId: descriptor.objectId,
1089
+ partName: descriptor.part,
1090
+ record,
1091
+ nativePart,
1092
+ obstacleIds: [],
1093
+ descriptors: []
1094
+ });
1095
+ const group = groups.get(key);
1096
+ group.obstacleIds.push(obstacleId);
1097
+ group.descriptors.push(descriptor);
1098
+ }
1099
+ return [...groups.values()];
1100
+ }
1101
+ counterfactualWithout(group, start, end, options, build) {
1102
+ return {
1103
+ ...this.queryReadyPath(start, end, {
1104
+ ...options,
1105
+ scope: "counterfactual",
1106
+ build,
1107
+ suppressedObstacleIds: group.obstacleIds,
1108
+ dynamicObstacles: {
1109
+ assumption: "obstacle-suppressed",
1110
+ suppressed: [...group.obstacleIds],
1111
+ provisional: true
1112
+ }
1113
+ }),
1114
+ provisional: true,
1115
+ assumption: "obstacle-suppressed"
1116
+ };
1117
+ }
1118
+ nativeJointCandidates(group, start, end, options, current) {
1119
+ const state = this.physics.getArticulationState(group.objectId, group.partName);
1120
+ if (!state?.limits) return [];
1121
+ const action = state.jointType === "prismatic" ? "slide" : "rotateJoint";
1122
+ const candidates = [];
1123
+ for (const target of state.limits) {
1124
+ if (this.dirty) break;
1125
+ if (Math.abs(target - state.coordinate) <= state.tolerance * 1.5) continue;
1126
+ const base = {
1127
+ objectId: group.objectId,
1128
+ partName: group.partName,
1129
+ source: "native-physics",
1130
+ action,
1131
+ target,
1132
+ currentCoordinate: round(state.coordinate),
1133
+ obstacleIds: [...group.obstacleIds],
1134
+ distanceToPartialEndpoint: round(group.distance)
1135
+ };
1136
+ const rejected = (reason, counterfactual = {}) => ({
1137
+ ...base,
1138
+ eligibility: {
1139
+ eligible: false,
1140
+ reason
1141
+ },
1142
+ alreadyRequested: false,
1143
+ counterfactual: {
1144
+ provisional: true,
1145
+ assumption: "joint-target-pose",
1146
+ reachable: false,
1147
+ ...counterfactual
1148
+ }
1149
+ });
1150
+ const pose = this.physics.nativeNavigationJointPose(group.objectId, group.partName, target);
1151
+ if (!pose.checked || pose.descriptors.length !== group.obstacleIds.length || pose.descriptors.some((item) => !group.obstacleIds.includes(item.id))) {
1152
+ candidates.push(rejected(pose.reason || "NATIVE_NAVIGATION_OBSTACLE_COVERAGE_INCOMPLETE"));
1153
+ continue;
1154
+ }
1155
+ let route;
1156
+ try {
1157
+ route = this.queryReadyPath(start, end, {
1158
+ ...options,
1159
+ scope: "counterfactual",
1160
+ build: this.lastBuild,
1161
+ replacementObstacles: pose.descriptors,
1162
+ dynamicObstacles: {
1163
+ assumption: "joint-target-pose",
1164
+ provisional: true
1165
+ }
1166
+ });
1167
+ } catch (error) {
1168
+ if (!this.reconcileDynamicObstacles().success) this.invalidate("counterfactual-restore-failed");
1169
+ candidates.push(rejected(error.message));
1170
+ continue;
1171
+ }
1172
+ const progress = route.reachable ? null : partialRouteProgress(current, route, Math.max(.5, 2 * this.config.agentRadius, 2 * options.endTolerance));
1173
+ const counterfactual = {
1174
+ provisional: true,
1175
+ assumption: "joint-target-pose",
1176
+ reachable: route.reachable,
1177
+ reason: route.reason,
1178
+ cost: route.cost,
1179
+ waypointCount: route.path.length,
1180
+ finalDistance: route.finalDistance ?? null,
1181
+ ...progress ? { progress } : {}
1182
+ };
1183
+ if (!route.reachable && !progress) {
1184
+ candidates.push(rejected("TARGET_POSE_DOES_NOT_UNLOCK_ROUTE", counterfactual));
1185
+ continue;
1186
+ }
1187
+ const sweep = this.physics.articulationWorldCounterfactual(group.objectId, group.partName, target);
1188
+ const eligible = sweep.checked && sweep.actionIntroducesNoCollision === true;
1189
+ candidates.push({
1190
+ ...base,
1191
+ eligibility: {
1192
+ eligible: Boolean(eligible),
1193
+ status: eligible ? "declared-numeric-joint" : "ineligible",
1194
+ ...!eligible ? { reason: sweep.reason || "JOINT_SWEEP_INTRODUCES_COLLISION" } : {}
1195
+ },
1196
+ alreadyRequested: false,
1197
+ counterfactual,
1198
+ sweep: {
1199
+ checked: sweep.checked,
1200
+ samples: sweep.samples,
1201
+ actionIntroducesNoCollision: sweep.actionIntroducesNoCollision,
1202
+ blockers: sweep.actionEnvelope?.introducedBlockers?.slice(0, 8) || []
1203
+ }
1204
+ });
1205
+ }
1206
+ return candidates.sort((a, b) => Number(b.eligibility.eligible) - Number(a.eligibility.eligible) || Math.abs(a.target - state.coordinate) - Math.abs(b.target - state.coordinate));
1207
+ }
1208
+ async suggestActions(start, end, { maxSnapDistance = this.config.maxSnapDistance, maxCandidates = 6 } = {}) {
1209
+ const endTolerance = this.config.endTolerance;
1210
+ const current = await this.findPath(start, end, {
1211
+ maxSnapDistance,
1212
+ endTolerance
1213
+ });
1214
+ if (current.reachable) return {
1215
+ status: "reachable",
1216
+ current,
1217
+ candidates: [],
1218
+ recommendation: null
1219
+ };
1220
+ if (!["PARTIAL_PATH", "NO_PATH"].includes(current.reason)) return {
1221
+ status: "unresolved",
1222
+ current,
1223
+ candidates: [],
1224
+ recommendation: null
1225
+ };
1226
+ const anchor = current.path.at(-1) || start;
1227
+ const groups = this.actionableObstacleGroups().map((group) => ({
1228
+ ...group,
1229
+ distance: Math.min(...group.descriptors.map((descriptor) => obstacleDistanceXZ(anchor, descriptor)))
1230
+ })).sort((a, b) => a.distance - b.distance).slice(0, Math.max(1, Math.min(8, maxCandidates)));
1231
+ const candidates = [];
1232
+ for (const group of groups) {
1233
+ if (this.dirty) break;
1234
+ if (group.nativePart) {
1235
+ candidates.push(...this.nativeJointCandidates(group, start, end, {
1236
+ maxSnapDistance,
1237
+ endTolerance
1238
+ }, current));
1239
+ continue;
1240
+ }
1241
+ const eligibility = articulationEligibility(group.record, group.partName, "open");
1242
+ const requested = group.record.state?.partTargets?.[group.partName] === "open" || group.record.state?.parts?.[group.partName] === "open";
1243
+ let counterfactual;
1244
+ try {
1245
+ counterfactual = this.counterfactualWithout(group, start, end, {
1246
+ maxSnapDistance,
1247
+ endTolerance
1248
+ }, current.build || this.lastBuild);
1249
+ } catch (error) {
1250
+ const recovery = this.reconcileDynamicObstacles();
1251
+ counterfactual = {
1252
+ reachable: false,
1253
+ provisional: true,
1254
+ assumption: "obstacle-suppressed",
1255
+ reason: error.message,
1256
+ recovery: recovery.success ? "restored-current-world" : recovery.code
1257
+ };
1258
+ }
1259
+ candidates.push({
1260
+ objectId: group.objectId,
1261
+ partName: group.partName,
1262
+ action: "open",
1263
+ obstacleIds: [...group.obstacleIds],
1264
+ distanceToPartialEndpoint: round(group.distance),
1265
+ eligibility,
1266
+ alreadyRequested: requested,
1267
+ counterfactual: {
1268
+ provisional: true,
1269
+ assumption: "obstacle-suppressed",
1270
+ reachable: Boolean(counterfactual.reachable),
1271
+ reason: counterfactual.reason || null,
1272
+ cost: counterfactual.cost ?? null,
1273
+ waypointCount: counterfactual.path?.length ?? 0
1274
+ }
1275
+ });
1276
+ }
1277
+ if (this.dirty) return {
1278
+ status: "unresolved",
1279
+ current,
1280
+ candidates: [],
1281
+ recommendation: null,
1282
+ reason: "NAVIGATION_COUNTERFACTUAL_RESTORE_FAILED"
1283
+ };
1284
+ candidates.sort((a, b) => Number(navigationRecoveryCandidate(b)) - Number(navigationRecoveryCandidate(a)) || routePriority(b) - routePriority(a) || (b.counterfactual.progress?.gain || 0) - (a.counterfactual.progress?.gain || 0));
1285
+ const recommended = candidates.find(navigationRecoveryCandidate) || null;
1286
+ const waiting = !recommended && candidates.find((candidate) => candidate.alreadyRequested && candidate.counterfactual.reachable);
1287
+ return {
1288
+ status: recommended ? "action-candidate" : waiting ? "waiting-for-world-update" : "blocked",
1289
+ current,
1290
+ candidates,
1291
+ recommendation: recommended ? {
1292
+ ...recommended.source === "native-physics" ? { interaction: {
1293
+ action: "invoke",
1294
+ target: recommended.objectId,
1295
+ source: "native-physics",
1296
+ name: recommended.action,
1297
+ partName: recommended.partName,
1298
+ args: { target: recommended.target }
1299
+ } } : { call: {
1300
+ name: "open",
1301
+ args: {
1302
+ id: recommended.objectId,
1303
+ partName: recommended.partName
1304
+ }
1305
+ } },
1306
+ ...recommended.counterfactual.progress ? { progress: recommended.counterfactual.progress } : {},
1307
+ then: {
1308
+ name: "findPath",
1309
+ args: {
1310
+ start: [...start],
1311
+ end: [...end]
1312
+ },
1313
+ condition: "after-world-state-changes"
1314
+ },
1315
+ provisional: true
1316
+ } : null
1317
+ };
1318
+ }
1319
+ offMeshResult(reason, projected, build, scope = "static", dynamicObstacles = null) {
1320
+ return {
1321
+ reachable: false,
1322
+ scope,
1323
+ reason,
1324
+ sameIsland: null,
1325
+ path: [],
1326
+ cost: null,
1327
+ snapDistance: Number.isFinite(projected.snapDistance) ? round(projected.snapDistance) : null,
1328
+ snapped: projected.point ? roundPoint(projected.point) : null,
1329
+ buildVersion: build?.buildVersion || this.buildVersion,
1330
+ dynamicObstacles
1331
+ };
1332
+ }
1333
+ async canReach(start, end, options) {
1334
+ const { path, ...summary } = await this.findPath(start, end, options);
1335
+ return {
1336
+ ...summary,
1337
+ waypointCount: path.length
1338
+ };
1339
+ }
1340
+ debugGeometry() {
1341
+ return this.backend.debugGeometry?.() || [];
1342
+ }
1343
+ debugSnapshot() {
1344
+ const mesh = this.backend.debugMesh?.() || {
1345
+ positions: this.debugGeometry(),
1346
+ indices: []
1347
+ };
1348
+ return {
1349
+ schemaVersion: 1,
1350
+ source: "navigation",
1351
+ status: this.status(),
1352
+ navMesh: {
1353
+ positions: [...mesh.positions || []],
1354
+ indices: [...mesh.indices || []],
1355
+ vertexCount: Math.floor((mesh.positions?.length || 0) / 3),
1356
+ triangleCount: mesh.indices?.length ? Math.floor(mesh.indices.length / 3) : Math.floor((mesh.positions?.length || 0) / 9)
1357
+ },
1358
+ obstacles: [...this.obstacles.values()].map((descriptor) => structuredClone(descriptor))
1359
+ };
1360
+ }
1361
+ dispose() {
1362
+ this.disposed = true;
1363
+ this.revision += 1;
1364
+ this.backend.dispose?.();
1365
+ this.obstacles.clear();
1366
+ this.dirty = true;
1367
+ this.buildPromise = null;
1368
+ }
1369
+ };
1370
+ // modules/world/runtime/semantic/SemanticWorldView.js
1371
+ const spatialPredicates = /* @__PURE__ */ new Set([
1372
+ "ON",
1373
+ "NEAR",
1374
+ "INSIDE",
1375
+ "CONTAINS",
1376
+ "SUPPORTS"
1377
+ ]);
1378
+ function recordFor(runtime, id) {
1379
+ if (!runtime?.store?.get || runtime.store.has?.(id) === false) return null;
1380
+ try {
1381
+ return runtime.store.get(id) || null;
1382
+ } catch {
1383
+ return null;
1384
+ }
1385
+ }
1386
+ function unknown(base, reason) {
1387
+ return {
1388
+ ...base,
1389
+ status: "unknown",
1390
+ reason
1391
+ };
1392
+ }
1393
+ /** Mixed/native ON uses current solver contact, not a historical place receipt. */
1394
+ function physicalSupportFact(runtime, subject, target, surfaceId) {
1395
+ const nativeSubject = nativePhysicalTarget(runtime.entities, runtime.physics, subject);
1396
+ const nativeTarget = nativePhysicalTarget(runtime.entities, runtime.physics, target);
1397
+ const a = nativeSubject || recordFor(runtime, subject), b = nativeTarget || recordFor(runtime, target);
1398
+ if (!a || !b || a.active === false || b.active === false || !runtime.physics?.getPosition(subject) || !runtime.physics?.getPosition(target)) return {
1399
+ truth: "unknown",
1400
+ reason: "SUPPORT_PHYSICS_UNAVAILABLE"
1401
+ };
1402
+ if (a.state?.heldBy) return {
1403
+ truth: "false",
1404
+ reason: "OBJECT_HELD"
1405
+ };
1406
+ if (!runtime.physics.hasCapability?.("scene-query")) return {
1407
+ truth: "unknown",
1408
+ reason: "SUPPORT_PHYSICS_UNAVAILABLE"
1409
+ };
1410
+ const geometry = runtime.spatial.supportGeometry(subject, target, {
1411
+ surfaceId,
1412
+ tolerance: .03
1413
+ });
1414
+ if (!geometry.supported) return {
1415
+ truth: "false",
1416
+ reason: geometry.reason || "SUPPORT_GEOMETRY_MISMATCH"
1417
+ };
1418
+ const contacts = nativeSupportContacts(runtime.physics, subject, target);
1419
+ const motion = runtime.physics.getMotion(subject);
1420
+ if (!motion || !Number.isFinite(motion.linearSpeed) || !Number.isFinite(motion.angularSpeed)) return {
1421
+ truth: "unknown",
1422
+ reason: "SUPPORT_MOTION_UNAVAILABLE"
1423
+ };
1424
+ if (!contacts.length || motion.linearSpeed > .04 || motion.angularSpeed > .12) return {
1425
+ truth: "false",
1426
+ reason: !contacts.length ? "SUPPORT_CONTACT_MISSING" : "SUPPORT_MOVING"
1427
+ };
1428
+ return {
1429
+ truth: "true",
1430
+ source: "physics-support",
1431
+ evidenceKind: "solver-contact+spatial-geometry",
1432
+ evidence: {
1433
+ geometry,
1434
+ contacts: contacts.slice(0, 4),
1435
+ motion
1436
+ }
1437
+ };
1438
+ }
1439
+ var SemanticWorldView = class {
1440
+ constructor(runtime) {
1441
+ this.runtime = runtime;
1442
+ }
1443
+ entity(id) {
1444
+ const runtime = this.runtime;
1445
+ const physical = recordFor(runtime, id);
1446
+ const project = Boolean(runtime?.projectCapabilities?.has?.(id));
1447
+ if (physical) {
1448
+ const providers = [
1449
+ "runtime",
1450
+ ...project ? ["project"] : [],
1451
+ ...runtime?.thermal?.has?.(id) ? ["simulation"] : []
1452
+ ];
1453
+ return {
1454
+ exists: true,
1455
+ source: "runtime",
1456
+ ...providers.length > 1 ? { providers } : {}
1457
+ };
1458
+ }
1459
+ if (runtime?.affordances?.get?.(id)) return {
1460
+ exists: true,
1461
+ source: "environment"
1462
+ };
1463
+ if (project && runtime.projectCapabilities.attachmentOf?.(id) === "runtime") return {
1464
+ exists: false,
1465
+ source: "none",
1466
+ reason: "PROJECT_ATTACHMENT_TARGET_MISSING"
1467
+ };
1468
+ if (project) return {
1469
+ exists: true,
1470
+ source: "project",
1471
+ ...inspectNativePhysics(runtime, id) ? { providers: ["project", "native-physics"] } : {}
1472
+ };
1473
+ return {
1474
+ exists: false,
1475
+ source: "none",
1476
+ reason: "OBJECT_NOT_FOUND"
1477
+ };
1478
+ }
1479
+ state(targetId, stateKey, { source = null } = {}) {
1480
+ const owner = this.entity(targetId);
1481
+ const base = {
1482
+ kind: "state",
1483
+ targetId,
1484
+ stateKey,
1485
+ source: source || owner.source
1486
+ };
1487
+ if (!owner.exists) return unknown(base, owner.reason || "OBJECT_NOT_FOUND");
1488
+ const runtime = this.runtime;
1489
+ const readers = [];
1490
+ const record = recordFor(runtime, targetId);
1491
+ if (record) readers.push(["runtime", () => record.state]);
1492
+ const environment = runtime?.affordances?.get?.(targetId);
1493
+ if (environment) readers.push(["environment", () => {
1494
+ if (environment.kind === "text") {
1495
+ const error = /* @__PURE__ */ new Error("ENVIRONMENT_TEXT_REQUIRES_ACTOR_READ");
1496
+ error.code = "ENVIRONMENT_TEXT_REQUIRES_ACTOR_READ";
1497
+ throw error;
1498
+ }
1499
+ return environment.read?.();
1500
+ }]);
1501
+ if (runtime?.projectCapabilities?.has?.(targetId)) readers.push(["project", () => runtime.projectCapabilities.readState(targetId)]);
1502
+ if (inspectNativePhysics(runtime, targetId)) readers.push(["native-physics", () => inspectNativePhysics(runtime, targetId)?.state]);
1503
+ if (runtime?.thermal?.has?.(targetId)) readers.push(["simulation", () => runtime.thermal.readState(targetId)]);
1504
+ const selected = readers.filter(([provider]) => source == null || provider === source);
1505
+ if (!selected.length) return unknown(base, "STATE_PROVIDER_UNAVAILABLE");
1506
+ const found = [];
1507
+ for (const [provider, read] of selected) {
1508
+ let state;
1509
+ try {
1510
+ state = read();
1511
+ } catch (error) {
1512
+ return unknown({
1513
+ ...base,
1514
+ source: provider
1515
+ }, error?.code === "ENVIRONMENT_TEXT_REQUIRES_ACTOR_READ" ? error.code : "STATE_READ_FAILED");
1516
+ }
1517
+ if (state && typeof state === "object" && Object.hasOwn(state, stateKey) && state[stateKey] !== void 0) found.push({
1518
+ provider,
1519
+ value: state[stateKey]
1520
+ });
1521
+ }
1522
+ if (!found.length) return unknown(base, "STATE_NOT_OBSERVED");
1523
+ if (found.length > 1) return unknown({
1524
+ ...base,
1525
+ source: "multiple",
1526
+ providers: found.map((item) => item.provider)
1527
+ }, "STATE_PROVIDER_CONFLICT");
1528
+ return {
1529
+ ...base,
1530
+ source: found[0].provider,
1531
+ status: "known",
1532
+ value: structuredClone(found[0].value),
1533
+ evidenceKind: "owner-state"
1534
+ };
1535
+ }
1536
+ relation({ subject, predicate, object, objectAnyOf, surfaceId } = {}) {
1537
+ const targets = objectAnyOf || [object];
1538
+ const base = {
1539
+ kind: "relation",
1540
+ subject,
1541
+ predicate,
1542
+ ...objectAnyOf ? { objectAnyOf: [...objectAnyOf] } : { object },
1543
+ ...surfaceId ? { surfaceId } : {}
1544
+ };
1545
+ const graph = this.runtime?.sceneGraph;
1546
+ if (!graph?.list) return {
1547
+ ...base,
1548
+ truth: "unknown",
1549
+ source: "none",
1550
+ reason: "RELATION_GRAPH_UNAVAILABLE"
1551
+ };
1552
+ let unobservable = false;
1553
+ try {
1554
+ graph.update?.();
1555
+ for (const target of targets) {
1556
+ if (["ON", "SUPPORTS"].includes(predicate) && [subject, target].some((id) => this.runtime?.entities?.get?.(id)?.source === "native")) {
1557
+ const fact = physicalSupportFact(this.runtime, predicate === "ON" ? subject : target, predicate === "ON" ? target : subject, surfaceId);
1558
+ if (fact.truth === "true" || !objectAnyOf) return {
1559
+ ...base,
1560
+ source: "physics-support",
1561
+ ...fact
1562
+ };
1563
+ if (fact.truth === "unknown") unobservable = true;
1564
+ continue;
1565
+ }
1566
+ const edges = graph.list({
1567
+ subject,
1568
+ predicate,
1569
+ object: target
1570
+ });
1571
+ const matching = edges.find((edge) => !surfaceId || edge.meta?.surfaceId === surfaceId);
1572
+ if (matching) return {
1573
+ ...base,
1574
+ truth: "true",
1575
+ source: "scene-graph",
1576
+ evidenceKind: matching.meta?.evidence || (spatialPredicates.has(predicate) ? "spatial-relation" : "declared-relation"),
1577
+ evidence: structuredClone(matching)
1578
+ };
1579
+ const source = recordFor(this.runtime, subject), destination = recordFor(this.runtime, target);
1580
+ if (!(spatialPredicates.has(predicate) && typeof this.runtime?.spatial?.snapshot === "function" && source?.active !== false && destination?.active !== false && Boolean(source && destination)) && !(surfaceId && edges.length)) unobservable = true;
1581
+ }
1582
+ } catch {
1583
+ return {
1584
+ ...base,
1585
+ truth: "unknown",
1586
+ source: "scene-graph",
1587
+ reason: "RELATION_READ_FAILED"
1588
+ };
1589
+ }
1590
+ return unobservable ? {
1591
+ ...base,
1592
+ truth: "unknown",
1593
+ source: "scene-graph",
1594
+ reason: "RELATION_NOT_OBSERVED"
1595
+ } : {
1596
+ ...base,
1597
+ truth: "false",
1598
+ source: "scene-graph",
1599
+ reason: "RELATION_NOT_FOUND"
1600
+ };
1601
+ }
1602
+ };
1603
+ // modules/world/runtime/WorldCollisionSignature.js
1604
+ /** Compare effective collision shapes rather than visual geometry or material metadata. */
1605
+ const signature = (manifest) => JSON.stringify({
1606
+ body: manifest.physics?.body,
1607
+ colliders: manifest.physics?.colliders,
1608
+ parts: Object.fromEntries(Object.entries(manifest.parts || {}).sort(([a], [b]) => a.localeCompare(b)).map(([id, part]) => [id, {
1609
+ body: part.physics?.body,
1610
+ colliders: part.physics?.colliders,
1611
+ joint: part.joint
1612
+ }]))
1613
+ });
1614
+ const samePhysicalGeometry = (left, right) => signature(left) === signature(right);
1615
+ // modules/world/runtime/WorldCommands.js
1616
+ const round3 = (value) => Number(value.toFixed(3));
1617
+ const vec3Round = (value) => Array.isArray(value) ? value.map(round3) : value;
1618
+ const yawFromQuat = ([x, y, z, w]) => Math.atan2(2 * (w * y + x * z), 1 - 2 * (y * y + z * z));
1619
+ var WorldCommands = class {
1620
+ constructor(runtime) {
1621
+ if (!runtime) throw new TypeError("WorldCommands requires a WorldRuntime");
1622
+ this.runtime = runtime;
1623
+ }
1624
+ assertReady(command, batch) {
1625
+ this.runtime.assertWritable?.(batch);
1626
+ if (this.runtime.ready !== false) return;
1627
+ if (this.runtime.sceneGraph && this.runtime.history && this.runtime.navigation && this.runtime.locomotion && this.runtime.interactions) return;
1628
+ const error = /* @__PURE__ */ new Error(`World command requires an initialized WorldRuntime: ${command}`);
1629
+ error.code = "WORLD_COMMAND_NOT_READY";
1630
+ error.command = command;
1631
+ throw error;
1632
+ }
1633
+ async spawn(assetId, options = {}) {
1634
+ this.assertReady("spawn");
1635
+ const admission = assetAdmission(this.runtime.assetModule.getManifest(assetId));
1636
+ if (admission.status === "rejected") return {
1637
+ status: "asset-rejected",
1638
+ assetId,
1639
+ admission
1640
+ };
1641
+ const id = await this.runtime.spawn(assetId, options);
1642
+ return admission.status === "ready" ? id : {
1643
+ status: "asset-provisional",
1644
+ id,
1645
+ assetId,
1646
+ admission
1647
+ };
1648
+ }
1649
+ async replaceAsset(id, assetId, batch = null) {
1650
+ this.assertReady("replaceAsset", batch);
1651
+ const record = this.runtime.store.get(id);
1652
+ if (record.state?.heldBy) throw Object.assign(/* @__PURE__ */ new Error("Put down the object before upgrading its asset"), { code: "ASSET_INSTANCE_HELD" });
1653
+ if (record.manifest.type === "agent") throw Object.assign(/* @__PURE__ */ new Error("Agent embodiment upgrades are not supported"), { code: "ASSET_UPGRADE_AGENT_UNSUPPORTED" });
1654
+ const manifest = this.runtime.assetModule.getManifest(assetId);
1655
+ if (assetAdmission(manifest).status !== "ready") throw Object.assign(/* @__PURE__ */ new Error("Asset is not ready"), { code: "ASSET_NOT_READY" });
1656
+ const pose = {
1657
+ id,
1658
+ position: record.object.position.toArray(),
1659
+ quaternion: record.object.quaternion.toArray(),
1660
+ scale: record.object.scale.x
1661
+ };
1662
+ const previousAssetId = record.assetId;
1663
+ return this.runtime.mutate("asset:replace", async () => {
1664
+ const check = samePhysicalGeometry(manifest, record.manifest) || manifest.capabilityLevel === "visual" ? {
1665
+ checked: true,
1666
+ clear: true
1667
+ } : this.runtime.physics.checkManifestPose(physicsManifestForUniformScale(manifest, pose.scale), pose.position, {
1668
+ quaternion: pose.quaternion,
1669
+ excludeIds: [id]
1670
+ });
1671
+ if (!check.checked || !check.clear) throw Object.assign(/* @__PURE__ */ new Error("New asset does not fit at the current pose"), { code: "ASSET_UPGRADE_PLACEMENT_BLOCKED" });
1672
+ this.remove(id, { replacing: true });
1673
+ await this.spawn(assetId, pose);
1674
+ if (!(await this.runtime.navigation.ensureCurrent()).success || manifest.capabilityLevel !== "visual" && !this.runtime.physics.getPosition(id)) throw Object.assign(/* @__PURE__ */ new Error("New entity failed runtime registration"), { code: "ASSET_UPGRADE_FAILED" });
1675
+ return {
1676
+ status: "asset-instance-updated",
1677
+ id,
1678
+ assetId,
1679
+ previousAssetId,
1680
+ stateReset: true
1681
+ };
1682
+ }, {}, { batch });
1683
+ }
1684
+ transform(id, transform = {}, options = {}) {
1685
+ this.assertReady("transform");
1686
+ if (this.runtime.store.get(id).state?.heldBy || this.runtime.interactions?.isHeld?.(id) || this.runtime.interactions?.carry?.agentHeld?.has(id)) throw Object.assign(/* @__PURE__ */ new Error("Put down the object before editing"), { code: "OBJECT_HELD" });
1687
+ return this.runtime.applyObjectTransform(id, transform, options);
1688
+ }
1689
+ beginTransform(id) {
1690
+ this.assertReady("beginTransform");
1691
+ if (this.runtime.store.get(id).state?.heldBy || this.runtime.interactions?.isHeld?.(id) || this.runtime.interactions?.carry?.agentHeld?.has(id)) throw Object.assign(/* @__PURE__ */ new Error("Put down the object before editing"), { code: "OBJECT_HELD" });
1692
+ return this.runtime.physics.beginTransform(id);
1693
+ }
1694
+ endTransform(id) {
1695
+ this.assertReady("endTransform");
1696
+ return this.runtime.physics.endTransform(id);
1697
+ }
1698
+ setHumanViewPose(pose) {
1699
+ this.assertReady("setHumanViewPose");
1700
+ return this.runtime.interactions.setHumanViewPose(pose);
1701
+ }
1702
+ async duplicate(id) {
1703
+ this.assertReady("duplicate");
1704
+ const assetId = this.runtime.store.get(id).assetId;
1705
+ const admission = assetAdmission(this.runtime.assetModule.getManifest(assetId));
1706
+ if (admission.status === "rejected") return {
1707
+ status: "asset-rejected",
1708
+ assetId,
1709
+ sourceId: id,
1710
+ admission
1711
+ };
1712
+ const duplicateId = await this.runtime.duplicate(id);
1713
+ return admission.status === "ready" ? duplicateId : {
1714
+ status: "asset-provisional",
1715
+ id: duplicateId,
1716
+ assetId,
1717
+ sourceId: id,
1718
+ admission
1719
+ };
1720
+ }
1721
+ remove(id, options = {}) {
1722
+ this.assertReady("remove");
1723
+ if (this.runtime.store.get(id).state?.heldBy || this.runtime.interactions?.isHeld?.(id) || this.runtime.interactions?.carry?.agentHeld?.has(id)) throw Object.assign(/* @__PURE__ */ new Error("Put down the object before editing"), { code: "OBJECT_HELD" });
1724
+ return this.runtime.remove(id, options);
1725
+ }
1726
+ navigate(id, end, options = {}) {
1727
+ this.assertReady("navigate");
1728
+ return this.runtime.locomotion.navigate(id, end, options);
1729
+ }
1730
+ async moveForward(id, { distance = .8, speed } = {}) {
1731
+ this.assertReady("moveForward");
1732
+ if (!this.runtime.store?.has?.(id)) {
1733
+ const error = /* @__PURE__ */ new Error(`Object not found: ${id}`);
1734
+ error.code = "OBJECT_NOT_FOUND";
1735
+ throw error;
1736
+ }
1737
+ if (!Number.isFinite(distance) || distance <= 0 || distance > 4) {
1738
+ const error = /* @__PURE__ */ new Error("moveForward distance must be within (0, 4]");
1739
+ error.code = "MOVE_FORWARD_DISTANCE_INVALID";
1740
+ throw error;
1741
+ }
1742
+ const record = this.runtime.store.get(id);
1743
+ if (record.manifest?.type !== "agent" || !record.manifest.actions?.includes("navigate")) {
1744
+ const error = /* @__PURE__ */ new Error(`Object is not a navigable agent: ${id}`);
1745
+ error.code = "NOT_NAVIGABLE_AGENT";
1746
+ throw error;
1747
+ }
1748
+ if (record.manifest.physics?.body !== "kinematic") {
1749
+ const error = /* @__PURE__ */ new Error(`Navigable agent must use a kinematic body: ${id}`);
1750
+ error.code = "NAVIGABLE_BODY_INVALID";
1751
+ throw error;
1752
+ }
1753
+ const start = this.runtime.physics?.getPosition?.(id);
1754
+ if (!start) {
1755
+ const error = /* @__PURE__ */ new Error(`Physics body not available: ${id}`);
1756
+ error.code = "PHYSICS_BODY_UNAVAILABLE";
1757
+ throw error;
1758
+ }
1759
+ const rotation = this.runtime.physics?.getRotation?.(id);
1760
+ if (!Array.isArray(rotation) || rotation.length !== 4 || !rotation.every(Number.isFinite)) {
1761
+ const error = /* @__PURE__ */ new Error(`Agent rotation unavailable: ${id}`);
1762
+ error.code = "AGENT_ROTATION_UNAVAILABLE";
1763
+ throw error;
1764
+ }
1765
+ const yaw = yawFromQuat(rotation);
1766
+ const forward = [
1767
+ -Math.sin(yaw),
1768
+ 0,
1769
+ -Math.cos(yaw)
1770
+ ];
1771
+ const end = [
1772
+ start[0] + forward[0] * distance,
1773
+ start[1],
1774
+ start[2] + forward[2] * distance
1775
+ ];
1776
+ const result = await this.runtime.locomotion.navigate(id, end, { speed });
1777
+ const position = Array.isArray(result?.position) ? result.position : null;
1778
+ const moved = position ? Math.hypot(position[0] - start[0], position[2] - start[2]) : result?.status === "arrived" ? distance : 0;
1779
+ const base = {
1780
+ ...result,
1781
+ skill: "moveForward",
1782
+ start: vec3Round(start),
1783
+ end: vec3Round(end),
1784
+ distance,
1785
+ yaw: round3(yaw),
1786
+ forward: vec3Round(forward),
1787
+ moved: round3(moved)
1788
+ };
1789
+ if (result?.status === "arrived" && moved < Math.max(.05, distance * .35)) return {
1790
+ ...base,
1791
+ status: "blocked",
1792
+ reason: "INSUFFICIENT_FORWARD_DISPLACEMENT"
1793
+ };
1794
+ return base;
1795
+ }
1796
+ activateEnvironmentInteraction(interactionId, { actorId = null, requireReach = true } = {}) {
1797
+ this.assertReady("activateEnvironmentInteraction");
1798
+ const runtime = this.runtime;
1799
+ const item = (runtime.environment?.interactions || []).find((entry) => entry.id === interactionId);
1800
+ if (!item) return {
1801
+ status: "interaction-not-found",
1802
+ interactionId,
1803
+ environmentId: runtime.environment?.id || null
1804
+ };
1805
+ if (typeof item.activate !== "function") return {
1806
+ status: "interaction-not-executable",
1807
+ interactionId,
1808
+ label: item.label || null
1809
+ };
1810
+ const position = (() => {
1811
+ const object = item.object;
1812
+ if (!object) return null;
1813
+ if (object.isObject3D) {
1814
+ object.updateWorldMatrix?.(true, false);
1815
+ const elements = object.matrixWorld?.elements;
1816
+ if (elements) return [
1817
+ elements[12],
1818
+ elements[13],
1819
+ elements[14]
1820
+ ];
1821
+ }
1822
+ return null;
1823
+ })();
1824
+ if (item.contractId) {
1825
+ const contract = runtime.affordances?.get?.(item.contractId);
1826
+ if (contract) {
1827
+ const state = contract.read?.() || {};
1828
+ let action = null;
1829
+ if (contract.kind === "book") action = state.out ? "return" : "pull_out";
1830
+ else if (contract.kind === "switch") action = state.on ? "turn_off" : "turn_on";
1831
+ else if (state.requestedOpen === true || state.out === true) action = "close";
1832
+ else if (state.requestedOpen === false || state.out === false) action = "open";
1833
+ if (action && contract.actions?.includes(action)) {
1834
+ const response = runtime.affordances.execute({
1835
+ targetId: item.contractId,
1836
+ action,
1837
+ actorId
1838
+ }, {});
1839
+ const withNativeId = (value) => value?.status === "world-action-blocked" ? {
1840
+ ...value,
1841
+ interactionId
1842
+ } : value;
1843
+ return response?.then ? response.then(withNativeId) : withNativeId(response);
1844
+ }
1845
+ }
1846
+ }
1847
+ if (requireReach && actorId) {
1848
+ const feet = runtime.physics?.getPosition?.(actorId);
1849
+ if (!feet) return {
1850
+ status: "world-action-blocked",
1851
+ interactionId,
1852
+ reason: "ACTOR_PHYSICS_UNAVAILABLE",
1853
+ actorId
1854
+ };
1855
+ if (!position) return {
1856
+ status: "world-action-blocked",
1857
+ interactionId,
1858
+ reason: "INTERACTION_POSITION_UNAVAILABLE",
1859
+ actorId
1860
+ };
1861
+ const distance = Math.hypot(position[0] - feet[0], position[1] - feet[1], position[2] - feet[2]);
1862
+ if (distance > 1.5) return {
1863
+ status: "world-action-blocked",
1864
+ interactionId,
1865
+ reason: "OUT_OF_REACH",
1866
+ actorId,
1867
+ distance: round3(distance),
1868
+ maxDistance: 1.5,
1869
+ position: vec3Round(position)
1870
+ };
1871
+ if (runtime.physics?.hasCapability?.("scene-query") && runtime.physics.raycast) {
1872
+ const origin = [
1873
+ feet[0],
1874
+ feet[1] + 1.2,
1875
+ feet[2]
1876
+ ];
1877
+ const hit = runtime.physics.raycast(origin, position, { excludeId: actorId });
1878
+ if (hit && hit.distance < distance - .12) return {
1879
+ status: "world-action-blocked",
1880
+ interactionId,
1881
+ reason: "OCCLUDED",
1882
+ actorId,
1883
+ blocker: hit.provenance || { id: hit.id },
1884
+ distance: round3(distance)
1885
+ };
1886
+ }
1887
+ }
1888
+ item.activate();
1889
+ return {
1890
+ status: "environment-interaction-activated",
1891
+ interactionId,
1892
+ label: item.label || null,
1893
+ contractId: item.contractId || null,
1894
+ environmentId: runtime.environment?.id || null,
1895
+ position: vec3Round(position),
1896
+ via: "native-activate",
1897
+ provisional: true,
1898
+ verification: "native-provisional",
1899
+ evidenceKind: "animated-transform",
1900
+ physicsVerified: false,
1901
+ note: "Native Three.js scene interaction; not force-verified articulated asset physics."
1902
+ };
1903
+ }
1904
+ async resolveEnvironmentApproach(target, start, { radii = [
1905
+ .9,
1906
+ 1.2,
1907
+ 1.5,
1908
+ 1.8
1909
+ ], samples = 16, maxSnapDistance = .75 } = {}) {
1910
+ const navigation = this.runtime.navigation;
1911
+ if (!navigation?.findPath || !Array.isArray(target) || !Array.isArray(start)) return {
1912
+ reachable: false,
1913
+ reason: "NAVIGATION_UNAVAILABLE",
1914
+ candidates: 0
1915
+ };
1916
+ const candidates = [];
1917
+ for (const radius of radii) {
1918
+ for (let i = 0; i < samples; i += 1) {
1919
+ const angle = i / samples * Math.PI * 2;
1920
+ candidates.push([
1921
+ target[0] + Math.sin(angle) * radius,
1922
+ target[1],
1923
+ target[2] + Math.cos(angle) * radius
1924
+ ]);
1925
+ }
1926
+ candidates.push([
1927
+ target[0] + radius,
1928
+ target[1],
1929
+ target[2]
1930
+ ]);
1931
+ candidates.push([
1932
+ target[0] - radius,
1933
+ target[1],
1934
+ target[2]
1935
+ ]);
1936
+ candidates.push([
1937
+ target[0],
1938
+ target[1],
1939
+ target[2] + radius
1940
+ ]);
1941
+ candidates.push([
1942
+ target[0],
1943
+ target[1],
1944
+ target[2] - radius
1945
+ ]);
1946
+ }
1947
+ const tried = [];
1948
+ const budget = Math.min(candidates.length, 28);
1949
+ for (let index = 0; index < budget; index += 1) {
1950
+ const end = candidates[index];
1951
+ const route = await navigation.findPath(start, end, {
1952
+ maxSnapDistance,
1953
+ endTolerance: .6
1954
+ });
1955
+ tried.push({
1956
+ end: vec3Round(end),
1957
+ reachable: route?.reachable === true,
1958
+ reason: route?.reason || null,
1959
+ cost: route?.cost ?? null
1960
+ });
1961
+ if (route?.reachable) return {
1962
+ reachable: true,
1963
+ end,
1964
+ route,
1965
+ tried,
1966
+ candidates: candidates.length
1967
+ };
1968
+ }
1969
+ return {
1970
+ reachable: false,
1971
+ reason: "NO_APPROACH_POSE",
1972
+ tried,
1973
+ candidates: candidates.length
1974
+ };
1975
+ }
1976
+ async findEnvironmentInteractApproach(interactionId, { actorId = null } = {}) {
1977
+ this.assertReady("findEnvironmentInteractApproach");
1978
+ const runtime = this.runtime;
1979
+ const item = (runtime.environment?.interactions || []).find((entry) => entry.id === interactionId);
1980
+ if (!item) return {
1981
+ status: "interaction-not-found",
1982
+ interactionId
1983
+ };
1984
+ const target = (() => {
1985
+ const object = item.object;
1986
+ if (!object?.isObject3D) return null;
1987
+ object.updateWorldMatrix?.(true, false);
1988
+ const elements = object.matrixWorld?.elements;
1989
+ return elements ? [
1990
+ elements[12],
1991
+ elements[13],
1992
+ elements[14]
1993
+ ] : null;
1994
+ })();
1995
+ if (!target) return {
1996
+ status: "interaction-position-unavailable",
1997
+ interactionId
1998
+ };
1999
+ const start = actorId ? runtime.physics?.getPosition?.(actorId) : null;
2000
+ if (!start) return {
2001
+ status: "actor-required-or-unavailable",
2002
+ interactionId,
2003
+ actorId
2004
+ };
2005
+ const approach = await this.resolveEnvironmentApproach(target, start);
2006
+ return {
2007
+ status: approach.reachable ? "approach-ready" : "approach-unreachable",
2008
+ interactionId,
2009
+ label: item.label || null,
2010
+ contractId: item.contractId || null,
2011
+ actorId,
2012
+ start: vec3Round(start),
2013
+ target: vec3Round(target),
2014
+ approach: approach.reachable ? vec3Round(approach.end) : null,
2015
+ distance: round3(Math.hypot(target[0] - start[0], target[1] - start[1], target[2] - start[2])),
2016
+ reason: approach.reachable ? null : approach.reason || "NO_APPROACH_POSE",
2017
+ tried: approach.tried || []
2018
+ };
2019
+ }
2020
+ async approachAndActivateEnvironmentInteract(interactionId, { actorId = null, speed } = {}) {
2021
+ this.assertReady("approachAndActivateEnvironmentInteract");
2022
+ const runtime = this.runtime;
2023
+ const skill = "approachAndActivateEnvironmentInteract";
2024
+ const item = (runtime.environment?.interactions || []).find((entry) => entry.id === interactionId);
2025
+ if (!item) return {
2026
+ status: "interaction-not-found",
2027
+ skill,
2028
+ interactionId,
2029
+ environmentId: runtime.environment?.id || null
2030
+ };
2031
+ if (typeof item.activate !== "function") return {
2032
+ status: "interaction-not-executable",
2033
+ skill,
2034
+ interactionId,
2035
+ label: item.label || null
2036
+ };
2037
+ if (!actorId) return {
2038
+ status: "actor-required",
2039
+ skill,
2040
+ interactionId
2041
+ };
2042
+ const start = runtime.physics?.getPosition?.(actorId);
2043
+ if (!start) return {
2044
+ status: "world-action-blocked",
2045
+ skill,
2046
+ interactionId,
2047
+ reason: "ACTOR_PHYSICS_UNAVAILABLE",
2048
+ actorId
2049
+ };
2050
+ const target = (() => {
2051
+ const object = item.object;
2052
+ if (!object?.isObject3D) return null;
2053
+ object.updateWorldMatrix?.(true, false);
2054
+ const elements = object.matrixWorld?.elements;
2055
+ return elements ? [
2056
+ elements[12],
2057
+ elements[13],
2058
+ elements[14]
2059
+ ] : null;
2060
+ })();
2061
+ if (!target) return {
2062
+ status: "world-action-blocked",
2063
+ skill,
2064
+ interactionId,
2065
+ reason: "INTERACTION_POSITION_UNAVAILABLE",
2066
+ actorId
2067
+ };
2068
+ const distanceToTarget = Math.hypot(target[0] - start[0], target[1] - start[1], target[2] - start[2]);
2069
+ if (distanceToTarget <= 1.5) {
2070
+ const activation = await this.activateEnvironmentInteraction(interactionId, { actorId });
2071
+ runtime.navigation?.invalidate?.("environment-interaction-activated");
2072
+ const navigationBuild = runtime.navigation?.ensureBuilt ? await runtime.navigation.ensureBuilt() : null;
2073
+ return {
2074
+ ...activation,
2075
+ skill,
2076
+ phase: "activated",
2077
+ start: vec3Round(start),
2078
+ target: vec3Round(target),
2079
+ distance: round3(distanceToTarget),
2080
+ navigated: false,
2081
+ navigationInvalidated: true,
2082
+ navigationBuild: navigationBuild ? {
2083
+ success: navigationBuild.success === true,
2084
+ buildVersion: navigationBuild.buildVersion ?? null,
2085
+ code: navigationBuild.code || null
2086
+ } : null,
2087
+ nextStepHint: item.contractId ? "NavMesh rebuilt after door/path change; call navigateTo/findPath on a fresh planning round before entering or climbing." : "Native activation does not rebuild NavMesh by itself."
2088
+ };
2089
+ }
2090
+ const approach = await this.resolveEnvironmentApproach(target, start);
2091
+ if (!approach.reachable) return {
2092
+ status: "unreachable",
2093
+ skill,
2094
+ interactionId,
2095
+ label: item.label || null,
2096
+ actorId,
2097
+ start: vec3Round(start),
2098
+ target: vec3Round(target),
2099
+ distance: round3(distanceToTarget),
2100
+ reason: approach.reason || "NO_PATH_TO_ENVIRONMENT_INTERACTION",
2101
+ tried: approach.tried || []
2102
+ };
2103
+ const end = approach.end;
2104
+ const navResult = await runtime.locomotion.navigate(actorId, end, { speed });
2105
+ if (navResult?.status !== "arrived") return {
2106
+ ...navResult,
2107
+ skill,
2108
+ phase: "approach",
2109
+ interactionId,
2110
+ label: item.label || null,
2111
+ target: vec3Round(target),
2112
+ approach: vec3Round(end)
2113
+ };
2114
+ const activation = await this.activateEnvironmentInteraction(interactionId, { actorId });
2115
+ runtime.navigation?.invalidate?.("environment-interaction-activated");
2116
+ const navigationBuild = runtime.navigation?.ensureBuilt ? await runtime.navigation.ensureBuilt() : null;
2117
+ return {
2118
+ ...activation,
2119
+ skill,
2120
+ phase: "activated",
2121
+ start: vec3Round(start),
2122
+ approach: vec3Round(end),
2123
+ target: vec3Round(target),
2124
+ navigated: true,
2125
+ navigationInvalidated: true,
2126
+ navigationBuild: navigationBuild ? {
2127
+ success: navigationBuild.success === true,
2128
+ buildVersion: navigationBuild.buildVersion ?? null,
2129
+ code: navigationBuild.code || null
2130
+ } : null,
2131
+ nextStepHint: item.contractId ? "NavMesh rebuilt after door/path change; fresh replan then navigateTo/findPath before entering or going upstairs." : "Native activation does not rebuild NavMesh by itself."
2132
+ };
2133
+ }
2134
+ pickup(id) {
2135
+ this.assertReady("pickup");
2136
+ return this.runtime.interactions.pickup(id);
2137
+ }
2138
+ drop(id) {
2139
+ this.assertReady("drop");
2140
+ return this.runtime.interactions.drop(id);
2141
+ }
2142
+ place(id, targetId, options = {}) {
2143
+ this.assertReady("place");
2144
+ return this.runtime.interactions.place(id, targetId, options);
2145
+ }
2146
+ setArticulationAction(id, action, options = {}) {
2147
+ this.assertReady("setArticulationAction");
2148
+ return this.runtime.interactions.setArticulationAction(id, action, options);
2149
+ }
2150
+ approachAndInteract(actorId, targetId, action, options = {}) {
2151
+ this.assertReady("approachAndInteract");
2152
+ return this.runtime.interactions.approachAndInteract(actorId, targetId, action, options);
2153
+ }
2154
+ approachAndPickup(actorId, targetId, options = {}) {
2155
+ this.assertReady("approachAndPickup");
2156
+ return this.runtime.interactions.approachAndPickup(actorId, targetId, options);
2157
+ }
2158
+ approachAndPlace(actorId, supportId, options = {}) {
2159
+ this.assertReady("approachAndPlace");
2160
+ return this.runtime.interactions.approachAndPlace(actorId, supportId, options);
2161
+ }
2162
+ dropHeld(actorId) {
2163
+ this.assertReady("dropHeld");
2164
+ return this.runtime.interactions.dropHeld(actorId);
2165
+ }
2166
+ markRecoveryHeld(actorId, details) {
2167
+ this.assertReady("markRecoveryHeld");
2168
+ return this.runtime.interactions.markRecoveryHeld(actorId, details);
2169
+ }
2170
+ cleanupRecoveryBlocker(actorId, targetId, options = {}) {
2171
+ this.assertReady("cleanupRecoveryBlocker");
2172
+ return this.runtime.interactions.cleanupRecoveryBlocker(actorId, targetId, options);
2173
+ }
2174
+ applyStateTransition(id, stateKey, value, meta = {}) {
2175
+ this.assertReady("applyStateTransition");
2176
+ return this.runtime.applyStateTransition(id, stateKey, value, meta);
2177
+ }
2178
+ executeAffordance(args = {}, options = {}) {
2179
+ this.assertReady("executeAffordance");
2180
+ return options.approach ? this.runtime.affordances.approachAndExecute(args) : this.runtime.affordances.execute(args, options);
2181
+ }
2182
+ repair(report, options = {}) {
2183
+ this.assertReady("repair");
2184
+ return this.runtime.repair.repair(report, options);
2185
+ }
2186
+ syncAssetVerification(assetId, manifest) {
2187
+ let updated = 0;
2188
+ for (const record of this.runtime.store?.values?.() || []) {
2189
+ if (record.assetId !== assetId) continue;
2190
+ record.manifest.verification = structuredClone(manifest.verification || {});
2191
+ if (manifest.compiler?.quality && record.manifest.compiler) record.manifest.compiler.quality = structuredClone(manifest.compiler.quality);
2192
+ if (record.object?.userData?.manifest) {
2193
+ record.object.userData.manifest.verification = structuredClone(record.manifest.verification);
2194
+ if (record.manifest.compiler?.quality && record.object.userData.manifest.compiler) record.object.userData.manifest.compiler.quality = structuredClone(record.manifest.compiler.quality);
2195
+ }
2196
+ updated += 1;
2197
+ }
2198
+ return {
2199
+ status: "asset-verification-synced",
2200
+ assetId,
2201
+ instances: updated
2202
+ };
2203
+ }
2204
+ };
2205
+ export { rigidBodyActions as _, compileInteractionContract as a, clearInteractionEvidenceForTarget as c, inspectNativePhysics as d, nativeManipulationActions as f, manipulationParameters as g, nativeSupportContacts as h, navigationRecoveryCandidate as i, getInteractionEvidence as l, nativePhysicalTarget as m, SemanticWorldView as n, getInteractionContract as o, nativeCarryRecord as p, NavigationSystem as r, verifyInteractionResult as s, WorldCommands as t, recordInteractionEvidence as u };
2206
+
2207
+ //# sourceMappingURL=WorldCommands-Debj7V4L.js.map