agentscape3d-engine 0.0.0-stage → 1.0.0-beta.2

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 (396) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +19 -2
  3. package/cli.mjs +53 -0
  4. package/dist/AssetCompiler-A99wKf7H.js +2424 -0
  5. package/dist/AssetCompiler-A99wKf7H.js.map +1 -0
  6. package/dist/AssetInputContracts-uKYeQu-X.js +245 -0
  7. package/dist/AssetInputContracts-uKYeQu-X.js.map +1 -0
  8. package/dist/AssetRecipe-DCaLLXvG.js +67 -0
  9. package/dist/AssetRecipe-DCaLLXvG.js.map +1 -0
  10. package/dist/BrowserCodeWorker.js +53850 -0
  11. package/dist/BrowserCodeWorker.js.map +1 -0
  12. package/dist/KinematicHypothesisScreen-4v7GBwdv.js +241 -0
  13. package/dist/KinematicHypothesisScreen-4v7GBwdv.js.map +1 -0
  14. package/dist/SceneSerializer-CLCzQjL_.js +350 -0
  15. package/dist/SceneSerializer-CLCzQjL_.js.map +1 -0
  16. package/dist/StylePack-CD_BC-Mv.js +6317 -0
  17. package/dist/StylePack-CD_BC-Mv.js.map +1 -0
  18. package/dist/WorldArchive-dYf1OpSe.js +417 -0
  19. package/dist/WorldArchive-dYf1OpSe.js.map +1 -0
  20. package/dist/WorldIO-Dqz4MqTQ.js +149 -0
  21. package/dist/WorldIO-Dqz4MqTQ.js.map +1 -0
  22. package/dist/blankWorld-OoOvN_IK.js +75 -0
  23. package/dist/blankWorld-OoOvN_IK.js.map +1 -0
  24. package/dist/core.d.ts +68 -0
  25. package/dist/core.js +209 -0
  26. package/dist/core.js.map +1 -0
  27. package/dist/disposeObject3D-B3HCflvO.js +128 -0
  28. package/dist/disposeObject3D-B3HCflvO.js.map +1 -0
  29. package/dist/environments-B1WaICAN.js +4197 -0
  30. package/dist/environments-B1WaICAN.js.map +1 -0
  31. package/dist/gltfIO-BMK1hc2D.js +9 -0
  32. package/dist/gltfIO-BMK1hc2D.js.map +1 -0
  33. package/dist/grandUrbanBlock-Bdjgc6ZT.js +515 -0
  34. package/dist/grandUrbanBlock-Bdjgc6ZT.js.map +1 -0
  35. package/dist/index.d.ts +275 -0
  36. package/dist/index.js +16239 -0
  37. package/dist/index.js.map +1 -0
  38. package/dist/magicCabin-DPQi_jh-.js +11019 -0
  39. package/dist/magicCabin-DPQi_jh-.js.map +1 -0
  40. package/dist/mcp.d.ts +2 -0
  41. package/dist/mcp.js +1 -0
  42. package/dist/monumentHall-IOLbRZQC.js +403 -0
  43. package/dist/monumentHall-IOLbRZQC.js.map +1 -0
  44. package/dist/node.d.ts +16 -0
  45. package/dist/node.js +26 -0
  46. package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
  47. package/dist/ruinedCourtyard-BtaF_aOi.js +696 -0
  48. package/dist/ruinedCourtyard-BtaF_aOi.js.map +1 -0
  49. package/dist/runtime/application/AgentTools.js +28 -0
  50. package/dist/runtime/application/README.md +14 -0
  51. package/dist/runtime/application/agent/ProgressiveAgentTools.js +92 -0
  52. package/dist/runtime/application/agent/StudioMcpAllowlist.js +8 -0
  53. package/dist/runtime/application/buildTaskObservation.js +117 -0
  54. package/dist/runtime/application/code-execution/AuthoringSandboxEntry.js +46 -0
  55. package/dist/runtime/application/code-execution/BrowserCodeExecutor.js +35 -0
  56. package/dist/runtime/application/code-execution/BrowserCodeWorker.js +17 -0
  57. package/dist/runtime/application/code-execution/RemoteAuthoringDocument.js +72 -0
  58. package/dist/runtime/application/createSession.js +66 -0
  59. package/dist/runtime/application/createWorldAuthoringContext.js +400 -0
  60. package/dist/runtime/application/generation/GenerationOrchestrator.js +629 -0
  61. package/dist/runtime/application/generation/GenerationRuntime.js +214 -0
  62. package/dist/runtime/application/generation/PromptHybridWorldOrchestrator.js +285 -0
  63. package/dist/runtime/application/native-scene/CodeProject.js +119 -0
  64. package/dist/runtime/application/native-scene/CodeProjectModules.js +128 -0
  65. package/dist/runtime/application/native-scene/NativeEnvironmentGeometry.js +62 -0
  66. package/dist/runtime/application/native-scene/NativeOverlayCheckpoint.js +127 -0
  67. package/dist/runtime/application/native-scene/NativeRenderDiscovery.js +51 -0
  68. package/dist/runtime/application/native-scene/NativeSceneHost.js +319 -0
  69. package/dist/runtime/application/native-scene/NativeSceneOverlay.js +116 -0
  70. package/dist/runtime/application/native-scene/NativeThreeModule.js +16 -0
  71. package/dist/runtime/application/object-forge/SceneObjectForge.js +232 -0
  72. package/dist/runtime/application/programmatic-assets/ProgrammaticAssetBuilder.js +59 -0
  73. package/dist/runtime/application/programmatic-assets/ProgrammaticAssetContract.js +22 -0
  74. package/dist/runtime/application/programmatic-assets/ThreeCodeAsset.js +40 -0
  75. package/dist/runtime/application/scene/CapabilityResolver.js +79 -0
  76. package/dist/runtime/application/scene/RequestWindow.js +54 -0
  77. package/dist/runtime/application/scene/SceneAgentTools.js +21 -0
  78. package/dist/runtime/application/scene/SceneContracts.js +45 -0
  79. package/dist/runtime/application/scene/SceneEditService.js +144 -0
  80. package/dist/runtime/application/scene/SceneFacade.js +261 -0
  81. package/dist/runtime/application/scene/SceneInteractionAdapters.js +40 -0
  82. package/dist/runtime/application/scene/SceneJobController.js +229 -0
  83. package/dist/runtime/application/scene/SceneLifecycle.js +57 -0
  84. package/dist/runtime/application/scene/ScenePackage.js +162 -0
  85. package/dist/runtime/application/scene/ScenePersistence.js +50 -0
  86. package/dist/runtime/application/scene/SceneProject.js +95 -0
  87. package/dist/runtime/application/scene/SceneSkillNames.js +5 -0
  88. package/dist/runtime/application/scene/StarterScene.js +56 -0
  89. package/dist/runtime/application/scene/WorldArchive.js +87 -0
  90. package/dist/runtime/application/scene/WorldDirectory.js +20 -0
  91. package/dist/runtime/application/scene/WorldDocument.js +74 -0
  92. package/dist/runtime/application/scene/WorldIO.js +103 -0
  93. package/dist/runtime/application/scene/WorldStorage.js +137 -0
  94. package/dist/runtime/application/skills/SkillRegistry.js +189 -0
  95. package/dist/runtime/application/skills/packs/acceptanceSkills.js +32 -0
  96. package/dist/runtime/application/skills/packs/affordanceSkills.js +36 -0
  97. package/dist/runtime/application/skills/packs/assetSkills.js +46 -0
  98. package/dist/runtime/application/skills/packs/authoringSkills.js +16 -0
  99. package/dist/runtime/application/skills/packs/batchSkills.js +22 -0
  100. package/dist/runtime/application/skills/packs/codeSkills.js +106 -0
  101. package/dist/runtime/application/skills/packs/generationSkills.js +45 -0
  102. package/dist/runtime/application/skills/packs/interactionSkills.js +46 -0
  103. package/dist/runtime/application/skills/packs/recoverySkills.js +80 -0
  104. package/dist/runtime/application/skills/packs/sceneSkills.js +24 -0
  105. package/dist/runtime/application/skills/packs/spatialSkills.js +35 -0
  106. package/dist/runtime/application/skills/packs/verificationSkills.js +14 -0
  107. package/dist/runtime/application/skills/packs/worldSkills.js +45 -0
  108. package/dist/runtime/application/skills/registerCoreSkills.js +31 -0
  109. package/dist/runtime/application/skills/skillPrimitives.js +4 -0
  110. package/dist/runtime/application/tasks/CabinetCupTask.js +76 -0
  111. package/dist/runtime/application/tasks.jsonl +67 -0
  112. package/dist/runtime/application/world-authoring/AuthoringAssetProducer.js +42 -0
  113. package/dist/runtime/application/world-authoring/AuthoringDiff.js +149 -0
  114. package/dist/runtime/application/world-authoring/AuthoringDocument.js +825 -0
  115. package/dist/runtime/application/world-authoring/AuthoringExecutionHost.js +109 -0
  116. package/dist/runtime/application/world-authoring/AuthoringIdentity.js +17 -0
  117. package/dist/runtime/application/world-authoring/AuthoringModelResolver.js +29 -0
  118. package/dist/runtime/application/world-authoring/AuthoringPatch.js +118 -0
  119. package/dist/runtime/application/world-authoring/AuthoringPromotionController.js +334 -0
  120. package/dist/runtime/application/world-authoring/AuthoringPromotionSource.js +126 -0
  121. package/dist/runtime/application/world-authoring/AuthoringRevisionHistory.js +144 -0
  122. package/dist/runtime/application/world-authoring/HeadlessImageExport.js +174 -0
  123. package/dist/runtime/application/world-authoring/ModelRef.js +62 -0
  124. package/dist/runtime/apps/mcp-server/AUTHORING.md +71 -0
  125. package/dist/runtime/apps/mcp-server/AgentMcpCompat.js +77 -0
  126. package/dist/runtime/apps/mcp-server/AuthoringSandboxEntry.js +1 -0
  127. package/dist/runtime/apps/mcp-server/AuthoringSandboxWorker.mjs +30 -0
  128. package/dist/runtime/apps/mcp-server/BuildEnvironment.js +17 -0
  129. package/dist/runtime/apps/mcp-server/CodeExecutor.js +71 -0
  130. package/dist/runtime/apps/mcp-server/DEPLOYMENT-PC2.md +42 -0
  131. package/dist/runtime/apps/mcp-server/DockerBuildRunner.js +66 -0
  132. package/dist/runtime/apps/mcp-server/FileAssetRepository.js +159 -0
  133. package/dist/runtime/apps/mcp-server/HeadlessAssetIO.js +8 -0
  134. package/dist/runtime/apps/mcp-server/HeadlessGLTFLoader.js +47 -0
  135. package/dist/runtime/apps/mcp-server/HeadlessWorldHost.js +132 -0
  136. package/dist/runtime/apps/mcp-server/IsolatedAuthoringExecutor.js +6 -0
  137. package/dist/runtime/apps/mcp-server/PROGRAMMATIC-ASSETS.md +116 -0
  138. package/dist/runtime/apps/mcp-server/ProgrammaticAssets.js +60 -0
  139. package/dist/runtime/apps/mcp-server/README.md +150 -0
  140. package/dist/runtime/apps/mcp-server/RemoteAuthoringDocument.js +1 -0
  141. package/dist/runtime/apps/mcp-server/SandboxBundle.js +13 -0
  142. package/dist/runtime/apps/mcp-server/SessionManager.js +80 -0
  143. package/dist/runtime/apps/mcp-server/StudioBridgeHttp.js +58 -0
  144. package/dist/runtime/apps/mcp-server/StudioLiveBridge.js +190 -0
  145. package/dist/runtime/apps/mcp-server/TrustedAuthoringWorker.mjs +16 -0
  146. package/dist/runtime/apps/mcp-server/VALIDATION.md +45 -0
  147. package/dist/runtime/apps/mcp-server/acceptance-evidence.json +332 -0
  148. package/dist/runtime/apps/mcp-server/errorDiagnostics.js +32 -0
  149. package/dist/runtime/apps/mcp-server/examples/code-house.js +24 -0
  150. package/dist/runtime/apps/mcp-server/examples/procedural-assets.js +85 -0
  151. package/dist/runtime/apps/mcp-server/main.mjs +65 -0
  152. package/dist/runtime/apps/mcp-server/registerTools.js +225 -0
  153. package/dist/runtime/apps/mcp-server/sandbox/run.mjs +23 -0
  154. package/dist/runtime/apps/mcp-server/security.js +21 -0
  155. package/dist/runtime/apps/mcp-server/tasks.jsonl +9 -0
  156. package/dist/runtime/apps/server/CapabilityAdapterRegistry.js +157 -0
  157. package/dist/runtime/apps/server/README.md +7 -0
  158. package/dist/runtime/apps/server/WorldDiskStorage.js +51 -0
  159. package/dist/runtime/apps/server/openai-compatible-agent-gateway.mjs +278 -0
  160. package/dist/runtime/apps/server/tasks.jsonl +10 -0
  161. package/dist/runtime/foundation/EventBus.js +18 -0
  162. package/dist/runtime/foundation/JsonGateway.js +47 -0
  163. package/dist/runtime/foundation/PolicyEngine.js +21 -0
  164. package/dist/runtime/foundation/README.md +7 -0
  165. package/dist/runtime/foundation/TraceRecorder.js +76 -0
  166. package/dist/runtime/foundation/errors.js +8 -0
  167. package/dist/runtime/foundation/simulation/SimulationProfile.js +143 -0
  168. package/dist/runtime/foundation/version.js +2 -0
  169. package/dist/runtime/modules/agent/README.md +11 -0
  170. package/dist/runtime/modules/agent/ToolCallingAgent.js +19 -0
  171. package/dist/runtime/modules/agent/bootstrapWorld.js +10 -0
  172. package/dist/runtime/modules/agent/buildRecoveryProposals.js +533 -0
  173. package/dist/runtime/modules/agent/execution/AgentExecutionRules.js +128 -0
  174. package/dist/runtime/modules/agent/execution/AgentRunResults.js +55 -0
  175. package/dist/runtime/modules/agent/execution/AgentRunSession.js +393 -0
  176. package/dist/runtime/modules/agent/execution/AgentToolInvoker.js +40 -0
  177. package/dist/runtime/modules/agent/gateway/HttpLLMGateway.js +19 -0
  178. package/dist/runtime/modules/agent/prompt/index.js +52 -0
  179. package/dist/runtime/modules/agent/tasks.jsonl +94 -0
  180. package/dist/runtime/modules/artifact/ArtifactContentGate.js +144 -0
  181. package/dist/runtime/modules/artifact/ArtifactDescriptor.js +280 -0
  182. package/dist/runtime/modules/artifact/ArtifactImporter.js +185 -0
  183. package/dist/runtime/modules/artifact/ArtifactModule.js +111 -0
  184. package/dist/runtime/modules/artifact/ArtifactRegistry.js +197 -0
  185. package/dist/runtime/modules/artifact/IncrementalSha256.js +129 -0
  186. package/dist/runtime/modules/artifact/MemoryArtifactByteStore.js +115 -0
  187. package/dist/runtime/modules/artifact/README.md +7 -0
  188. package/dist/runtime/modules/artifact/storage/IndexedDbArtifactStore.js +67 -0
  189. package/dist/runtime/modules/artifact/tasks.jsonl +31 -0
  190. package/dist/runtime/modules/asset/AssetModule.js +399 -0
  191. package/dist/runtime/modules/asset/README.md +54 -0
  192. package/dist/runtime/modules/asset/loading/AssetLoader.js +157 -0
  193. package/dist/runtime/modules/asset/loading/GltfAssetLoader.js +61 -0
  194. package/dist/runtime/modules/asset/loading/builtins/BuiltinAssets.js +95 -0
  195. package/dist/runtime/modules/asset/loading/builtins/HouseDoor.js +33 -0
  196. package/dist/runtime/modules/asset/loading/builtins/IndustrialCabinet.js +103 -0
  197. package/dist/runtime/modules/asset/model/AssetInputContracts.js +100 -0
  198. package/dist/runtime/modules/asset/model/AssetRef.js +12 -0
  199. package/dist/runtime/modules/asset/model/MechanicalAssetDraft.js +172 -0
  200. package/dist/runtime/modules/asset/model/admission.js +117 -0
  201. package/dist/runtime/modules/asset/model/errors.js +6 -0
  202. package/dist/runtime/modules/asset/model/parts.js +27 -0
  203. package/dist/runtime/modules/asset/model/resourceBudget.js +10 -0
  204. package/dist/runtime/modules/asset/model/schema.js +150 -0
  205. package/dist/runtime/modules/asset/persistence/AssetManifestStore.js +78 -0
  206. package/dist/runtime/modules/asset/persistence/CompiledAssetStore.js +84 -0
  207. package/dist/runtime/modules/asset/persistence/LocalAssetLibrary.js +86 -0
  208. package/dist/runtime/modules/asset/persistence/LocalAssetLibraryStore.js +81 -0
  209. package/dist/runtime/modules/asset/production/AssetProductionPipeline.js +272 -0
  210. package/dist/runtime/modules/asset/production/AssetRecipe.js +47 -0
  211. package/dist/runtime/modules/asset/production/adapters/EmbodiedGenAdapter.js +45 -0
  212. package/dist/runtime/modules/asset/production/adapters/EmbodiedGenBundleAdapter.js +590 -0
  213. package/dist/runtime/modules/asset/production/compiler/AssetCompiler.js +173 -0
  214. package/dist/runtime/modules/asset/production/compiler/evidence/AnimationMotionEvidence.js +124 -0
  215. package/dist/runtime/modules/asset/production/compiler/evidence/StaticPanelEvidence.js +56 -0
  216. package/dist/runtime/modules/asset/production/compiler/gltfIO.js +6 -0
  217. package/dist/runtime/modules/asset/production/compiler/partGeometry.js +74 -0
  218. package/dist/runtime/modules/asset/production/compiler/passes/ArticulatedCollisionPass.js +63 -0
  219. package/dist/runtime/modules/asset/production/compiler/passes/ArticulationCandidatePass.js +48 -0
  220. package/dist/runtime/modules/asset/production/compiler/passes/AuthoringIntentPass.js +16 -0
  221. package/dist/runtime/modules/asset/production/compiler/passes/ColliderFallbackPass.js +30 -0
  222. package/dist/runtime/modules/asset/production/compiler/passes/CompileQualityPass.js +75 -0
  223. package/dist/runtime/modules/asset/production/compiler/passes/ExplicitDefinitionPass.js +20 -0
  224. package/dist/runtime/modules/asset/production/compiler/passes/GLTFInspectPass.js +34 -0
  225. package/dist/runtime/modules/asset/production/compiler/passes/GeometryPass.js +32 -0
  226. package/dist/runtime/modules/asset/production/compiler/passes/JointFramePass.js +116 -0
  227. package/dist/runtime/modules/asset/production/compiler/passes/KinematicEvidencePass.js +84 -0
  228. package/dist/runtime/modules/asset/production/compiler/passes/ManifestPass.js +63 -0
  229. package/dist/runtime/modules/asset/production/compiler/passes/NormalizeTransformPass.js +16 -0
  230. package/dist/runtime/modules/asset/production/compiler/passes/OptimizeGLBPass.js +23 -0
  231. package/dist/runtime/modules/asset/production/compiler/passes/PartColliderPass.js +50 -0
  232. package/dist/runtime/modules/asset/production/compiler/passes/PartGeometryEnrichmentPass.js +60 -0
  233. package/dist/runtime/modules/asset/production/compiler/passes/PartProposalPass.js +93 -0
  234. package/dist/runtime/modules/asset/production/compiler/passes/RemoteEnrichmentPass.js +32 -0
  235. package/dist/runtime/modules/asset/production/compiler/passes/ResourceBudgetPass.js +55 -0
  236. package/dist/runtime/modules/asset/production/compiler/passes/SegmentMaterializePass.js +203 -0
  237. package/dist/runtime/modules/asset/production/compiler/passes/SegmentationEvidencePass.js +43 -0
  238. package/dist/runtime/modules/asset/production/compiler/passes/SemanticHeuristicPass.js +33 -0
  239. package/dist/runtime/modules/asset/production/compiler/passes/StructurePass.js +60 -0
  240. package/dist/runtime/modules/asset/production/compiler/providers/HttpCompilerProvider.js +23 -0
  241. package/dist/runtime/modules/asset/production/verification/KinematicHypothesisScreen.js +198 -0
  242. package/dist/runtime/modules/asset/registry/AssetCatalog.js +72 -0
  243. package/dist/runtime/modules/asset/registry/AssetRegistry.js +51 -0
  244. package/dist/runtime/modules/asset/registry/manifests/index.js +173 -0
  245. package/dist/runtime/modules/asset/tasks.jsonl +87 -0
  246. package/dist/runtime/modules/generation/README.md +9 -0
  247. package/dist/runtime/modules/generation/connector/ConnectorArtifactClient.js +45 -0
  248. package/dist/runtime/modules/generation/connector/ConnectorCapabilityAdapter.js +169 -0
  249. package/dist/runtime/modules/generation/connector/ConnectorClient.js +192 -0
  250. package/dist/runtime/modules/generation/connector/ConnectorJobClient.js +167 -0
  251. package/dist/runtime/modules/generation/connector/ConnectorJobEventClient.js +179 -0
  252. package/dist/runtime/modules/generation/connector/ConnectorSession.js +202 -0
  253. package/dist/runtime/modules/generation/jobs/GenerationJobProjection.js +239 -0
  254. package/dist/runtime/modules/generation/jobs/GenerationJobReconciler.js +99 -0
  255. package/dist/runtime/modules/generation/jobs/GenerationJobStore.js +91 -0
  256. package/dist/runtime/modules/generation/jobs/GenerationJobTransportOverlay.js +50 -0
  257. package/dist/runtime/modules/generation/providers/ProviderRegistry.js +304 -0
  258. package/dist/runtime/modules/generation/tasks.jsonl +35 -0
  259. package/dist/runtime/modules/navigation/NavigationBackend.js +17 -0
  260. package/dist/runtime/modules/navigation/RecastNavigationBackend.js +245 -0
  261. package/dist/runtime/modules/physics/JoltPhysicsBackend.js +850 -0
  262. package/dist/runtime/modules/physics/PhysicsApiSurface.js +651 -0
  263. package/dist/runtime/modules/physics/PhysicsBackend.js +88 -0
  264. package/dist/runtime/modules/physics/RapierPhysicsBackend.js +410 -0
  265. package/dist/runtime/modules/rendering/README.md +7 -0
  266. package/dist/runtime/modules/rendering/RendererProbe.js +153 -0
  267. package/dist/runtime/modules/rendering/WebGpuPostFxPipeline.js +140 -0
  268. package/dist/runtime/modules/rendering/createRenderer.js +76 -0
  269. package/dist/runtime/modules/rendering/disposeObject3D.js +37 -0
  270. package/dist/runtime/modules/rendering/loadGaussianSplatVisual.js +74 -0
  271. package/dist/runtime/modules/rendering/spatial/ThreeBvhRuntime.js +107 -0
  272. package/dist/runtime/modules/rendering/style/StylePack.js +34 -0
  273. package/dist/runtime/modules/rendering/style/StyleSystem.js +173 -0
  274. package/dist/runtime/modules/rendering/tasks.jsonl +7 -0
  275. package/dist/runtime/modules/world/README.md +13 -0
  276. package/dist/runtime/modules/world/build/WorldBuilder.js +170 -0
  277. package/dist/runtime/modules/world/compiler/PipelineEngine.js +32 -0
  278. package/dist/runtime/modules/world/compiler/WorldAdmission.js +43 -0
  279. package/dist/runtime/modules/world/compiler/WorldBehaviorCompiler.js +68 -0
  280. package/dist/runtime/modules/world/compiler/WorldCompilation.js +157 -0
  281. package/dist/runtime/modules/world/compiler/WorldComposer.js +201 -0
  282. package/dist/runtime/modules/world/compiler/WorldPhysicsAdmission.js +76 -0
  283. package/dist/runtime/modules/world/compiler/WorldRecompiler.js +356 -0
  284. package/dist/runtime/modules/world/compiler/WorldRetry.js +75 -0
  285. package/dist/runtime/modules/world/compiler/createWorldPipeline.js +379 -0
  286. package/dist/runtime/modules/world/content/blankWorld.js +35 -0
  287. package/dist/runtime/modules/world/content/environments.js +84 -0
  288. package/dist/runtime/modules/world/content/grandUrbanBlock.js +189 -0
  289. package/dist/runtime/modules/world/content/magic-cabin/README.md +28 -0
  290. package/dist/runtime/modules/world/content/magic-cabin/affordances.js +64 -0
  291. package/dist/runtime/modules/world/content/magic-cabin/cabinContents.js +7078 -0
  292. package/dist/runtime/modules/world/content/magic-cabin/lighting.js +26 -0
  293. package/dist/runtime/modules/world/content/magic-cabin/materials.js +20 -0
  294. package/dist/runtime/modules/world/content/magicCabin.js +190 -0
  295. package/dist/runtime/modules/world/content/monumentHall.js +154 -0
  296. package/dist/runtime/modules/world/content/ruinedCourtyard.js +196 -0
  297. package/dist/runtime/modules/world/content/suzhouGarden/README.md +141 -0
  298. package/dist/runtime/modules/world/content/suzhouGarden/index.js +137 -0
  299. package/dist/runtime/modules/world/content/suzhouGarden/src/arch.js +491 -0
  300. package/dist/runtime/modules/world/content/suzhouGarden/src/buildings.js +670 -0
  301. package/dist/runtime/modules/world/content/suzhouGarden/src/core.js +578 -0
  302. package/dist/runtime/modules/world/content/suzhouGarden/src/lod.js +127 -0
  303. package/dist/runtime/modules/world/content/suzhouGarden/src/main.js +642 -0
  304. package/dist/runtime/modules/world/content/suzhouGarden/src/nature.js +650 -0
  305. package/dist/runtime/modules/world/content/suzhouGarden/src/rockery.js +280 -0
  306. package/dist/runtime/modules/world/content/suzhouGarden/src/sky.js +242 -0
  307. package/dist/runtime/modules/world/content/suzhouGarden/src/water.js +215 -0
  308. package/dist/runtime/modules/world/content/woodlandWorkshop.js +192 -0
  309. package/dist/runtime/modules/world/content/yuanmingyuan/README.md +36 -0
  310. package/dist/runtime/modules/world/content/yuanmingyuan/arch.js +351 -0
  311. package/dist/runtime/modules/world/content/yuanmingyuan/buildings.js +490 -0
  312. package/dist/runtime/modules/world/content/yuanmingyuan/core.js +505 -0
  313. package/dist/runtime/modules/world/content/yuanmingyuan/index.js +101 -0
  314. package/dist/runtime/modules/world/content/yuanmingyuan/nature.js +435 -0
  315. package/dist/runtime/modules/world/content/yuanmingyuan/sky.js +169 -0
  316. package/dist/runtime/modules/world/content/yuanmingyuan/water.js +245 -0
  317. package/dist/runtime/modules/world/errors.js +9 -0
  318. package/dist/runtime/modules/world/generated/GeneratedWorldCoordinates.js +50 -0
  319. package/dist/runtime/modules/world/generated/GeneratedWorldLoader.js +297 -0
  320. package/dist/runtime/modules/world/runtime/CommandHistory.js +80 -0
  321. package/dist/runtime/modules/world/runtime/EntityCapabilityRegistry.js +150 -0
  322. package/dist/runtime/modules/world/runtime/ObjectStore.js +31 -0
  323. package/dist/runtime/modules/world/runtime/ObjectTransform.js +62 -0
  324. package/dist/runtime/modules/world/runtime/ObservedEntity.js +37 -0
  325. package/dist/runtime/modules/world/runtime/ProjectCapabilities.js +207 -0
  326. package/dist/runtime/modules/world/runtime/SceneSerializer.js +246 -0
  327. package/dist/runtime/modules/world/runtime/WorldAuthority.js +41 -0
  328. package/dist/runtime/modules/world/runtime/WorldCollisionSignature.js +14 -0
  329. package/dist/runtime/modules/world/runtime/WorldCommands.js +502 -0
  330. package/dist/runtime/modules/world/runtime/WorldObservation.js +71 -0
  331. package/dist/runtime/modules/world/runtime/WorldQueries.js +340 -0
  332. package/dist/runtime/modules/world/runtime/WorldRecovery.js +78 -0
  333. package/dist/runtime/modules/world/runtime/WorldRuntime.js +665 -0
  334. package/dist/runtime/modules/world/runtime/affordance/ObjectAffordances.js +107 -0
  335. package/dist/runtime/modules/world/runtime/affordance/WorldAffordances.js +130 -0
  336. package/dist/runtime/modules/world/runtime/behavior/BehaviorCompiler.js +79 -0
  337. package/dist/runtime/modules/world/runtime/behavior/ProjectStateMachine.js +195 -0
  338. package/dist/runtime/modules/world/runtime/behavior/RuleGraph.js +70 -0
  339. package/dist/runtime/modules/world/runtime/behavior/RuleRuntime.js +115 -0
  340. package/dist/runtime/modules/world/runtime/graph/SceneGraph.js +305 -0
  341. package/dist/runtime/modules/world/runtime/interaction/ArticulationRuntime.js +214 -0
  342. package/dist/runtime/modules/world/runtime/interaction/CarryCapability.js +65 -0
  343. package/dist/runtime/modules/world/runtime/interaction/CarryRuntime.js +222 -0
  344. package/dist/runtime/modules/world/runtime/interaction/InteractionApproach.js +130 -0
  345. package/dist/runtime/modules/world/runtime/interaction/InteractionContract.js +57 -0
  346. package/dist/runtime/modules/world/runtime/interaction/RecoveryRuntime.js +123 -0
  347. package/dist/runtime/modules/world/runtime/interaction/SettleRuntime.js +120 -0
  348. package/dist/runtime/modules/world/runtime/semantic/SemanticWorldView.js +102 -0
  349. package/dist/runtime/modules/world/runtime/simulation/SimulationClock.js +89 -0
  350. package/dist/runtime/modules/world/runtime/simulation/SimulationSession.js +99 -0
  351. package/dist/runtime/modules/world/runtime/simulation/ThermalSystem.js +269 -0
  352. package/dist/runtime/modules/world/runtime/spatial/SpatialSnapshot.js +56 -0
  353. package/dist/runtime/modules/world/runtime/systems/AudioSystem.js +125 -0
  354. package/dist/runtime/modules/world/runtime/systems/Instrument.js +38 -0
  355. package/dist/runtime/modules/world/runtime/systems/InteractionSystem.js +728 -0
  356. package/dist/runtime/modules/world/runtime/systems/LocomotionSystem.js +269 -0
  357. package/dist/runtime/modules/world/runtime/systems/NavigationSystem.js +469 -0
  358. package/dist/runtime/modules/world/runtime/systems/PhysicsSystem.js +1673 -0
  359. package/dist/runtime/modules/world/runtime/systems/RenderingSystem.js +457 -0
  360. package/dist/runtime/modules/world/runtime/systems/SpatialSystem.js +284 -0
  361. package/dist/runtime/modules/world/spec/WorldIR.js +165 -0
  362. package/dist/runtime/modules/world/spec/WorldIRToolSchema.js +86 -0
  363. package/dist/runtime/modules/world/spec/WorldPlannerProposal.js +51 -0
  364. package/dist/runtime/modules/world/spec/WorldRevision.js +231 -0
  365. package/dist/runtime/modules/world/spec/WorldSpec.js +86 -0
  366. package/dist/runtime/modules/world/tasks.jsonl +530 -0
  367. package/dist/runtime/modules/world/verification/ArticulationVerifier.js +254 -0
  368. package/dist/runtime/modules/world/verification/Finding.js +105 -0
  369. package/dist/runtime/modules/world/verification/InteractionEvidence.js +69 -0
  370. package/dist/runtime/modules/world/verification/RepairEngine.js +49 -0
  371. package/dist/runtime/modules/world/verification/WorldAcceptance.js +158 -0
  372. package/dist/runtime/modules/world/verification/WorldValidator.js +65 -0
  373. package/dist/runtime/package-lock.json +16048 -0
  374. package/dist/runtime/package.json +105 -0
  375. package/dist/runtime/public/assets/cabinet.glb +0 -0
  376. package/dist/runtime/public/assets/grand-urban-block/clean_asphalt_diff_1k.jpg +0 -0
  377. package/dist/runtime/public/assets/grand-urban-block/clean_asphalt_nor_gl_1k.jpg +0 -0
  378. package/dist/runtime/public/assets/grand-urban-block/concrete_pavement_diff_1k.jpg +0 -0
  379. package/dist/runtime/public/assets/grand-urban-block/urban_street_01_1k.hdr +0 -0
  380. package/dist/runtime/public/assets/monument-hall/marble_diff_1k.jpg +0 -0
  381. package/dist/runtime/public/assets/monument-hall/marble_nor_gl_1k.jpg +0 -0
  382. package/dist/runtime/public/assets/monument-hall/marble_rough_1k.jpg +0 -0
  383. package/dist/runtime/public/assets/monument-hall/solitude_interior_1k.hdr +0 -0
  384. package/dist/runtime/public/assets/ruined-courtyard/courtyard_1k.hdr +0 -0
  385. package/dist/runtime/public/assets/ruined-courtyard/mossy_cobblestone_diff_1k.jpg +0 -0
  386. package/dist/runtime/public/assets/ruined-courtyard/mossy_cobblestone_nor_gl_1k.jpg +0 -0
  387. package/dist/runtime/public/assets/ruined-courtyard/mossy_sandstone_diff_1k.jpg +0 -0
  388. package/dist/schema-BWpTl0Wj.js +359 -0
  389. package/dist/schema-BWpTl0Wj.js.map +1 -0
  390. package/dist/suzhouGarden-H9tiPgxq.js +6150 -0
  391. package/dist/suzhouGarden-H9tiPgxq.js.map +1 -0
  392. package/dist/woodlandWorkshop-D6zzSbHr.js +483 -0
  393. package/dist/woodlandWorkshop-D6zzSbHr.js.map +1 -0
  394. package/dist/yuanmingyuan-D6IHqjZ-.js +4955 -0
  395. package/dist/yuanmingyuan-D6IHqjZ-.js.map +1 -0
  396. package/package.json +70 -4
@@ -0,0 +1,85 @@
1
+ export const box={
2
+ source:`export function createAsset(THREE) {
3
+ const root=new THREE.Group();root.name='Box';
4
+ const mesh=new THREE.Mesh(new THREE.BoxGeometry(.3,.3,.3),new THREE.MeshStandardMaterial({color:0xff8844}));
5
+ mesh.position.y=.15;mesh.name='Body';root.add(mesh);return root;
6
+ }`,
7
+ definition:{id:'box',type:'box',label:'程序化箱子',actions:['move','pickup','drop','place'],requiredNodes:['Body'],physics:{body:'dynamic',mass:.3,colliders:[{shape:'box',halfExtents:[.15,.15,.15],translation:[0,.15,0]}]}}
8
+ };
9
+ export const table={
10
+ source:`export function createAsset(THREE) {
11
+ const root=new THREE.Group();root.name='Table';
12
+ const material=new THREE.MeshStandardMaterial({color:0x996633});
13
+ const top=new THREE.Mesh(new THREE.BoxGeometry(2.4,.16,1.25),material);top.name='TableTop';top.position.y=1;root.add(top);
14
+ for(const x of [-1.02,1.02])for(const z of [-.46,.46]){const leg=new THREE.Mesh(new THREE.BoxGeometry(.14,.94,.14),material);leg.position.set(x,.47,z);root.add(leg);}
15
+ return root;
16
+ }`,
17
+ definition:{id:'table',type:'table',label:'程序化桌子',actions:['move'],requiredNodes:['TableTop'],physics:{body:'fixed',colliders:[{shape:'box',halfExtents:[1.2,.08,.625],translation:[0,1,0]},...[-1.02,1.02].flatMap(x=>[-.46,.46].map(z=>({shape:'box',halfExtents:[.07,.47,.07],translation:[x,.47,z]})))]},surfaces:[{id:'top',localPosition:[0,1.1,0],size:[2.2,1.05]}]}
18
+ };
19
+ const shell=[
20
+ {shape:'box',halfExtents:[.05,1,.36],translation:[-.8,1,0]},
21
+ {shape:'box',halfExtents:[.05,1,.36],translation:[.8,1,0]},
22
+ {shape:'box',halfExtents:[.75,.05,.32],translation:[0,.05,0]},
23
+ {shape:'box',halfExtents:[.75,.05,.32],translation:[0,1.95,0]},
24
+ {shape:'box',halfExtents:[.75,.9,.04],translation:[0,1,-.32]}
25
+ ];
26
+ export const fridge={
27
+ source:`export function createAsset(THREE) {
28
+ const root=new THREE.Group();root.name='Fridge';const body=new THREE.Group();body.name='Body';root.add(body);
29
+ const material=new THREE.MeshStandardMaterial({color:0xeeeeee});
30
+ const panels=[[[.1,2,.72],[-.8,1,0]],[[.1,2,.72],[.8,1,0]],[[1.5,.1,.64],[0,.05,0]],[[1.5,.1,.64],[0,1.95,0]],[[1.5,1.8,.08],[0,1,-.32]]];
31
+ for(const [size,position] of panels){const m=new THREE.Mesh(new THREE.BoxGeometry(...size),material);m.position.set(...position);body.add(m);}
32
+ const hinge=new THREE.Group();hinge.name='doorHinge';hinge.position.set(-.82,1,.39);root.add(hinge);
33
+ const door=new THREE.Mesh(new THREE.BoxGeometry(1.62,1.9,.08),new THREE.MeshStandardMaterial({color:0xddeeff}));door.name='Door';door.position.x=.81;hinge.add(door);
34
+ return root;
35
+ }`,
36
+ definition:{id:'fridge',type:'fridge',label:'程序化冰箱',actions:['move','open','close'],requiredNodes:['Body','doorHinge','Door'],physics:{body:'fixed',colliders:shell},receptacles:[{id:'interior',localPosition:[0,.95,-.01],size:[1.4,1.7,.46]}],parts:{door:{node:'doorHinge',semantic:'door',actions:['open','close'],targets:{open:-1.35,close:0},physics:{body:'dynamic',mass:8,colliders:[{shape:'box',halfExtents:[.81,.95,.04],translation:[.81,0,0]}]},joint:{type:'revolute',axis:[0,1,0],limits:[-1.35,0],parentAnchor:[-.82,1,.39],childAnchor:[0,0,0],motor:{stiffness:80,damping:12}}}}}
37
+ };
38
+
39
+ const applePositions = [
40
+ [-0.85, 2.65, 0.2], [0.05, 2.95, 0.35], [0.8, 2.55, 0.1],
41
+ [-0.35, 3.25, -0.35], [0.45, 3.35, -0.25]
42
+ ];
43
+ const appleParts = Object.fromEntries(applePositions.map((_, index) => {
44
+ const node = `Apple_${String(index + 1).padStart(2, '0')}`;
45
+ return [node.toLowerCase(), {
46
+ node, semantic: 'apple', actions: ['pickup', 'drop', 'place'],
47
+ physics: { body: 'dynamic', mass: 0.12, colliders: [{ shape: 'cylinder', radius: 0.13, halfHeight: 0.13 }] }
48
+ }];
49
+ }));
50
+
51
+ export const appleTree = {
52
+ source: `export function createAsset(THREE) {
53
+ const root = new THREE.Group(); root.name = 'AppleTree';
54
+ const trunkMaterial = new THREE.MeshStandardMaterial({ color: 0x6b3f21, roughness: 0.9 });
55
+ const leafMaterial = new THREE.MeshStandardMaterial({ color: 0x2f7d32, roughness: 1 });
56
+ const appleMaterial = new THREE.MeshStandardMaterial({ color: 0xc92d35, roughness: 0.55 });
57
+ const trunk = new THREE.Mesh(new THREE.CylinderGeometry(0.28, 0.42, 2.3, 12), trunkMaterial);
58
+ trunk.name = 'Trunk'; trunk.position.y = 1.15; root.add(trunk);
59
+ for (const [index, [x, y, z]] of [[0, [-0.5, 1.75, 0]], [1, [0.5, 1.8, 0]], [2, [0, 2.15, 0]]]) {
60
+ const branch = new THREE.Mesh(new THREE.CylinderGeometry(0.09, 0.14, 1.3, 8), trunkMaterial);
61
+ branch.name = 'Branch_' + String(index + 1).padStart(2, '0'); branch.position.set(x, y, z); branch.rotation.z = x < 0 ? -0.7 : x > 0 ? 0.7 : 0; root.add(branch);
62
+ }
63
+ const crown = new THREE.Group(); crown.name = 'Crown'; root.add(crown);
64
+ for (const [x, y, z, scale] of [[0, 2.65, 0, 1.25], [-0.75, 2.35, 0.15, 0.9], [0.75, 2.35, 0.15, 0.9], [0, 3.15, -0.2, 0.95]]) {
65
+ const leaves = new THREE.Mesh(new THREE.IcosahedronGeometry(0.85, 1), leafMaterial);
66
+ leaves.position.set(x, y, z); leaves.scale.setScalar(scale); crown.add(leaves);
67
+ }
68
+ for (const [index, [x, y, z]] of ${JSON.stringify(applePositions.map((position, index) => [index, position]))}) {
69
+ const apple = new THREE.Mesh(new THREE.SphereGeometry(0.13, 12, 8), appleMaterial);
70
+ apple.name = 'Apple_' + String(index + 1).padStart(2, '0'); apple.position.set(x, y, z); root.add(apple);
71
+ }
72
+ return root;
73
+ }`,
74
+ definition: {
75
+ id: 'apple-tree', type: 'apple_tree', label: '程序化苹果树',
76
+ description: '包含树干、树枝、树冠和可拾取苹果的程序化树木。',
77
+ tags: ['nature', 'tree', 'apple', 'interactive'],
78
+ actions: ['move'], requiredNodes: ['Trunk', 'Crown', ...applePositions.map((_, i) => `Apple_${String(i + 1).padStart(2, '0')}`)],
79
+ physics: { body: 'fixed', navigationObstacle: true, colliders: [
80
+ { shape: 'cylinder', radius: 0.42, halfHeight: 1.15, translation: [0, 1.15, 0] }
81
+ ] },
82
+ parts: appleParts
83
+ }
84
+ };
85
+
@@ -0,0 +1,65 @@
1
+ import { createServer } from 'node:http';
2
+ import { pathToFileURL } from 'node:url';
3
+ import path from 'node:path';
4
+ import { McpServer, createMcpHandler } from '@modelcontextprotocol/server';
5
+ import { toWebRequest } from '@modelcontextprotocol/node';
6
+ import { SessionManager } from './SessionManager.js';
7
+ import { StudioLiveBridge } from './StudioLiveBridge.js';
8
+ import { handleStudioBridgeHttp } from './StudioBridgeHttp.js';
9
+ import { registerTools } from './registerTools.js';
10
+ import { handleRestrictedAgentMcp } from './AgentMcpCompat.js';
11
+ import { createSecurity } from './security.js';
12
+ import { FileAssetRepository } from './FileAssetRepository.js';
13
+ import { createCodeExecutor } from './CodeExecutor.js';
14
+ import { ProgrammaticAssets } from './ProgrammaticAssets.js';
15
+ import { ProgrammaticAssetBuilder } from '../../application/programmatic-assets/ProgrammaticAssetBuilder.js';
16
+ import { createHeadlessGLTFLoader } from './HeadlessGLTFLoader.js';
17
+ import { installHeadlessAssetIO } from './HeadlessAssetIO.js';
18
+ export async function startServer({tokens,port=39015,root=path.resolve('.mcp-sessions'),dataRoot=path.resolve('.mcp-assets'),security={},managerOptions={},buildRunner=null,studioOrigins,codeExecution={mode:'worker-wasm'}}={}) {
19
+ installHeadlessAssetIO();
20
+ const repository=new FileAssetRepository(dataRoot);
21
+ const runner=buildRunner || createCodeExecutor({...codeExecution,configPath:path.join(dataRoot,'sandbox.json')});
22
+ const assets=new ProgrammaticAssets({repository,runner,builder:new ProgrammaticAssetBuilder({runner,gltfLoader:createHeadlessGLTFLoader()})});
23
+ const authorize=createSecurity(tokens,security); const manager=new SessionManager({root,repository,hostOptions:{codeExecution,sandboxConfig:path.join(dataRoot,'sandbox.json')},...managerOptions});
24
+ const studioBridge=new StudioLiveBridge();
25
+ const connections=new Set();
26
+ const http=createServer(async(req,res)=>{
27
+ let server;
28
+ try {
29
+ if(await handleStudioBridgeHttp(req,res,studioBridge,{...(studioOrigins?{origins:studioOrigins}:{})}))return;
30
+ if(req.url!=='/mcp' && req.url!=='/agent-mcp') {res.writeHead(404).end();return;}
31
+ const {owner,body}=await authorize(req);
32
+ if(req.url==='/agent-mcp'){
33
+ if(req.method!=='POST'){res.writeHead(405).end();return;}
34
+ const answer=await handleRestrictedAgentMcp({body,owner,manager,assets,studioBridge,scope:req.headers['x-agentscape-project']});
35
+ if(answer.body===null){res.writeHead(answer.status).end();return;}
36
+ const payload=JSON.stringify(answer.body);
37
+ res.writeHead(answer.status,{'content-type':'application/json; charset=utf-8','content-length':Buffer.byteLength(payload)}).end(payload);
38
+ return;
39
+ }
40
+ if(req.method!=='POST') {res.writeHead(405).end();return;}
41
+ // The unified SDK handler supports modern per-request envelopes and legacy initialization.
42
+ const handler=createMcpHandler(()=>{
43
+ server=new McpServer({name:'AgentScape Remote MCP',version:'0.3.0'});
44
+ registerTools(server,manager,owner,assets,studioBridge,{agentOnly:req.url==='/agent-mcp'});
45
+ connections.add(server);
46
+ return server;
47
+ });
48
+ res.on('close',()=>{connections.delete(server);handler.close().catch(()=>{});});
49
+ const response=await handler.fetch(await toWebRequest(req,body),{parsedBody:body});
50
+ res.writeHead(response.status,Object.fromEntries(response.headers));
51
+ res.end(Buffer.from(await response.arrayBuffer()));
52
+ } catch(e) {if(!res.headersSent) res.writeHead(e.status||500).end(JSON.stringify({error:e.status?'HTTP_REQUEST_REJECTED':'INTERNAL_ERROR'}));}
53
+ });
54
+ http.requestTimeout=35000; http.headersTimeout=10000;
55
+ try {await new Promise((resolve,reject)=>{http.once('error',reject);http.listen(port,'127.0.0.1',resolve);});}
56
+ catch(e){await manager.dispose();throw e;}
57
+ return {http,manager,assets,studioBridge,port:http.address().port,async close(){studioBridge.dispose();await assets.close();await manager.dispose();await Promise.all([...connections].map(s=>s.close()));await new Promise(r=>http.close(r));}};
58
+ }
59
+ if(process.argv[1] && import.meta.url===pathToFileURL(path.resolve(process.argv[1])).href) {
60
+ // Deliberately do not load dotenv or the Studio configuration.
61
+ const tokens=JSON.parse(process.env.AGENTSCAPE_MCP_TOKENS||'[]');
62
+ const app=await startServer({tokens,dataRoot:process.env.AGENTSCAPE_MCP_DATA_ROOT || path.resolve('.mcp-assets'),codeExecution:{mode:process.env.AGENTSCAPE_CODE_EXECUTION || 'worker-wasm',authorized:process.env.AGENTSCAPE_TRUSTED_CODE==='1',remote:process.env.AGENTSCAPE_PUBLIC_SERVICE==='1'}});
63
+ console.log(`AgentScape Remote MCP: http://127.0.0.1:${app.port}/mcp`);
64
+ for(const signal of ['SIGINT','SIGTERM']) process.once(signal,()=>app.close().then(()=>process.exit(0)));
65
+ }
@@ -0,0 +1,225 @@
1
+ import * as z from 'zod/v4';
2
+ import { AGENT_STUDIO_MCP_SET } from '../../application/agent/StudioMcpAllowlist.js';
3
+ import { allowedSkills } from './HeadlessWorldHost.js';
4
+ import { compileWorldAcceptance } from '../../modules/world/verification/WorldAcceptance.js';
5
+ import { definitionSchema, proceduralContract } from '../../application/programmatic-assets/ProgrammaticAssetContract.js';
6
+ import { assetAdmission } from '../../modules/asset/model/admission.js';
7
+ import { sceneObjectIdSchema, sceneTransformSchema, sceneVector3Schema } from '../../application/scene/SceneProject.js';
8
+ import { recipeSchema } from '../../modules/asset/model/AssetInputContracts.js';
9
+ import { publicMcpError } from './errorDiagnostics.js';
10
+ const id=z.string().min(1).max(100).regex(/^[a-zA-Z0-9_-]+$/);
11
+ const targetId=z.string().min(1).max(256);
12
+ const vec=z.array(z.number().finite().min(-100).max(100)).length(3);
13
+ const speed=z.number().positive().max(8).optional();
14
+ export const actionSchemas={
15
+ spawnAsset:z.object({assetId:id,position:vec,instanceId:id.optional()}).strict(),
16
+ moveObject:z.object({id,position:vec}).strict(),
17
+ replaceAsset:z.object({id,assetId:id}).strict(),
18
+ navigateTo:z.object({id,end:vec,speed}).strict(),
19
+ approachAndInteract:z.object({actorId:id,targetId:id,action:z.enum(['open','close']),partName:id.optional(),speed}).strict(),
20
+ approachAndPickup:z.object({actorId:id,targetId:id,speed}).strict(),
21
+ approachAndPlace:z.object({actorId:id,supportId:id,surfaceId:id.optional(),speed}).strict()
22
+ };
23
+ export function registerTools(server,manager,owner,assets,studioBridge=null,{agentOnly=false,projectScope}={}) {
24
+ const session={worldSessionId:z.uuid()};
25
+ const sceneSession={worldSessionId:z.uuid().optional()};
26
+ const add=(name,description,shape,fn)=>agentOnly && !AGENT_STUDIO_MCP_SET.has(name) ? null : server.registerTool(name,{description,inputSchema:z.object(shape).strict()},async(a,extra)=>{
27
+ try { const result=await fn(a,extra); return {content:[{type:'text',text:JSON.stringify(result)}]}; }
28
+ catch(e) { return {isError:true,content:[{type:'text',text:JSON.stringify(publicMcpError(e))}]}; }
29
+ });
30
+ add('studio_pair_create','Create a short-lived one-time pairing code for an explicitly approved local Studio world. The bearer token is never delivered to the browser.',{},()=>studioBridge.pair(owner));
31
+ add('studio_session_status','Check a Studio connection, or inspect the automatically connected local world without passing an ID.',sceneSession,a=>a.worldSessionId?studioBridge.status(owner,a.worldSessionId):studioBridge.currentSession(owner));
32
+ add('session_attach','Attach the local current Studio automatically or resolve an explicit paired world.',sceneSession,a=>{
33
+ const state=a.worldSessionId?studioBridge.status(owner,a.worldSessionId):studioBridge.currentSession(owner);
34
+ if(!state.connected)throw new Error('STUDIO_DISCONNECTED');
35
+ return state;
36
+ });
37
+ add('studio_session_close','Revoke the paired Studio capability and reject outstanding Scene requests.',{worldSessionId:z.uuid()},a=>studioBridge.close(owner,a.worldSessionId));
38
+ add('session_create','Create a private offline monument-hall world with agent, cabinet, cup and table.',{template:z.literal('monument-hall').default('monument-hall')},()=>manager.create(owner));
39
+ add('session_status','Read world session lifecycle.',session,a=>manager.status(owner,a.worldSessionId));
40
+ add('session_close','Cancel work and release your world.',session,a=>manager.close(owner,a.worldSessionId));
41
+ add('asset_build_submit','Submit versioned createAsset(THREE) source to the configured code executor. Optional definition enables physical admission; inspect execution and physics evidence separately.',{contract:z.literal(proceduralContract),source:z.string().min(1).max(32768),definition:definitionSchema.optional(),requestId:z.uuid(),forceRebuild:z.boolean().default(false)},a=>assets.submit(owner,a));
42
+ add('asset_build_status','Read your build status, immutable asset version, admission or diagnostic code.',{buildId:z.uuid()},a=>assets.status(owner,a.buildId));
43
+ add('asset_build_cancel','Cancel your build and terminate its execution Worker or container.',{buildId:z.uuid()},a=>assets.cancel(owner,a.buildId));
44
+ add('asset_publish','Publish a successful immutable asset for your worlds. Provisional requires explicit editing-state opt-in.',{buildId:z.uuid(),allowProvisional:z.boolean().default(false)},a=>assets.publish(owner,a.buildId,a.allowProvisional));
45
+ add('asset_inspect','Inspect your asset, original source (optional), hashes, Manifest and runtime verification evidence.',{assetId:id,includeSource:z.boolean().default(false)},a=>assets.inspect(owner,a.assetId,a.includeSource));
46
+ add('asset_publish_project','Explicitly publish one ready local Object Forge instance to the owner-scoped immutable global library. Publishing does not mutate the project or automatically upgrade any instance.',{
47
+ ...session,objectId:id,requestId:z.uuid()
48
+ },(a,e)=>manager.run(owner,a.worldSessionId,async s=>{
49
+ if(!manager.repository)throw new Error('PERSISTENCE_UNAVAILABLE');
50
+ const entry=s.forge.get(s.host.world,a.objectId);
51
+ const module=s.host.world.assetModule;
52
+ const manifest=module.getManifest(entry.assetId);
53
+ const bytes=await module.readAssetBytes(entry.assetId);
54
+ const prepared=await manager.repository.saveProjectAsset(owner,{definition:entry.definition,manifest,bytes});
55
+ await manager.repository.publish(owner,prepared.manifest.id);
56
+ return {published:true,scope:'owner-global',assetId:prepared.manifest.id,version:prepared.build.version,
57
+ reference:'asset://sha256/'+prepared.build.version,sourceObjectId:a.objectId,
58
+ sourceRevision:entry.revision,admission:prepared.build.admission};
59
+ },{signal:e?.signal,requestId:a.requestId,fingerprint:JSON.stringify(['asset_publish_project',a.objectId])}));
60
+ add('asset_list','List your published asset versions, paginated.',{offset:z.number().int().min(0).max(128).default(0),limit:z.number().int().min(1).max(20).default(20)},async a=>{const all=await assets.repository.list(owner);return {assets:all.slice(a.offset,a.offset+a.limit),total:all.length,nextOffset:a.offset+a.limit<all.length?a.offset+a.limit:null};});
61
+ const run=(a,fn,extra)=>manager.run(owner,a.worldSessionId,fn,{signal:extra?.signal});
62
+ const sceneRun=async(a,method,args,fn,extra)=>{
63
+ const target=projectScope?.worldSessionId || a.worldSessionId || studioBridge.currentSession(owner).worldSessionId;
64
+ if(projectScope)args={...args,expectedProjectId:projectScope.projectId};
65
+ if(studioBridge?.isStudioSession(target)) {
66
+ studioBridge.ownerSession(owner,target);
67
+ const ref=args.model?.asset;
68
+ if(method==='addModel' && typeof ref==='string' && /^asset:\/\/sha256\/[a-f0-9]{64}$/.test(ref)) {
69
+ const published=await assets.repository.get(owner,`pa_${ref.slice('asset://sha256/'.length)}`,{published:true});
70
+ const {id}=published.manifest;
71
+ const definition=Object.fromEntries(['type','label','actions','physics','parts','surfaces','receptacles','requiredNodes','interactionContract','capabilityLevel'].filter(key=>published.manifest[key]!=null).map(key=>[key,published.manifest[key]]));
72
+ args={...args,model:{...args.model,asset:{kind:'compiled-code',id,bytesBase64:Buffer.from(published.bytes).toString('base64'),definition}}};
73
+ }
74
+ return studioBridge.call(owner,target,method,args,{signal:extra?.signal,requestId:a.requestId});
75
+ }
76
+ if(projectScope)throw new Error('STUDIO_NOT_CONNECTED');
77
+ return manager.run(owner,target,fn,{signal:extra?.signal,
78
+ ...(a.requestId?{requestId:a.requestId,fingerprint:JSON.stringify([method,args])}:{})});
79
+ };
80
+ const attachSceneAssets=async(s,references)=>{
81
+ for(const ref of references) if(typeof ref==='string' && /^asset:\/\/sha256\/[a-f0-9]{64}$/.test(ref)) {
82
+ const hash=ref.slice('asset://sha256/'.length), assetId=`pa_${hash}`;
83
+ if(!s.host.world.assetModule.hasAsset(`asset_${hash}`) && !s.host.world.assetModule.hasAsset(assetId)) {
84
+ await assets.repository.get(owner,assetId,{published:true});
85
+ await assets.repository.attach(owner,s.host.world.assetModule,[assetId]);
86
+ }
87
+ }
88
+ };
89
+ add('studio_project','Create, edit, run, save and reopen complete trusted code worlds in the active Studio workbench. Use operation=read to list projects; open takes id from projects[].id. run takes expectedRevision from open/write. save persists the active project. Read first for source, revision and createProject API guide. file/file_read edit named JavaScript and shader files, resource imports embedded binary resources. write saves a draft; patch applies a unique exact-fragment edit with expectedRevision; preview_batch stages up to 32 changes for diff review, apply_batch commits them atomically, discard_batch drops the preview, and undo_batch reverts the latest batch; run activates it; save persists live state and assets. Not a sandbox. Use scene_observe/interact for dynamic actions.',{
90
+ ...sceneSession, operation:z.enum(['read','write','patch','file_read','file','resource','preview_batch','apply_batch','discard_batch','undo_batch','run','save','open','close','create_world']), requestId:z.uuid().optional(),
91
+ create:z.boolean().optional(), source:z.string().min(1).optional(), name:z.string().min(1).optional(),
92
+ oldText:z.string().min(1).optional(), newText:z.string().optional(),
93
+ action:z.enum(['create','write','patch','rename','delete','add']).optional(), path:z.string().min(1).max(180).optional(),
94
+ newPath:z.string().max(180).optional(), content:z.string().optional(), mime:z.string().optional(), base64:z.string().optional(),
95
+ offset:z.number().int().min(0).optional(), limit:z.number().int().min(1).max(65536).optional(),
96
+ expectedRevision:z.number().int().nonnegative().optional(), id:z.string().optional(), project:z.record(z.string(),z.unknown()).optional(),
97
+ previewId:z.uuid().optional(),
98
+ operations:z.array(z.object({kind:z.enum(['file','resource']),action:z.enum(['create','write','patch','rename','delete','add']),
99
+ path:z.string().min(1).max(180),newPath:z.string().max(180).optional(),
100
+ content:z.string().optional(),oldText:z.string().optional(),newText:z.string().optional(),
101
+ mime:z.string().optional(),base64:z.string().optional()}).strict()).min(1).max(32).optional()
102
+ },(a,e)=>{
103
+ const {worldSessionId,requestId,...args}=a;
104
+ if(projectScope && (a.create || ['open','close','create_world'].includes(a.operation)))throw new Error('TASK_PROJECT_SWITCH_FORBIDDEN');
105
+ return sceneRun(a,'project',args,()=>{throw new Error('STUDIO_PROJECTS_UNAVAILABLE');},e);
106
+ });
107
+ const decodeModel=model=>{
108
+ if(model?.asset?.kind!=='glb') return model;
109
+ const source=z.object({kind:z.literal('glb'),name:z.string().min(1).max(128).optional(),bytesBase64:z.string().min(1).max(45*1024*1024),urdfBase64:z.string().min(1).max(2*1024*1024).optional(),review:z.record(z.string(),z.unknown()).optional()}).strict().parse(model.asset);
110
+ const decode=text=>{const bytes=Buffer.from(text,'base64');if(bytes.toString('base64')!==text) throw new Error('INVALID_RESOURCE_ENCODING');return new Uint8Array(bytes);};
111
+ return {...model,asset:{kind:'glb',bytes:decode(source.bytesBase64),...(source.name?{name:source.name}:{}),...(source.urdfBase64?{urdfBytes:decode(source.urdfBase64)}:{}),...(source.review?{review:source.review}:{})}};
112
+ };
113
+ const authoringAction=(a,skill,args,e)=>manager.run(owner,a.worldSessionId,(s,signal)=>s.host.execute(skill,args,signal),{requestId:a.requestId,fingerprint:JSON.stringify([skill,args]),signal:e.signal});
114
+ add('authoring_execute','Build static Three.js draft in a bounded isolated WASM runtime. Supports THREE, scene, clear; no network, imports, runtime callbacks or model references. Nothing enters physics until explicitly promoted.',{...session,code:z.string().min(1).max(32768),label:z.string().max(100).default('AI 创作'),requestId:z.uuid()},(a,e)=>authoringAction(a,'runAuthoringCode',{code:a.code,label:a.label},e));
115
+ add('authoring_observe','List draft node IDs, prepared assets, world entities and admission/verification states.',session,(a,e)=>run(a,s=>s.host.tools.call('listAuthoringNodes',{}),e));
116
+ const selection={...session,nodeId:id,usage:z.enum(['static','movable']),requestId:z.uuid()};
117
+ add('authoring_prepare','Compile one draft subtree as a local asset. Provisional admission is reported honestly; preparation does not insert an entity.',selection,(a,e)=>authoringAction(a,'prepareAuthoringAsset',{nodeId:a.nodeId,usage:a.usage},e));
118
+ for(const [name,skill] of [['authoring_promote','promoteAuthoringNode'],['authoring_update','updateAuthoringEntity']]) {
119
+ add(name,'Install or explicitly update one prepared draft entity through world commands. allowProvisional opts into editing state, never verified admission.',{...selection,allowProvisional:z.boolean().default(false)},(a,e)=>authoringAction(a,skill,{nodeId:a.nodeId,usage:a.usage,allowProvisional:a.allowProvisional},e));
120
+ }
121
+ add('authoring_verify','Check entity physics and navigation. Unexercised interaction remains unverified; use action_execute to exercise it.',{...session,nodeId:id},(a,e)=>run(a,s=>s.host.tools.call('verifyAuthoringEntity',{nodeId:a.nodeId}),e));
122
+ add('authoring_export','Save original successful code revisions, editable draft and promotion links. Does not bundle compiled assets or import a world.',session,(a,e)=>run(a,s=>manager.exportAuthoring(s),e));
123
+ add('world_observe','Observe bounded objects and physical relations.',{...session,offset:z.number().int().min(0).max(64).default(0),limit:z.number().int().min(1).max(50).default(25)},(a,e)=>run(a,s=>({worldSessionId:s.id,execution:s.host.world.mutationOwner?'running':'idle',...s.host.observe(a.offset,a.limit)}),e));
124
+ add('object_inspect','Inspect a real object and articulation evidence.',{...session,id},(a,e)=>run(a,s=>s.host.inspect(a.id),e));
125
+ add('skills_list','List audited remote actions and their argument schemas.',session,(a,e)=>run(a,()=>allowedSkills.map(name=>({name,inputSchema:z.toJSONSchema(actionSchemas[name])})),e));
126
+ add('action_execute','Execute an audited skill. Transport success is not physical verification.',{...session,skill:z.enum(allowedSkills),args:z.record(z.string(),z.unknown()),requestId:z.uuid()},(a,e)=>{
127
+ const args=actionSchemas[a.skill].parse(a.args);
128
+ return manager.run(owner,a.worldSessionId,async(s,signal)=>{
129
+ if(['spawnAsset','replaceAsset'].includes(a.skill)&&args.assetId.startsWith('pa_')){
130
+ const asset=await assets.repository.get(owner,args.assetId,{published:true});
131
+ if(assetAdmission(asset.manifest).status!=='ready')throw new Error('ASSET_NOT_READY');
132
+ await assets.repository.attach(owner,s.host.world.assetModule,[args.assetId]);
133
+ }
134
+ return s.host.execute(a.skill,args,signal);
135
+ },{requestId:a.requestId,fingerprint:JSON.stringify([a.skill,args]),signal:e.signal});
136
+ });
137
+ const check=z.object({id,kind:z.enum(['world-valid','object-exists','state-equals','interaction-verified','relation-exists','no-unresolved']),targetId:targetId.optional(),stateKey:id.optional(),value:z.union([z.string().max(200),z.number().finite(),z.boolean(),z.null()]).optional(),capability:id.optional(),source:z.string().min(1).max(64).optional(),subject:targetId.optional(),predicate:z.enum(['ON','NEAR','INSIDE','CONTAINS','SUPPORTS']).optional(),object:targetId.optional(),objectAnyOf:z.array(targetId).min(1).max(32).optional(),surfaceId:id.optional()}).strict();
138
+ add('world_verify','Verify caller-supplied criteria using Runtime evidence. With no criteria, runs the original cabinet/cup preset.',{...session,criteria:z.array(check).min(1).max(32).optional()},(a,e)=>{if(a.criteria) compileWorldAcceptance(a.criteria); return run(a,s=>s.host.verify(a.criteria),e);});
139
+ add('world_export','Atomically save and return SceneSerializer JSON; assets are not bundled.',session,(a,e)=>run(a,s=>manager.export(s),e));
140
+ add('world_save','Save an owned world and immutable published asset dependencies for recovery after service restart.',session,(a,e)=>run(a,s=>manager.save(owner,s),e));
141
+ add('world_restore','Create a new private session from your server-issued save ID. Verifies all hashes and restores via SceneSerializer; historical action evidence is not reused.',{saveId:z.uuid(),requestId:z.uuid()},a=>manager.restore(owner,a.saveId,a.requestId));
142
+ add('scene_observe','Observe a target, the full scene, or a lightweight paginated object list. Use limit and offset to avoid global relations and affordance expansion.',{...sceneSession,target:z.string().min(1).max(256).optional(),actor:id.optional(),offset:z.number().int().nonnegative().max(1000000).optional(),limit:z.number().int().min(1).max(1000).optional()},(a,e)=>{
143
+ if(a.target && (a.offset!=null||a.limit!=null))throw new Error('SCENE_OBSERVE_MODE_CONFLICT');
144
+ if(a.offset!=null && a.limit==null)throw new Error('PAGE_LIMIT_REQUIRED');
145
+ const query={actor:a.actor,...(a.limit!=null?{limit:a.limit,offset:a.offset||0}:{})};
146
+ return sceneRun(a,'observe',{target:a.target,...query},s=>a.target?s.host.scene.inspect(a.target,{actor:a.actor}):s.host.scene.observe(query),e);
147
+ });
148
+ add('scene_thermal','Read or run real thermal simulation in the active Scene: list entities, inspect per-part temperatures, get measured time-series, set heat power or advance up to 10 seconds of WorldRuntime. Write operations require requestId; thermal simulation is a declared model, not real-world proof.',{
149
+ ...sceneSession,
150
+ operation:z.enum(['list','inspect','series','setPower','run']),
151
+ targetId:targetId.optional(),nodeId:id.optional(),limit:z.number().int().min(1).max(600).optional(),
152
+ powerW:z.number().finite().min(-1e9).max(1e9).optional(),
153
+ durationSec:z.number().positive().max(10).optional(),
154
+ requestId:z.uuid().optional()
155
+ },(a,e)=>{
156
+ if(['setPower','run'].includes(a.operation)&&!a.requestId)throw new Error('REQUEST_ID_REQUIRED');
157
+ const args=Object.fromEntries(Object.entries(a).filter(([key,value])=>!['worldSessionId','requestId'].includes(key)&&value!==undefined));
158
+ return sceneRun(a,'thermal',args,s=>s.host.scene.thermalExperiment(args),e);
159
+ });
160
+ add('scene_apply','Apply structured scene edits with revision protection and explicit partial results.',{...sceneSession,requestId:z.uuid(),expectedRevision:z.number().int().nonnegative().optional(),operations:z.array(z.record(z.string(),z.unknown())).min(1).max(32)},(a,e)=>sceneRun(a,'apply',{requestId:a.requestId,expectedRevision:a.expectedRevision,operations:a.operations},async s=>{await attachSceneAssets(s,a.operations.map(op=>op.type==='add'?op.model?.asset:op.asset));return s.host.scene.apply({expectedRevision:a.expectedRevision,operations:a.operations});},e));
161
+ add('scene_interact','Start a real action and return a queryable JobRef immediately.',{...sceneSession,requestId:z.uuid(),interaction:z.record(z.string(),z.unknown())},(a,e)=>sceneRun(a,'interact',{interaction:a.interaction},s=>s.host.startSceneInteraction(a.interaction),e));
162
+ const job={...sceneSession,jobId:z.string().regex(/^job_[a-f0-9-]+$/)};
163
+ add('scene_job','Read task completion and physical verification separately.',job,(a,e)=>sceneRun(a,'job',{jobId:a.jobId},s=>s.host.scene.getJob(a.jobId),e));
164
+ add('scene_cancel','Request task cancellation and query until terminal.',job,(a,e)=>sceneRun(a,'cancel',{jobId:a.jobId},s=>s.host.scene.cancelJob(a.jobId),e));
165
+ add('scene_verify','Evaluate explicit postconditions through the common verifier.',{...sceneSession,criteria:z.array(check).min(1).max(32)},(a,e)=>sceneRun(a,'verify',{criteria:a.criteria},s=>s.host.scene.verify(a.criteria),e));
166
+ add('scene_add_model','Add a recipe using model={id,asset:{schema:"agentscape.asset-recipe",schemaVersion:1,id,parts:[{id,geometry:{type:"box",size:[1,1,1]}}]},position:[0,0,0]}. Analyze GLB/URDF with mode=prepare; mode=screen runs bounded, isolated Rapier tests of source-bound kinematic candidates (model.proposalId and optional model.hypothesisIds), never grants actions; mode=add imports reviewed assets. GLB uses bytesBase64.',{
167
+ ...sceneSession,requestId:z.uuid(),mode:z.enum(['prepare','screen','add']).default('add'),model:z.object({
168
+ id:sceneObjectIdSchema.optional(),position:sceneVector3Schema.optional(),transform:sceneTransformSchema.optional(),
169
+ level:z.enum(['visual','physical','interactive']).optional(),
170
+ asset:z.union([recipeSchema,z.string(),z.record(z.string(),z.unknown()).refine(asset=>asset.schema!=='agentscape.asset-recipe')])
171
+ }).passthrough()
172
+ },(a,e)=>sceneRun(a,'addModel',{model:a.model,mode:a.mode},async s=>{
173
+ const model=decodeModel(a.model);
174
+ if(a.mode==='prepare')return s.host.scene.prepareAsset(model.asset);
175
+ if(a.mode==='screen')return s.host.scene.screenAsset({...model.asset,proposalId:model.proposalId,hypothesisIds:model.hypothesisIds});
176
+ await attachSceneAssets(s,[model.asset]);
177
+ const added=await s.host.scene.addModel(model);
178
+ if(a.mode==='add' && added.status==='succeeded' && (['agentscape.mechanical-draft','agentscape.asset-recipe'].includes(model.asset?.schema) || model.asset?.kind==='three-code'))
179
+ s.forge.record(model.id,model.asset,s.host.world.store.get(model.id).assetId,s.host.world);
180
+ return added;
181
+ },e));
182
+ add('scene_object_definition','Inspect source evidence, preview precise field changes, or apply a single instance revision after asset compilation and runtime admission. Session-scoped AI-declared mechanical drafts, recipes and three-code definitions only.',{
183
+ ...sceneSession,objectId:id,operation:z.enum(['inspect','preview','apply','fork']),expectedRevision:z.number().int().positive().optional(),
184
+ changes:z.array(z.object({path:z.string().min(1).max(192),value:z.unknown()}).strict()).min(1).max(8).optional(),
185
+ previewId:z.uuid().optional(),requestId:z.uuid().optional()
186
+ },(a,e)=>{
187
+ if(a.operation!=='inspect' && !a.requestId)throw new Error('REQUEST_ID_REQUIRED');
188
+ if(a.operation==='fork'){
189
+ if(!a.worldSessionId)throw new Error('FORK_REQUIRES_PRIVATE_WORLD');
190
+ return manager.run(owner,a.worldSessionId,async session=>{
191
+ const record=session.host.world.store.get(a.objectId);
192
+ if(!record || !/^pa_[a-f0-9]{64}$/.test(record.assetId))
193
+ throw new Error('OBJECT_DEFINITION_UNAVAILABLE');
194
+ const published=await manager.repository.get(owner,record.assetId,{published:true});
195
+ if(published.build.schema!=='agentscape.project-asset.v1')
196
+ throw new Error('OBJECT_DEFINITION_UNAVAILABLE');
197
+ return session.forge.fork(session.host.world,a.objectId,published.build.definition,record.assetId);
198
+ },{signal:e?.signal,requestId:a.requestId,fingerprint:JSON.stringify(['object-fork',a.objectId])});
199
+ }
200
+ const args={operation:a.operation,objectId:a.objectId,expectedRevision:a.expectedRevision,changes:a.changes,previewId:a.previewId};
201
+ return sceneRun(a,'objectDefinition',args,async s=>{
202
+ if(a.operation==='inspect')return s.forge.inspect(s.host.world,a.objectId);
203
+ if(a.operation==='preview')return s.forge.preview(s.host.world,a.objectId,a.expectedRevision,a.changes);
204
+ return s.forge.apply(s.host.world,s.host.scene,a.objectId,a.expectedRevision,a.previewId,{executor:s.host.executor});
205
+ },e);
206
+ });
207
+ add('scene_import','Import a previously exported scene_save project bundle into the active Scene. Validates embedded hashes, assets and environment in a staging world; historical interaction evidence is not reused.',{...sceneSession,requestId:z.uuid(),bundle:z.record(z.string(),z.unknown())},(a,e)=>{
208
+ if(Buffer.byteLength(JSON.stringify(a.bundle))>manager.maxExportBytes)throw new Error('IMPORT_LIMIT');
209
+ return sceneRun(a,'importProject',{bundle:a.bundle},async s=>{
210
+ const result=await s.host.scene.importProject(a.bundle);
211
+ s.forge.restore(s.host.world,result.value.editable||[]);
212
+ return {...result,value:{status:result.value.status,objects:result.value.objects,editableRestored:result.value.editable?.length||0}};
213
+ },e);
214
+ });
215
+ add('scene_save','Export a complete portable project with bounded embedded dependencies.',sceneSession,(a,e)=>sceneRun(a,'save',{},async s=>{
216
+ const result=await s.host.scene.save({editable:s.forge.export(s.host.world),readResource:async url=>{
217
+ const prefix='data:model/gltf-binary;base64,';
218
+ if(!url?.startsWith(prefix)) throw new Error('RESOURCE_UNAVAILABLE');
219
+ return new Uint8Array(Buffer.from(url.slice(prefix.length),'base64'));
220
+ }});
221
+ if(Buffer.byteLength(JSON.stringify(result))>manager.maxExportBytes) throw new Error('EXPORT_LIMIT');
222
+ return result;
223
+ },e));
224
+ add('scene_set_style','Select a declarative StylePack. Headless worlds report deferred rendering.',{...sceneSession,style:z.union([z.string().max(128),z.record(z.string(),z.unknown())]),fallback:z.enum(['reject','declared']).default('reject')},(a,e)=>sceneRun(a,'setStyle',{style:a.style,fallback:a.fallback},s=>s.host.scene.setStyle(a.style,{fallback:a.fallback}),e));
225
+ }
@@ -0,0 +1,23 @@
1
+ import { getQuickJS } from 'quickjs-emscripten';
2
+ import { readFile } from 'node:fs/promises';
3
+ const chunks=[];let size=0;
4
+ for await(const chunk of process.stdin) {size+=chunk.length;if(size>3145728)throw Error('SANDBOX_INPUT_LIMIT');chunks.push(chunk);}
5
+ const request=JSON.parse(Buffer.concat(chunks).toString('utf8'));
6
+ const bundle=await readFile('/app/bundle.js','utf8');
7
+ const QuickJS=await getQuickJS();const runtime=QuickJS.newRuntime();
8
+ runtime.setMemoryLimit(96*1024*1024);runtime.setMaxStackSize(1024*1024);
9
+ const vm=runtime.newContext();let deadline=Date.now()+5000;
10
+ runtime.setInterruptHandler(()=>Date.now()>deadline);
11
+ try {
12
+ const setup=vm.evalCode(bundle);if(setup.error){setup.error.dispose();throw Error('SANDBOX_INIT_FAILED');}setup.value.dispose();
13
+ deadline=Date.now()+1500;
14
+ const expression=request.mode==='procedural'
15
+ ? `AuthoringSandbox.build(${JSON.stringify(request.source)})`
16
+ : `AuthoringSandbox.execute(${JSON.stringify(request.code)},${JSON.stringify(request.document)})`;
17
+ const result=vm.evalCode(`JSON.stringify(${expression})`);
18
+ if(result.error){const error=vm.dump(result.error);result.error.dispose();throw Error(Date.now()>deadline?'BUILD_TIMEOUT':String(error?.message||'BUILD_EXECUTION_FAILED').slice(0,500));}
19
+ const json=vm.getString(result.value);result.value.dispose();
20
+ if(json.length>2097152)throw Error('BUILD_OUTPUT_LIMIT');
21
+ process.stdout.write(JSON.stringify({document:JSON.parse(json)}));
22
+ } catch(error){process.stdout.write(JSON.stringify({error:String(error.message).slice(0,500)}));process.exitCode=1;}
23
+ finally {vm.dispose();runtime.dispose();}
@@ -0,0 +1,21 @@
1
+ import { createHash, timingSafeEqual } from 'node:crypto';
2
+ const digest=value=>createHash('sha256').update(value).digest();
3
+ export function createSecurity(tokens,{origins=[],hosts=['127.0.0.1','localhost'],maxBody=65536,rate=120}={}) {
4
+ if(!tokens.length || tokens.some(t=>typeof t.token!=='string'||t.token.length<32||!t.identity)) throw new Error('Configure independent MCP tokens (32+ characters)');
5
+ const buckets=new Map();
6
+ return async(req)=>{
7
+ let host; try {host=new URL(`http://${req.headers.host}`).hostname;} catch {throw Object.assign(new Error(),{status:403});}
8
+ if(!hosts.includes(host) || req.headers.origin && !origins.includes(req.headers.origin)) throw Object.assign(new Error(),{status:403});
9
+ const value=String(req.headers.authorization||'').replace(/^Bearer /,'');
10
+ const principal=tokens.find(t=>timingSafeEqual(digest(t.token),digest(value)));
11
+ if(!principal) throw Object.assign(new Error(),{status:401});
12
+ const now=Date.now(),bucket=buckets.get(principal.identity)||{start:now,count:0};
13
+ if(now-bucket.start>60000){bucket.start=now;bucket.count=0;} buckets.set(principal.identity,bucket);
14
+ if(++bucket.count>rate) throw Object.assign(new Error(),{status:429});
15
+ if(Number(req.headers['content-length'])>maxBody) throw Object.assign(new Error(),{status:413});
16
+ let size=0; const chunks=[];
17
+ for await(const chunk of req) {size+=chunk.length;if(size>maxBody) throw Object.assign(new Error(),{status:413});chunks.push(chunk);}
18
+ let body; try {body=size?JSON.parse(Buffer.concat(chunks).toString()):undefined;} catch {throw Object.assign(new Error(),{status:400});}
19
+ return {owner:principal.identity,body};
20
+ };
21
+ }
@@ -0,0 +1,9 @@
1
+ {"id":"MCP-000","type":"feat","title":"独立工作区及基线验证","status":"DONE","priority":"P1","path":"apps/mcp-server","depends":[],"files":["apps/mcp-server/README.md"],"criteria":["独立工作区及基线验证"]}
2
+ {"id":"MCP-001","type":"feat","title":"正式装配的 Headless Host 与真实物理动作","status":"DONE","priority":"P1","path":"apps/mcp-server","depends":["MCP-000"],"files":["apps/mcp-server/README.md"],"criteria":["正式装配的 Headless Host 与真实物理动作"]}
3
+ {"id":"MCP-002","type":"feat","title":"私有会话、互斥、取消及资源预算","status":"DONE","priority":"P1","path":"apps/mcp-server","depends":["MCP-001"],"files":["apps/mcp-server/README.md"],"criteria":["私有会话、互斥、取消及资源预算"]}
4
+ {"id":"MCP-003","type":"feat","title":"鉴权的 MCP v2 Streamable HTTP 九工具","status":"DONE","priority":"P1","path":"apps/mcp-server","depends":["MCP-002"],"files":["apps/mcp-server/README.md"],"criteria":["鉴权的 MCP v2 Streamable HTTP 九工具"]}
5
+ {"id":"MCP-004","type":"feat","title":"官方 MCP 客户端真实开柜取杯放置验收","status":"DONE","priority":"P1","path":"apps/mcp-server","depends":["MCP-003"],"files":["apps/mcp-server/README.md"],"criteria":["官方 MCP 客户端真实开柜取杯放置验收"]}
6
+ {"id":"MCP-005","type":"test","title":"安全和项目回归验证","status":"DONE","priority":"P1","path":"apps/mcp-server","depends":["MCP-004"],"files":["apps/mcp-server/README.md"],"criteria":["安全和项目回归验证"]}
7
+ {"id":"MCP-006","type":"feat","title":"通过隔离 Three.js 草稿编译与晋升操作真实世界","status":"DONE","priority":"P1","path":"apps/mcp-server","depends":["MCP-005"],"files":["apps/mcp-server/AUTHORING.md","apps/mcp-server/IsolatedAuthoringExecutor.js","tests/mcp/authoring-workflow.test.js"],"criteria":["复用无头创作晋升链并隔离远程代码","通过真实物理拾取放置新资产","参数化验收及源码导出","全量检查与 AgentDock 验收通过"]}
8
+ {"id":"MCP-007","type":"feat","title":"容器隔离的程序化资产构建发布及不可变版本","status":"DONE","priority":"P1","path":"apps/mcp-server","depends":["MCP-006"],"files":["apps/mcp-server/PROGRAMMATIC-ASSETS.md","application/programmatic-assets/ProgrammaticAssetBuilder.js"],"criteria":["无安全隔离时拒绝源码执行","复用 GLB 与 Manifest 管线发布私有资产","源码与产物原子持久化且不可变"]}
9
+ {"id":"MCP-008","type":"test","title":"程序化交互世界重启恢复与版本升级验收","status":"DONE","priority":"P1","path":"apps/mcp-server","depends":["MCP-007"],"files":["tests/mcp/programmatic-world.test.js","tests/mcp/container-security.test.js"],"criteria":["真实桌面放置和冰箱开关门","服务重启后恢复资产与世界并重新验证","所有权、哈希、取消及失败回滚通过"]}
@@ -0,0 +1,157 @@
1
+ const SAFE_FORWARD_HEADERS = new Set(['accept', 'content-type']);
2
+ export const INVOKE_TIMEOUT_MS = 185_000;
3
+ export const HEALTH_TIMEOUT_MS = 3_000;
4
+ export const HEALTH_SLOW_MS = 1_500;
5
+
6
+ export const CAPABILITIES = Object.freeze({
7
+ AGENT: 'agent',
8
+ ASSET_COMPILE: 'asset.compile'
9
+ });
10
+
11
+ export const DEPLOYMENT_ADAPTERS = Object.freeze({
12
+ [CAPABILITIES.AGENT]: Object.freeze({
13
+ urlEnv: 'AGENT_ADAPTER_URL',
14
+ authorizationEnv: 'AGENT_ADAPTER_AUTHORIZATION',
15
+ healthUrlEnv: 'AGENT_ADAPTER_HEALTH_URL'
16
+ }),
17
+ [CAPABILITIES.ASSET_COMPILE]: Object.freeze({
18
+ urlEnv: 'ASSET_COMPILE_ADAPTER_URL',
19
+ authorizationEnv: 'ASSET_COMPILE_ADAPTER_AUTHORIZATION',
20
+ healthUrlEnv: 'ASSET_COMPILE_ADAPTER_HEALTH_URL'
21
+ })
22
+ });
23
+
24
+ export function capabilityAvailability(env = process.env) {
25
+ return Object.fromEntries(Object.entries(DEPLOYMENT_ADAPTERS).map(([capability, adapter]) => [
26
+ capability,
27
+ { available: Boolean(normalizeTarget(env[adapter.urlEnv])) }
28
+ ]));
29
+ }
30
+
31
+ export async function invokeCapability(req, res, capability, { env = process.env, fetchImpl = fetch, timeoutMs = INVOKE_TIMEOUT_MS } = {}) {
32
+ if (req.method !== 'POST') return sendJson(res, 405, { code: 'METHOD_NOT_ALLOWED' }, { allow: 'POST' });
33
+ const adapter = DEPLOYMENT_ADAPTERS[capability];
34
+ if (!adapter) return sendJson(res, 404, { code: 'CAPABILITY_NOT_FOUND' });
35
+ const target = normalizeTarget(env[adapter.urlEnv]);
36
+ if (!target) return sendJson(res, 503, { code: 'CAPABILITY_UNAVAILABLE' });
37
+
38
+ const controller = new AbortController();
39
+ const disconnected=()=>{ if (!res.writableEnded) controller.abort(); };
40
+ res.once?.('close',disconnected);
41
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
42
+ try {
43
+ const body = await requestBody(req);
44
+ const response = await fetchImpl(target, {
45
+ method: 'POST',
46
+ headers: forwardHeaders(req.headers, env[adapter.authorizationEnv]),
47
+ body,
48
+ redirect: 'error',
49
+ signal: controller.signal
50
+ });
51
+ const bytes = Buffer.from(await response.arrayBuffer());
52
+ if (res.destroyed) return;
53
+ res.statusCode = response.status;
54
+ const contentType = response.headers.get('content-type');
55
+ if (contentType) res.setHeader('content-type', contentType);
56
+ res.setHeader('cache-control', 'no-store');
57
+ res.end(bytes);
58
+ } catch (error) {
59
+ if (res.headersSent || res.writableEnded || res.destroyed) return;
60
+ if (error?.name === 'AbortError') return sendJson(res, 504, { code: 'ADAPTER_TIMEOUT', message: safeMessage(error) });
61
+ sendJson(res, 502, { code: 'ADAPTER_UNAVAILABLE', message: safeMessage(error) });
62
+ } finally {
63
+ clearTimeout(timer);
64
+ res.removeListener?.('close',disconnected);
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Probe each configured adapter's health endpoint from the server.
70
+ * Never returns URLs, headers, or upstream bodies: only state, latency and a reason code.
71
+ * state: unconfigured | ok | slow | down
72
+ */
73
+ export async function probeCapabilities(env = process.env, { fetchImpl = fetch, timeoutMs = HEALTH_TIMEOUT_MS, now = () => Date.now() } = {}) {
74
+ const entries = await Promise.all(Object.entries(DEPLOYMENT_ADAPTERS).map(async ([capability, adapter]) => {
75
+ const checkedAt = new Date(now()).toISOString();
76
+ const invokeTarget = normalizeTarget(env[adapter.urlEnv]);
77
+ if (!invokeTarget) {
78
+ return [capability, { available: false, state: 'unconfigured', latencyMs: null, reason: 'NOT_CONFIGURED', checkedAt }];
79
+ }
80
+ const healthTarget = normalizeTarget(env[adapter.healthUrlEnv]) || new URL('/health', invokeTarget).toString();
81
+ const controller = new AbortController();
82
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
83
+ const started = now();
84
+ try {
85
+ const response = await fetchImpl(healthTarget, {
86
+ method: 'GET',
87
+ headers: forwardHeaders({ accept: 'application/json' }, env[adapter.authorizationEnv]),
88
+ redirect: 'error',
89
+ signal: controller.signal
90
+ });
91
+ const latencyMs = Math.max(0, now() - started);
92
+ if (!response.ok) {
93
+ return [capability, { available: true, state: 'down', latencyMs, reason: 'HTTP_' + response.status, checkedAt }];
94
+ }
95
+ return [capability, { available: true, state: latencyMs > HEALTH_SLOW_MS ? 'slow' : 'ok', latencyMs, reason: null, checkedAt }];
96
+ } catch (error) {
97
+ return [capability, { available: true, state: 'down', latencyMs: null, reason: error?.name === 'AbortError' ? 'TIMEOUT' : 'UNREACHABLE', checkedAt }];
98
+ } finally {
99
+ clearTimeout(timer);
100
+ }
101
+ }));
102
+ return Object.fromEntries(entries);
103
+ }
104
+
105
+ export async function sendCapabilityHealth(req, res, env = process.env, options = {}) {
106
+ if (req.method !== 'GET') return sendJson(res, 405, { code: 'METHOD_NOT_ALLOWED' }, { allow: 'GET' });
107
+ return sendJson(res, 200, { capabilities: await probeCapabilities(env, options) });
108
+ }
109
+
110
+ export function sendCapabilityStatus(req, res, env = process.env) {
111
+ if (req.method !== 'GET') return sendJson(res, 405, { code: 'METHOD_NOT_ALLOWED' }, { allow: 'GET' });
112
+ return sendJson(res, 200, { capabilities: capabilityAvailability(env) });
113
+ }
114
+
115
+ function forwardHeaders(headers = {}, deploymentAuthorization = '') {
116
+ const forwarded = {};
117
+ for (const [key, value] of Object.entries(headers)) {
118
+ if (SAFE_FORWARD_HEADERS.has(key.toLowerCase()) && value) forwarded[key.toLowerCase()] = String(value);
119
+ }
120
+ const authorization = String(deploymentAuthorization || '').trim();
121
+ if (authorization) forwarded.authorization = authorization;
122
+ return forwarded;
123
+ }
124
+
125
+ async function requestBody(req) {
126
+ if (Buffer.isBuffer(req.body)) return req.body;
127
+ if (typeof req.body === 'string') return Buffer.from(req.body);
128
+ if (req.body && typeof req.body === 'object') {
129
+ const type = String(req.headers?.['content-type'] || '');
130
+ if (type.includes('application/json')) return Buffer.from(JSON.stringify(req.body));
131
+ }
132
+ const chunks = [];
133
+ for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
134
+ return Buffer.concat(chunks);
135
+ }
136
+
137
+ function normalizeTarget(value) {
138
+ const raw = String(value || '').trim();
139
+ if (!raw) return null;
140
+ try {
141
+ const url = new URL(raw);
142
+ if (!['http:', 'https:'].includes(url.protocol)) return null;
143
+ return url.toString();
144
+ } catch { return null; }
145
+ }
146
+
147
+ function safeMessage(error) {
148
+ return error?.name === 'AbortError' ? '适配器请求超时' : '适配器不可用';
149
+ }
150
+
151
+ function sendJson(res, status, payload, headers = {}) {
152
+ res.statusCode = status;
153
+ res.setHeader('content-type', 'application/json; charset=utf-8');
154
+ res.setHeader('cache-control', 'no-store');
155
+ for (const [key, value] of Object.entries(headers)) res.setHeader(key, value);
156
+ res.end(JSON.stringify(payload));
157
+ }
@@ -0,0 +1,7 @@
1
+ # Server
2
+
3
+ 服务端能力适配与模型代理。CapabilityAdapterRegistry.js 被根 api/capabilities 薄入口使用。
4
+ openai-compatible-agent-gateway.mjs 通过 npm run agent:gateway 启动;凭据保持在服务端环境。
5
+ 不拥有浏览器 World 状态,浏览器模块不得导入本目录。
6
+
7
+ 任务见 tasks.jsonl。验证:npm run test -- tests/contracts。