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.
- package/LICENSE +21 -0
- package/README.md +19 -2
- package/cli.mjs +53 -0
- package/dist/ArticulationVerifier-BfGxXY8V.js +337 -0
- package/dist/ArticulationVerifier-BfGxXY8V.js.map +1 -0
- package/dist/AssetCompiler-BLj09iu1.js +2424 -0
- package/dist/AssetCompiler-BLj09iu1.js.map +1 -0
- package/dist/AssetModule-DME-XaFS.js +2637 -0
- package/dist/AssetModule-DME-XaFS.js.map +1 -0
- package/dist/AssetRecipe-g8dZBhgJ.js +298 -0
- package/dist/AssetRecipe-g8dZBhgJ.js.map +1 -0
- package/dist/BrowserCodeWorker.js +53856 -0
- package/dist/BrowserCodeWorker.js.map +1 -0
- package/dist/CarryCapability-CXwHU5ay.js +104 -0
- package/dist/CarryCapability-CXwHU5ay.js.map +1 -0
- package/dist/KinematicHypothesisScreen-C3TKiuYR.js +241 -0
- package/dist/KinematicHypothesisScreen-C3TKiuYR.js.map +1 -0
- package/dist/ObjectTransform-BlQUNK7c.js +61 -0
- package/dist/ObjectTransform-BlQUNK7c.js.map +1 -0
- package/dist/RapierPhysicsBackend-B2wQe_Vl.js +3259 -0
- package/dist/RapierPhysicsBackend-B2wQe_Vl.js.map +1 -0
- package/dist/RenderingSystem-WIr1ZuGu.js +1042 -0
- package/dist/RenderingSystem-WIr1ZuGu.js.map +1 -0
- package/dist/ScenePresentation-LsYiDxbm.js +152 -0
- package/dist/ScenePresentation-LsYiDxbm.js.map +1 -0
- package/dist/SceneProject-K7HH1s8o.js +2687 -0
- package/dist/SceneProject-K7HH1s8o.js.map +1 -0
- package/dist/SceneSerializer-zOzbX4jZ.js +932 -0
- package/dist/SceneSerializer-zOzbX4jZ.js.map +1 -0
- package/dist/SimulationProfile-DSYZbBLQ.js +165 -0
- package/dist/SimulationProfile-DSYZbBLQ.js.map +1 -0
- package/dist/StylePack-DcRa_kU0.js +88 -0
- package/dist/StylePack-DcRa_kU0.js.map +1 -0
- package/dist/WorldArchive-BiFGLt--.js +451 -0
- package/dist/WorldArchive-BiFGLt--.js.map +1 -0
- package/dist/WorldCommands-Debj7V4L.js +2207 -0
- package/dist/WorldCommands-Debj7V4L.js.map +1 -0
- package/dist/WorldIO-Ch8QBfKY.js +151 -0
- package/dist/WorldIO-Ch8QBfKY.js.map +1 -0
- package/dist/admission-CVEvsrdz.js +121 -0
- package/dist/admission-CVEvsrdz.js.map +1 -0
- package/dist/blankWorld-B0MW6g7q.js +75 -0
- package/dist/blankWorld-B0MW6g7q.js.map +1 -0
- package/dist/core.d.ts +68 -0
- package/dist/core.js +209 -0
- package/dist/core.js.map +1 -0
- package/dist/disposeObject3D-DIMzy0FA.js +128 -0
- package/dist/disposeObject3D-DIMzy0FA.js.map +1 -0
- package/dist/environments-HOe3sJXH.js +567 -0
- package/dist/environments-HOe3sJXH.js.map +1 -0
- package/dist/gltfIO-BzVKLyaL.js +339 -0
- package/dist/gltfIO-BzVKLyaL.js.map +1 -0
- package/dist/grandUrbanBlock-DRndRZjF.js +515 -0
- package/dist/grandUrbanBlock-DRndRZjF.js.map +1 -0
- package/dist/index.d.ts +345 -0
- package/dist/index.js +16952 -0
- package/dist/index.js.map +1 -0
- package/dist/magicCabin-CfBZjx2Q.js +11019 -0
- package/dist/magicCabin-CfBZjx2Q.js.map +1 -0
- package/dist/manifests-D0LwbJ36.js +866 -0
- package/dist/manifests-D0LwbJ36.js.map +1 -0
- package/dist/mcp.d.ts +2 -0
- package/dist/mcp.js +1 -0
- package/dist/monumentHall-awZiGtda.js +403 -0
- package/dist/monumentHall-awZiGtda.js.map +1 -0
- package/dist/node.d.ts +16 -0
- package/dist/node.js +26 -0
- package/dist/parts-DrEcfJRl.js +37 -0
- package/dist/parts-DrEcfJRl.js.map +1 -0
- package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
- package/dist/ruinedCourtyard-DuF7NmUU.js +696 -0
- package/dist/ruinedCourtyard-DuF7NmUU.js.map +1 -0
- package/dist/runtime/application/AgentTools.js +28 -0
- package/dist/runtime/application/README.md +14 -0
- package/dist/runtime/application/agent/ProgressiveAgentTools.js +92 -0
- package/dist/runtime/application/agent/StudioMcpAllowlist.js +10 -0
- package/dist/runtime/application/agent/StudioProjectTools.js +18 -0
- package/dist/runtime/application/agent/TaskEvidence.js +199 -0
- package/dist/runtime/application/buildTaskObservation.js +117 -0
- package/dist/runtime/application/code-execution/AuthoringSandboxEntry.js +50 -0
- package/dist/runtime/application/code-execution/BrowserCodeExecutor.js +35 -0
- package/dist/runtime/application/code-execution/BrowserCodeWorker.js +17 -0
- package/dist/runtime/application/code-execution/RemoteAuthoringDocument.js +82 -0
- package/dist/runtime/application/createSession.js +66 -0
- package/dist/runtime/application/createWorldAuthoringContext.js +400 -0
- package/dist/runtime/application/generation/GenerationOrchestrator.js +630 -0
- package/dist/runtime/application/generation/GenerationRuntime.js +215 -0
- package/dist/runtime/application/generation/PromptHybridWorldOrchestrator.js +289 -0
- package/dist/runtime/application/native-scene/CodeProject.js +215 -0
- package/dist/runtime/application/native-scene/CodeProjectModules.js +143 -0
- package/dist/runtime/application/native-scene/ExampleWorldCatalog.js +35 -0
- package/dist/runtime/application/native-scene/NativeArticulation.js +53 -0
- package/dist/runtime/application/native-scene/NativeEditableRegistry.js +150 -0
- package/dist/runtime/application/native-scene/NativeEnvironmentGeometry.js +85 -0
- package/dist/runtime/application/native-scene/NativeLightingInspection.js +33 -0
- package/dist/runtime/application/native-scene/NativeMaterialInspection.js +52 -0
- package/dist/runtime/application/native-scene/NativeOverlayCheckpoint.js +127 -0
- package/dist/runtime/application/native-scene/NativePhysicsGeometry.js +64 -0
- package/dist/runtime/application/native-scene/NativeRenderDiscovery.js +51 -0
- package/dist/runtime/application/native-scene/NativeSceneHost.js +406 -0
- package/dist/runtime/application/native-scene/NativeSceneInspection.js +203 -0
- package/dist/runtime/application/native-scene/NativeSceneOverlay.js +116 -0
- package/dist/runtime/application/native-scene/NativeSceneQuery.js +123 -0
- package/dist/runtime/application/native-scene/NativeSceneReview.js +132 -0
- package/dist/runtime/application/native-scene/NativeThreeModule.js +16 -0
- package/dist/runtime/application/native-scene/SceneObserver.js +97 -0
- package/dist/runtime/application/native-scene/VisualCapturePolicy.js +4 -0
- package/dist/runtime/application/object-forge/SceneObjectForge.js +263 -0
- package/dist/runtime/application/programmatic-assets/ProgrammaticAssetBuilder.js +59 -0
- package/dist/runtime/application/programmatic-assets/ProgrammaticAssetContract.js +22 -0
- package/dist/runtime/application/programmatic-assets/ThreeCodeAsset.js +40 -0
- package/dist/runtime/application/scene/CapabilityResolver.js +90 -0
- package/dist/runtime/application/scene/NativeEditableContracts.js +18 -0
- package/dist/runtime/application/scene/RequestWindow.js +54 -0
- package/dist/runtime/application/scene/SceneAgentTools.js +21 -0
- package/dist/runtime/application/scene/SceneContracts.js +49 -0
- package/dist/runtime/application/scene/SceneEditService.js +154 -0
- package/dist/runtime/application/scene/SceneFacade.js +356 -0
- package/dist/runtime/application/scene/SceneInteractionAdapters.js +41 -0
- package/dist/runtime/application/scene/SceneJobController.js +320 -0
- package/dist/runtime/application/scene/SceneLifecycle.js +57 -0
- package/dist/runtime/application/scene/ScenePackage.js +173 -0
- package/dist/runtime/application/scene/ScenePersistence.js +50 -0
- package/dist/runtime/application/scene/SceneProject.js +95 -0
- package/dist/runtime/application/scene/SceneSkillNames.js +5 -0
- package/dist/runtime/application/scene/StarterScene.js +56 -0
- package/dist/runtime/application/scene/WorldArchive.js +89 -0
- package/dist/runtime/application/scene/WorldDirectory.js +20 -0
- package/dist/runtime/application/scene/WorldDocument.js +76 -0
- package/dist/runtime/application/scene/WorldIO.js +103 -0
- package/dist/runtime/application/scene/WorldStorage.js +155 -0
- package/dist/runtime/application/skills/SkillRegistry.js +193 -0
- package/dist/runtime/application/skills/packs/acceptanceSkills.js +32 -0
- package/dist/runtime/application/skills/packs/affordanceSkills.js +36 -0
- package/dist/runtime/application/skills/packs/assetSkills.js +46 -0
- package/dist/runtime/application/skills/packs/authoringSkills.js +16 -0
- package/dist/runtime/application/skills/packs/batchSkills.js +22 -0
- package/dist/runtime/application/skills/packs/codeSkills.js +106 -0
- package/dist/runtime/application/skills/packs/generationSkills.js +45 -0
- package/dist/runtime/application/skills/packs/interactionSkills.js +46 -0
- package/dist/runtime/application/skills/packs/recoverySkills.js +80 -0
- package/dist/runtime/application/skills/packs/sceneSkills.js +24 -0
- package/dist/runtime/application/skills/packs/spatialSkills.js +35 -0
- package/dist/runtime/application/skills/packs/verificationSkills.js +14 -0
- package/dist/runtime/application/skills/packs/worldSkills.js +45 -0
- package/dist/runtime/application/skills/registerCoreSkills.js +31 -0
- package/dist/runtime/application/skills/skillPrimitives.js +4 -0
- package/dist/runtime/application/tasks/CabinetCupTask.js +76 -0
- package/dist/runtime/application/tasks.jsonl +67 -0
- package/dist/runtime/application/world-authoring/AuthoringAssetProducer.js +42 -0
- package/dist/runtime/application/world-authoring/AuthoringDiff.js +149 -0
- package/dist/runtime/application/world-authoring/AuthoringDocument.js +825 -0
- package/dist/runtime/application/world-authoring/AuthoringExecutionHost.js +109 -0
- package/dist/runtime/application/world-authoring/AuthoringIdentity.js +17 -0
- package/dist/runtime/application/world-authoring/AuthoringModelResolver.js +29 -0
- package/dist/runtime/application/world-authoring/AuthoringPatch.js +118 -0
- package/dist/runtime/application/world-authoring/AuthoringPromotionController.js +334 -0
- package/dist/runtime/application/world-authoring/AuthoringPromotionSource.js +126 -0
- package/dist/runtime/application/world-authoring/AuthoringRevisionHistory.js +144 -0
- package/dist/runtime/application/world-authoring/HeadlessImageExport.js +92 -0
- package/dist/runtime/application/world-authoring/ModelRef.js +62 -0
- package/dist/runtime/application/world-authoring/SceneGLBExport.js +88 -0
- package/dist/runtime/apps/mcp-server/AUTHORING.md +71 -0
- package/dist/runtime/apps/mcp-server/AgentMcpCompat.js +68 -0
- package/dist/runtime/apps/mcp-server/AuthoringSandboxEntry.js +1 -0
- package/dist/runtime/apps/mcp-server/AuthoringSandboxWorker.mjs +30 -0
- package/dist/runtime/apps/mcp-server/BuildEnvironment.js +17 -0
- package/dist/runtime/apps/mcp-server/CodeExecutor.js +71 -0
- package/dist/runtime/apps/mcp-server/DEPLOYMENT-PC2.md +42 -0
- package/dist/runtime/apps/mcp-server/DockerBuildRunner.js +66 -0
- package/dist/runtime/apps/mcp-server/FileAssetRepository.js +159 -0
- package/dist/runtime/apps/mcp-server/HeadlessAssetIO.js +8 -0
- package/dist/runtime/apps/mcp-server/HeadlessGLTFLoader.js +47 -0
- package/dist/runtime/apps/mcp-server/HeadlessWorldHost.js +157 -0
- package/dist/runtime/apps/mcp-server/IsolatedAuthoringExecutor.js +6 -0
- package/dist/runtime/apps/mcp-server/PROGRAMMATIC-ASSETS.md +116 -0
- package/dist/runtime/apps/mcp-server/ProgrammaticAssets.js +60 -0
- package/dist/runtime/apps/mcp-server/README.md +269 -0
- package/dist/runtime/apps/mcp-server/RemoteAuthoringDocument.js +1 -0
- package/dist/runtime/apps/mcp-server/SandboxBundle.js +13 -0
- package/dist/runtime/apps/mcp-server/SessionManager.js +148 -0
- package/dist/runtime/apps/mcp-server/StudioBridgeHttp.js +75 -0
- package/dist/runtime/apps/mcp-server/StudioLiveBridge.js +246 -0
- package/dist/runtime/apps/mcp-server/StudioProjectToolContracts.js +58 -0
- package/dist/runtime/apps/mcp-server/TransferHttp.js +47 -0
- package/dist/runtime/apps/mcp-server/TransferLimits.js +6 -0
- package/dist/runtime/apps/mcp-server/TransferStore.js +134 -0
- package/dist/runtime/apps/mcp-server/TrustedAuthoringWorker.mjs +16 -0
- package/dist/runtime/apps/mcp-server/VALIDATION.md +45 -0
- package/dist/runtime/apps/mcp-server/acceptance-evidence.json +332 -0
- package/dist/runtime/apps/mcp-server/errorDiagnostics.js +32 -0
- package/dist/runtime/apps/mcp-server/examples/code-house.js +24 -0
- package/dist/runtime/apps/mcp-server/examples/procedural-assets.js +85 -0
- package/dist/runtime/apps/mcp-server/main.mjs +82 -0
- package/dist/runtime/apps/mcp-server/registerTools.js +274 -0
- package/dist/runtime/apps/mcp-server/sandbox/run.mjs +23 -0
- package/dist/runtime/apps/mcp-server/security.js +23 -0
- package/dist/runtime/apps/mcp-server/tasks.jsonl +9 -0
- package/dist/runtime/apps/server/CapabilityAdapterRegistry.js +157 -0
- package/dist/runtime/apps/server/README.md +7 -0
- package/dist/runtime/apps/server/WorldRepository.js +338 -0
- package/dist/runtime/apps/server/WorldRepositoryHttp.js +96 -0
- package/dist/runtime/apps/server/openai-compatible-agent-gateway.mjs +278 -0
- package/dist/runtime/apps/server/tasks.jsonl +10 -0
- package/dist/runtime/apps/shared/node/WorldDiskStorage.js +62 -0
- package/dist/runtime/foundation/EventBus.js +26 -0
- package/dist/runtime/foundation/JsonGateway.js +47 -0
- package/dist/runtime/foundation/PngRgba.js +99 -0
- package/dist/runtime/foundation/PolicyEngine.js +21 -0
- package/dist/runtime/foundation/README.md +7 -0
- package/dist/runtime/foundation/TraceRecorder.js +76 -0
- package/dist/runtime/foundation/errors.js +8 -0
- package/dist/runtime/foundation/simulation/SimulationProfile.js +143 -0
- package/dist/runtime/foundation/version.js +2 -0
- package/dist/runtime/modules/agent/README.md +11 -0
- package/dist/runtime/modules/agent/ToolCallingAgent.js +19 -0
- package/dist/runtime/modules/agent/bootstrapWorld.js +10 -0
- package/dist/runtime/modules/agent/buildRecoveryProposals.js +533 -0
- package/dist/runtime/modules/agent/execution/AgentExecutionRules.js +128 -0
- package/dist/runtime/modules/agent/execution/AgentRunResults.js +55 -0
- package/dist/runtime/modules/agent/execution/AgentRunSession.js +393 -0
- package/dist/runtime/modules/agent/execution/AgentToolInvoker.js +40 -0
- package/dist/runtime/modules/agent/gateway/HttpLLMGateway.js +19 -0
- package/dist/runtime/modules/agent/prompt/index.js +52 -0
- package/dist/runtime/modules/agent/tasks.jsonl +94 -0
- package/dist/runtime/modules/artifact/ArtifactContentGate.js +144 -0
- package/dist/runtime/modules/artifact/ArtifactDescriptor.js +280 -0
- package/dist/runtime/modules/artifact/ArtifactImporter.js +185 -0
- package/dist/runtime/modules/artifact/ArtifactModule.js +111 -0
- package/dist/runtime/modules/artifact/ArtifactRegistry.js +197 -0
- package/dist/runtime/modules/artifact/IncrementalSha256.js +129 -0
- package/dist/runtime/modules/artifact/MemoryArtifactByteStore.js +115 -0
- package/dist/runtime/modules/artifact/README.md +7 -0
- package/dist/runtime/modules/artifact/storage/IndexedDbArtifactStore.js +67 -0
- package/dist/runtime/modules/artifact/tasks.jsonl +31 -0
- package/dist/runtime/modules/asset/AssetModule.js +416 -0
- package/dist/runtime/modules/asset/README.md +67 -0
- package/dist/runtime/modules/asset/loading/AssetLoader.js +157 -0
- package/dist/runtime/modules/asset/loading/GltfAssetLoader.js +61 -0
- package/dist/runtime/modules/asset/loading/builtins/BuiltinAssets.js +95 -0
- package/dist/runtime/modules/asset/loading/builtins/HouseDoor.js +33 -0
- package/dist/runtime/modules/asset/loading/builtins/IndustrialCabinet.js +103 -0
- package/dist/runtime/modules/asset/model/AssetInputContracts.js +139 -0
- package/dist/runtime/modules/asset/model/AssetRef.js +12 -0
- package/dist/runtime/modules/asset/model/MechanicalAssetDraft.js +172 -0
- package/dist/runtime/modules/asset/model/ProceduralTextureContract.js +24 -0
- package/dist/runtime/modules/asset/model/admission.js +117 -0
- package/dist/runtime/modules/asset/model/errors.js +6 -0
- package/dist/runtime/modules/asset/model/parts.js +27 -0
- package/dist/runtime/modules/asset/model/resourceBudget.js +10 -0
- package/dist/runtime/modules/asset/model/schema.js +150 -0
- package/dist/runtime/modules/asset/persistence/AssetManifestStore.js +78 -0
- package/dist/runtime/modules/asset/persistence/CompiledAssetStore.js +84 -0
- package/dist/runtime/modules/asset/persistence/LocalAssetLibrary.js +86 -0
- package/dist/runtime/modules/asset/persistence/LocalAssetLibraryStore.js +81 -0
- package/dist/runtime/modules/asset/production/AssetProductionPipeline.js +272 -0
- package/dist/runtime/modules/asset/production/AssetRecipe.js +91 -0
- package/dist/runtime/modules/asset/production/ProceduralTexture.js +85 -0
- package/dist/runtime/modules/asset/production/adapters/EmbodiedGenAdapter.js +45 -0
- package/dist/runtime/modules/asset/production/adapters/EmbodiedGenBundleAdapter.js +590 -0
- package/dist/runtime/modules/asset/production/compiler/AssetCompiler.js +173 -0
- package/dist/runtime/modules/asset/production/compiler/evidence/AnimationMotionEvidence.js +124 -0
- package/dist/runtime/modules/asset/production/compiler/evidence/StaticPanelEvidence.js +56 -0
- package/dist/runtime/modules/asset/production/compiler/gltfIO.js +6 -0
- package/dist/runtime/modules/asset/production/compiler/partGeometry.js +74 -0
- package/dist/runtime/modules/asset/production/compiler/passes/ArticulatedCollisionPass.js +63 -0
- package/dist/runtime/modules/asset/production/compiler/passes/ArticulationCandidatePass.js +48 -0
- package/dist/runtime/modules/asset/production/compiler/passes/AuthoringIntentPass.js +16 -0
- package/dist/runtime/modules/asset/production/compiler/passes/ColliderFallbackPass.js +30 -0
- package/dist/runtime/modules/asset/production/compiler/passes/CompileQualityPass.js +75 -0
- package/dist/runtime/modules/asset/production/compiler/passes/ExplicitDefinitionPass.js +20 -0
- package/dist/runtime/modules/asset/production/compiler/passes/GLTFInspectPass.js +34 -0
- package/dist/runtime/modules/asset/production/compiler/passes/GeometryPass.js +32 -0
- package/dist/runtime/modules/asset/production/compiler/passes/JointFramePass.js +116 -0
- package/dist/runtime/modules/asset/production/compiler/passes/KinematicEvidencePass.js +84 -0
- package/dist/runtime/modules/asset/production/compiler/passes/ManifestPass.js +63 -0
- package/dist/runtime/modules/asset/production/compiler/passes/NormalizeTransformPass.js +16 -0
- package/dist/runtime/modules/asset/production/compiler/passes/OptimizeGLBPass.js +23 -0
- package/dist/runtime/modules/asset/production/compiler/passes/PartColliderPass.js +50 -0
- package/dist/runtime/modules/asset/production/compiler/passes/PartGeometryEnrichmentPass.js +60 -0
- package/dist/runtime/modules/asset/production/compiler/passes/PartProposalPass.js +93 -0
- package/dist/runtime/modules/asset/production/compiler/passes/RemoteEnrichmentPass.js +32 -0
- package/dist/runtime/modules/asset/production/compiler/passes/ResourceBudgetPass.js +55 -0
- package/dist/runtime/modules/asset/production/compiler/passes/SegmentMaterializePass.js +203 -0
- package/dist/runtime/modules/asset/production/compiler/passes/SegmentationEvidencePass.js +43 -0
- package/dist/runtime/modules/asset/production/compiler/passes/SemanticHeuristicPass.js +33 -0
- package/dist/runtime/modules/asset/production/compiler/passes/StructurePass.js +60 -0
- package/dist/runtime/modules/asset/production/compiler/providers/HttpCompilerProvider.js +23 -0
- package/dist/runtime/modules/asset/production/verification/KinematicHypothesisScreen.js +198 -0
- package/dist/runtime/modules/asset/registry/AssetCatalog.js +72 -0
- package/dist/runtime/modules/asset/registry/AssetRegistry.js +51 -0
- package/dist/runtime/modules/asset/registry/manifests/index.js +173 -0
- package/dist/runtime/modules/asset/tasks.jsonl +87 -0
- package/dist/runtime/modules/generation/README.md +9 -0
- package/dist/runtime/modules/generation/connector/ConnectorArtifactClient.js +45 -0
- package/dist/runtime/modules/generation/connector/ConnectorCapabilityAdapter.js +169 -0
- package/dist/runtime/modules/generation/connector/ConnectorClient.js +192 -0
- package/dist/runtime/modules/generation/connector/ConnectorJobClient.js +167 -0
- package/dist/runtime/modules/generation/connector/ConnectorJobEventClient.js +179 -0
- package/dist/runtime/modules/generation/connector/ConnectorSession.js +202 -0
- package/dist/runtime/modules/generation/jobs/GenerationJobProjection.js +239 -0
- package/dist/runtime/modules/generation/jobs/GenerationJobReconciler.js +99 -0
- package/dist/runtime/modules/generation/jobs/GenerationJobStore.js +91 -0
- package/dist/runtime/modules/generation/jobs/GenerationJobTransportOverlay.js +50 -0
- package/dist/runtime/modules/generation/providers/ProviderRegistry.js +304 -0
- package/dist/runtime/modules/generation/tasks.jsonl +35 -0
- package/dist/runtime/modules/navigation/NavigationBackend.js +17 -0
- package/dist/runtime/modules/navigation/RecastNavigationBackend.js +263 -0
- package/dist/runtime/modules/physics/JoltPhysicsBackend.js +850 -0
- package/dist/runtime/modules/physics/PhysicsApiSurface.js +660 -0
- package/dist/runtime/modules/physics/PhysicsBackend.js +88 -0
- package/dist/runtime/modules/physics/RapierPhysicsBackend.js +414 -0
- package/dist/runtime/modules/rendering/README.md +7 -0
- package/dist/runtime/modules/rendering/RendererProbe.js +153 -0
- package/dist/runtime/modules/rendering/WebGpuPostFxPipeline.js +140 -0
- package/dist/runtime/modules/rendering/captureStill.js +54 -0
- package/dist/runtime/modules/rendering/createRenderer.js +76 -0
- package/dist/runtime/modules/rendering/disposeObject3D.js +37 -0
- package/dist/runtime/modules/rendering/loadGaussianSplatVisual.js +74 -0
- package/dist/runtime/modules/rendering/spatial/ThreeBvhRuntime.js +107 -0
- package/dist/runtime/modules/rendering/style/StylePack.js +34 -0
- package/dist/runtime/modules/rendering/style/StyleSystem.js +173 -0
- package/dist/runtime/modules/rendering/tasks.jsonl +7 -0
- package/dist/runtime/modules/world/README.md +13 -0
- package/dist/runtime/modules/world/build/WorldBuilder.js +170 -0
- package/dist/runtime/modules/world/compiler/PipelineEngine.js +32 -0
- package/dist/runtime/modules/world/compiler/WorldAdmission.js +43 -0
- package/dist/runtime/modules/world/compiler/WorldBehaviorCompiler.js +68 -0
- package/dist/runtime/modules/world/compiler/WorldCompilation.js +157 -0
- package/dist/runtime/modules/world/compiler/WorldComposer.js +201 -0
- package/dist/runtime/modules/world/compiler/WorldPhysicsAdmission.js +76 -0
- package/dist/runtime/modules/world/compiler/WorldRecompiler.js +356 -0
- package/dist/runtime/modules/world/compiler/WorldRetry.js +75 -0
- package/dist/runtime/modules/world/compiler/createWorldPipeline.js +379 -0
- package/dist/runtime/modules/world/content/blankWorld.js +35 -0
- package/dist/runtime/modules/world/content/environments.js +84 -0
- package/dist/runtime/modules/world/content/grandUrbanBlock.js +189 -0
- package/dist/runtime/modules/world/content/magic-cabin/README.md +28 -0
- package/dist/runtime/modules/world/content/magic-cabin/affordances.js +64 -0
- package/dist/runtime/modules/world/content/magic-cabin/cabinContents.js +7078 -0
- package/dist/runtime/modules/world/content/magic-cabin/lighting.js +26 -0
- package/dist/runtime/modules/world/content/magic-cabin/materials.js +20 -0
- package/dist/runtime/modules/world/content/magicCabin.js +190 -0
- package/dist/runtime/modules/world/content/monumentHall.js +154 -0
- package/dist/runtime/modules/world/content/ruinedCourtyard.js +196 -0
- package/dist/runtime/modules/world/content/suzhouGarden/README.md +141 -0
- package/dist/runtime/modules/world/content/suzhouGarden/index.js +137 -0
- package/dist/runtime/modules/world/content/suzhouGarden/src/arch.js +491 -0
- package/dist/runtime/modules/world/content/suzhouGarden/src/buildings.js +670 -0
- package/dist/runtime/modules/world/content/suzhouGarden/src/core.js +578 -0
- package/dist/runtime/modules/world/content/suzhouGarden/src/lod.js +127 -0
- package/dist/runtime/modules/world/content/suzhouGarden/src/main.js +642 -0
- package/dist/runtime/modules/world/content/suzhouGarden/src/nature.js +650 -0
- package/dist/runtime/modules/world/content/suzhouGarden/src/rockery.js +280 -0
- package/dist/runtime/modules/world/content/suzhouGarden/src/sky.js +242 -0
- package/dist/runtime/modules/world/content/suzhouGarden/src/water.js +215 -0
- package/dist/runtime/modules/world/content/woodlandWorkshop.js +192 -0
- package/dist/runtime/modules/world/content/yuanmingyuan/README.md +36 -0
- package/dist/runtime/modules/world/content/yuanmingyuan/arch.js +351 -0
- package/dist/runtime/modules/world/content/yuanmingyuan/buildings.js +490 -0
- package/dist/runtime/modules/world/content/yuanmingyuan/core.js +505 -0
- package/dist/runtime/modules/world/content/yuanmingyuan/index.js +101 -0
- package/dist/runtime/modules/world/content/yuanmingyuan/nature.js +435 -0
- package/dist/runtime/modules/world/content/yuanmingyuan/sky.js +169 -0
- package/dist/runtime/modules/world/content/yuanmingyuan/water.js +245 -0
- package/dist/runtime/modules/world/errors.js +9 -0
- package/dist/runtime/modules/world/generated/GeneratedWorldCoordinates.js +50 -0
- package/dist/runtime/modules/world/generated/GeneratedWorldLoader.js +297 -0
- package/dist/runtime/modules/world/runtime/CommandHistory.js +111 -0
- package/dist/runtime/modules/world/runtime/EntityCapabilityRegistry.js +165 -0
- package/dist/runtime/modules/world/runtime/NativeNavigationGeometry.js +84 -0
- package/dist/runtime/modules/world/runtime/NativePhysicsSnapshot.js +245 -0
- package/dist/runtime/modules/world/runtime/ObjectStore.js +31 -0
- package/dist/runtime/modules/world/runtime/ObjectTransform.js +62 -0
- package/dist/runtime/modules/world/runtime/ObservedEntity.js +37 -0
- package/dist/runtime/modules/world/runtime/ProjectCapabilities.js +240 -0
- package/dist/runtime/modules/world/runtime/SceneExtensions.js +36 -0
- package/dist/runtime/modules/world/runtime/ScenePresentation.js +101 -0
- package/dist/runtime/modules/world/runtime/SceneSerializer.js +281 -0
- package/dist/runtime/modules/world/runtime/WorldAuthority.js +41 -0
- package/dist/runtime/modules/world/runtime/WorldCollisionSignature.js +14 -0
- package/dist/runtime/modules/world/runtime/WorldCommands.js +503 -0
- package/dist/runtime/modules/world/runtime/WorldObservation.js +71 -0
- package/dist/runtime/modules/world/runtime/WorldQueries.js +340 -0
- package/dist/runtime/modules/world/runtime/WorldRecovery.js +78 -0
- package/dist/runtime/modules/world/runtime/WorldRuntime.js +806 -0
- package/dist/runtime/modules/world/runtime/affordance/ObjectAffordances.js +110 -0
- package/dist/runtime/modules/world/runtime/affordance/WorldAffordances.js +130 -0
- package/dist/runtime/modules/world/runtime/behavior/BehaviorCompiler.js +79 -0
- package/dist/runtime/modules/world/runtime/behavior/ProjectStateMachine.js +195 -0
- package/dist/runtime/modules/world/runtime/behavior/RuleGraph.js +70 -0
- package/dist/runtime/modules/world/runtime/behavior/RuleRuntime.js +115 -0
- package/dist/runtime/modules/world/runtime/graph/SceneGraph.js +390 -0
- package/dist/runtime/modules/world/runtime/interaction/ArticulationRuntime.js +214 -0
- package/dist/runtime/modules/world/runtime/interaction/CarryCapability.js +65 -0
- package/dist/runtime/modules/world/runtime/interaction/CarryRuntime.js +244 -0
- package/dist/runtime/modules/world/runtime/interaction/InteractionApproach.js +147 -0
- package/dist/runtime/modules/world/runtime/interaction/InteractionContract.js +57 -0
- package/dist/runtime/modules/world/runtime/interaction/ManipulationActions.js +7 -0
- package/dist/runtime/modules/world/runtime/interaction/NativePhysicalTarget.js +31 -0
- package/dist/runtime/modules/world/runtime/interaction/RecoveryRuntime.js +123 -0
- package/dist/runtime/modules/world/runtime/interaction/SettleRuntime.js +134 -0
- package/dist/runtime/modules/world/runtime/semantic/NativePhysicsState.js +89 -0
- package/dist/runtime/modules/world/runtime/semantic/SemanticWorldView.js +129 -0
- package/dist/runtime/modules/world/runtime/simulation/SimulationClock.js +89 -0
- package/dist/runtime/modules/world/runtime/simulation/SimulationSession.js +104 -0
- package/dist/runtime/modules/world/runtime/simulation/ThermalSystem.js +269 -0
- package/dist/runtime/modules/world/runtime/simulation/WorldTimeline.js +110 -0
- package/dist/runtime/modules/world/runtime/spatial/SpatialSnapshot.js +56 -0
- package/dist/runtime/modules/world/runtime/spatial/VisualMeshBounds.js +41 -0
- package/dist/runtime/modules/world/runtime/systems/AudioSystem.js +306 -0
- package/dist/runtime/modules/world/runtime/systems/Instrument.js +39 -0
- package/dist/runtime/modules/world/runtime/systems/InteractionSystem.js +806 -0
- package/dist/runtime/modules/world/runtime/systems/LocomotionSystem.js +281 -0
- package/dist/runtime/modules/world/runtime/systems/NavigationSystem.js +561 -0
- package/dist/runtime/modules/world/runtime/systems/PhysicsSystem.js +1752 -0
- package/dist/runtime/modules/world/runtime/systems/RenderingSystem.js +527 -0
- package/dist/runtime/modules/world/runtime/systems/SpatialSystem.js +402 -0
- package/dist/runtime/modules/world/spec/WorldIR.js +165 -0
- package/dist/runtime/modules/world/spec/WorldIRToolSchema.js +86 -0
- package/dist/runtime/modules/world/spec/WorldPlannerProposal.js +51 -0
- package/dist/runtime/modules/world/spec/WorldRevision.js +231 -0
- package/dist/runtime/modules/world/spec/WorldSpec.js +86 -0
- package/dist/runtime/modules/world/tasks.jsonl +530 -0
- package/dist/runtime/modules/world/verification/ArticulationVerifier.js +254 -0
- package/dist/runtime/modules/world/verification/Finding.js +105 -0
- package/dist/runtime/modules/world/verification/InteractionEvidence.js +73 -0
- package/dist/runtime/modules/world/verification/RepairEngine.js +49 -0
- package/dist/runtime/modules/world/verification/VisualLayoutAcceptance.js +58 -0
- package/dist/runtime/modules/world/verification/WorldAcceptance.js +176 -0
- package/dist/runtime/modules/world/verification/WorldValidator.js +67 -0
- package/dist/runtime/package-lock.json +16071 -0
- package/dist/runtime/package.json +106 -0
- package/dist/runtime/public/assets/cabinet.glb +0 -0
- package/dist/runtime/public/assets/grand-urban-block/clean_asphalt_diff_1k.jpg +0 -0
- package/dist/runtime/public/assets/grand-urban-block/clean_asphalt_nor_gl_1k.jpg +0 -0
- package/dist/runtime/public/assets/grand-urban-block/concrete_pavement_diff_1k.jpg +0 -0
- package/dist/runtime/public/assets/grand-urban-block/urban_street_01_1k.hdr +0 -0
- package/dist/runtime/public/assets/monument-hall/marble_diff_1k.jpg +0 -0
- package/dist/runtime/public/assets/monument-hall/marble_nor_gl_1k.jpg +0 -0
- package/dist/runtime/public/assets/monument-hall/marble_rough_1k.jpg +0 -0
- package/dist/runtime/public/assets/monument-hall/solitude_interior_1k.hdr +0 -0
- package/dist/runtime/public/assets/ruined-courtyard/courtyard_1k.hdr +0 -0
- package/dist/runtime/public/assets/ruined-courtyard/mossy_cobblestone_diff_1k.jpg +0 -0
- package/dist/runtime/public/assets/ruined-courtyard/mossy_cobblestone_nor_gl_1k.jpg +0 -0
- package/dist/runtime/public/assets/ruined-courtyard/mossy_sandstone_diff_1k.jpg +0 -0
- package/dist/schema-DT7K9NjP.js +165 -0
- package/dist/schema-DT7K9NjP.js.map +1 -0
- package/dist/suzhouGarden-Y3hny8j6.js +6150 -0
- package/dist/suzhouGarden-Y3hny8j6.js.map +1 -0
- package/dist/version-CHc-i8ch.js +5 -0
- package/dist/version-CHc-i8ch.js.map +1 -0
- package/dist/woodlandWorkshop-DsScU-cx.js +483 -0
- package/dist/woodlandWorkshop-DsScU-cx.js.map +1 -0
- package/dist/yuanmingyuan-DsFnPzzR.js +4955 -0
- package/dist/yuanmingyuan-DsFnPzzR.js.map +1 -0
- package/package.json +75 -4
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { compileInteractionContract } from '../interaction/InteractionContract.js';
|
|
2
|
+
import { assetAdmission } from '../../../asset/model/admission.js';
|
|
3
|
+
import { inferCarryCapability } from '../interaction/CarryCapability.js';
|
|
4
|
+
import { nativeCarryRecord } from '../interaction/NativePhysicalTarget.js';
|
|
5
|
+
import { rigidBodyActions,manipulationParameters } from '../interaction/ManipulationActions.js';
|
|
6
|
+
|
|
7
|
+
const blocked = reason => ({ available: false, reason });
|
|
8
|
+
const reasonOf = error => error.details?.reason || error.code || 'CAPABILITY_CHECK_FAILED';
|
|
9
|
+
|
|
10
|
+
/** Read-through discovery. ObjectStore and PhysicsSystem remain the state owners. */
|
|
11
|
+
export function inspectObjectAffordances(runtime, id, actorId = null) {
|
|
12
|
+
if (!runtime.store?.has(id)) return null;
|
|
13
|
+
const record = runtime.store.get(id), manifest = record.manifest;
|
|
14
|
+
const registered = Boolean(runtime.physics?.getPosition(id));
|
|
15
|
+
const held = record.state?.heldBy || runtime.interactions?.isHeld?.(id) || runtime.interactions?.carry?.agentHeld?.has(id);
|
|
16
|
+
let access = { available: null, reason: 'ACTOR_REQUIRED_FOR_REACH_CHECK' };
|
|
17
|
+
if (actorId) {
|
|
18
|
+
if (!runtime.store.has(actorId)) access = blocked('ACTOR_NOT_FOUND');
|
|
19
|
+
else if (runtime.store.get(actorId).manifest.type !== 'agent') access = blocked('ACTOR_NOT_AGENT');
|
|
20
|
+
else if (!registered) access = blocked('TARGET_PHYSICS_UNAVAILABLE');
|
|
21
|
+
else if (!runtime.physics.hasCapability('scene-query')) access = blocked('VISIBILITY_UNAVAILABLE');
|
|
22
|
+
else {
|
|
23
|
+
try {
|
|
24
|
+
const reach = runtime.interactions.interactionStatus(actorId, id);
|
|
25
|
+
access = { available: reach.interactable, reason: reach.interactable ? null : reach.inRange ? 'OCCLUDED' : 'OUT_OF_REACH', distance: reach.distance };
|
|
26
|
+
} catch (error) { access = blocked(reasonOf(error)); }
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const actions = [];
|
|
30
|
+
const add = (action, parameters = {}, extra = {}) => {
|
|
31
|
+
const entry={action,parameters,...access,...extra};
|
|
32
|
+
if(entry.execution==='interaction')entry.canApproach=entry.available===false && ['OUT_OF_REACH','OCCLUDED'].includes(entry.reason) && Boolean(runtime.navigation?.findPath && runtime.locomotion?.navigate);
|
|
33
|
+
actions.push(entry);
|
|
34
|
+
};
|
|
35
|
+
// Editor operations are explicitly separate from embodied actions.
|
|
36
|
+
add('inspect', {}, { available: true, reason: null, execution: 'query' });
|
|
37
|
+
add('setTransform', { transform: { type: 'object', required: true } }, {
|
|
38
|
+
available: !held, reason: held ? 'OBJECT_HELD' : null, execution: 'editor'
|
|
39
|
+
});
|
|
40
|
+
const carry = inferCarryCapability(manifest, { scale:record.physicsScale ?? record.object?.scale?.x ?? 1,
|
|
41
|
+
allowProvisional:record.state?.authoringPromotion?.usage === 'movable' });
|
|
42
|
+
if (manifest.actions?.includes('pickup') || carry.eligible) {
|
|
43
|
+
let check = carry.eligible ? {} : blocked(carry.reason);
|
|
44
|
+
if (actorId && runtime.store.has(actorId)) {
|
|
45
|
+
try { runtime.interactions.assertAgentCarryable(actorId, id); }
|
|
46
|
+
catch (error) { check = blocked(reasonOf(error)); }
|
|
47
|
+
}
|
|
48
|
+
add('pickup', {}, { execution: 'interaction',
|
|
49
|
+
capabilitySource:manifest.actions?.includes('pickup') ? 'declared' : 'physical-inference',
|
|
50
|
+
graspVerified:false, ...check });
|
|
51
|
+
if(actorId&&runtime.interactions?.heldByAgent?.(actorId)===id)add('drop',{}, {execution:'interaction',available:true,reason:null,graspVerified:false});
|
|
52
|
+
}
|
|
53
|
+
if (manifest.surfaces?.length) {
|
|
54
|
+
const held = actorId && runtime.interactions?.heldByAgent?.(actorId);
|
|
55
|
+
const heldRecord=held?(runtime.store.has(held)?runtime.store.get(held):nativeCarryRecord(runtime.entities,runtime.physics,held)):null;
|
|
56
|
+
add('place', { surfaceId: { type: 'string', enum: manifest.surfaces.map(surface => surface.id), required: false } }, {
|
|
57
|
+
execution: 'interaction', ...(!actorId ? {} : !held ? blocked('NOT_HOLDING_OBJECT') : !heldRecord||!runtime.interactions.supports(heldRecord, 'place') ? blocked('ACTION_UNSUPPORTED') : {})
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
for (const contract of compileInteractionContract(manifest).contracts) {
|
|
61
|
+
const partName = contract.target.partName;
|
|
62
|
+
const live = runtime.physics?.getArticulationState?.(id, partName);
|
|
63
|
+
add(contract.action, { partName: { type: 'string', enum: [partName], required: true } }, {
|
|
64
|
+
execution: 'interaction', partName, contract,
|
|
65
|
+
joint: structuredClone(manifest.parts[partName].joint), state: live,
|
|
66
|
+
...(!live ? blocked('ARTICULATION_PHYSICS_UNAVAILABLE') : {}),
|
|
67
|
+
...(manifest.source?.kind==='compiled' && assetAdmission(manifest).layers.runtime.status!=='ready' ? blocked('RUNTIME_VERIFICATION_REQUIRED') : {}),
|
|
68
|
+
...(runtime.interactions.articulationTasks?.has(`${id}:${partName}`) ? blocked('ACTION_IN_PROGRESS') : {})
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
for (const [partName, part] of Object.entries(manifest.parts || {})) {
|
|
72
|
+
if (!['revolute', 'prismatic'].includes(part.joint?.type)) continue;
|
|
73
|
+
const action = part.joint.type === 'prismatic' ? 'slide' : 'rotateJoint';
|
|
74
|
+
const capability = runtime.interactions?.manipulationCapability?.(id, action, partName) || blocked('EXECUTOR_UNAVAILABLE');
|
|
75
|
+
let partAccess={};
|
|
76
|
+
if(actorId && runtime.store.has(actorId) && runtime.store.get(actorId).manifest.type==='agent') {
|
|
77
|
+
try {
|
|
78
|
+
const aimPoint=runtime.physics.manipulationBody(id,partName,{contacts:true}).contactCandidates[0]?.center;
|
|
79
|
+
if(aimPoint) {const reach=runtime.interactions.interactionStatus(actorId,id,{aimPoint});partAccess={available:reach.interactable,reason:reach.interactable?null:reach.inRange?'OCCLUDED':'OUT_OF_REACH',distance:reach.distance};}
|
|
80
|
+
} catch { /* Keep the root access diagnostic if a part cannot be queried. */ }
|
|
81
|
+
}
|
|
82
|
+
const relative = action === 'slide' ? 'distance' : 'angle';
|
|
83
|
+
add(action, { part: { type: 'string', enum: [partName], required: true },
|
|
84
|
+
target: { type: 'number', required: false, alternative:relative, unit: action === 'slide' ? 'meter' : 'radian', limits: structuredClone(part.joint.limits || null) },
|
|
85
|
+
[relative]: {type:'number', required:false, alternative:'target', relative:true, unit:action === 'slide' ? 'meter' : 'radian'} }, {
|
|
86
|
+
execution: 'interaction', partName, joint: structuredClone(part.joint), state:runtime.physics?.getArticulationState?.(id,partName),
|
|
87
|
+
...partAccess,...(!capability.available ? capability : {}), ...(actorId && runtime.interactions?.heldByAgent?.(actorId) ? blocked('HANDS_FULL') : {})
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
if (manifest.physics?.colliders?.length) {
|
|
91
|
+
for (const action of rigidBodyActions) {
|
|
92
|
+
const capability = runtime.interactions?.manipulationCapability?.(id, action) || blocked('EXECUTOR_UNAVAILABLE');
|
|
93
|
+
const parameters=manipulationParameters(action);
|
|
94
|
+
add(action, parameters, { execution:'interaction', ...(!capability.available ? capability : {}),
|
|
95
|
+
...(actorId && runtime.interactions?.heldByAgent?.(actorId) ? blocked('HANDS_FULL') : {}) });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return {
|
|
99
|
+
schema: 'agentscape.object-affordances', schemaVersion: 1, id,
|
|
100
|
+
label: manifest.label || manifest.id, kind: manifest.type, source: 'asset',
|
|
101
|
+
position: record.object.position.toArray(), state: structuredClone(record.state || {}),
|
|
102
|
+
physics: { registered, body: manifest.physics?.body || null, currentBody:runtime.physics?.manipulationBody?.(id)?.body ?? null,
|
|
103
|
+
mass: manifest.physics?.mass ?? null, friction: manifest.physics?.friction ?? null,
|
|
104
|
+
colliderCount: manifest.physics?.colliders?.length || 0 },
|
|
105
|
+
actions,
|
|
106
|
+
...(manifest.physics?.body === 'dynamic' && !carry.eligible ? { capabilityCandidates:[{ action:'pickup', executable:false, reason:carry.reason, source:'physical-geometry' }] } : {}),
|
|
107
|
+
evidenceKind: registered ? 'physics-state' : 'visual-state', physicsVerified: false,
|
|
108
|
+
pending: Boolean(runtime.interactions?.physicalTasks?.has(id) || (runtime.interactions?.articulationTasks && [...runtime.interactions.articulationTasks.values()].some(task => task.id === id)))
|
|
109
|
+
};
|
|
110
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import * as THREE from 'three';
|
|
2
|
+
import { inspectObjectAffordances } from './ObjectAffordances.js';
|
|
3
|
+
|
|
4
|
+
const clone=value=>structuredClone(value);
|
|
5
|
+
const failure=(id,reason,extra={})=>({status:'world-action-blocked',targetId:id,verified:false,reason,...extra});
|
|
6
|
+
|
|
7
|
+
export class WorldAffordances {
|
|
8
|
+
constructor(runtime) {this.runtime=runtime;this.pending=new Map();this.sequence=0;this.lastResult=null;this.epoch=0;}
|
|
9
|
+
contracts() {return this.runtime.environment?.affordances || [];}
|
|
10
|
+
get(id) {return this.contracts().find(entry=>entry.id===id);}
|
|
11
|
+
position(entry) {
|
|
12
|
+
if(entry.position) return [...entry.position];
|
|
13
|
+
const box=new THREE.Box3().setFromObject(entry.object);
|
|
14
|
+
return box.getCenter(new THREE.Vector3()).toArray();
|
|
15
|
+
}
|
|
16
|
+
access(entry,actorId,position=null) {
|
|
17
|
+
const runtime=this.runtime;
|
|
18
|
+
if(!runtime.store?.has(actorId)) return {available:false,reason:'ACTOR_NOT_FOUND'};
|
|
19
|
+
const actor=runtime.store.get(actorId);
|
|
20
|
+
if(actor.manifest?.type!=='agent') return {available:false,reason:'ACTOR_NOT_AGENT'};
|
|
21
|
+
const feet=position || runtime.physics?.getPosition(actorId);
|
|
22
|
+
if(!feet) return {available:false,reason:'ACTOR_PHYSICS_UNAVAILABLE'};
|
|
23
|
+
const target=this.position(entry);
|
|
24
|
+
const origin=[feet[0],feet[1]+1.2,feet[2]];
|
|
25
|
+
const distance=Math.hypot(...target.map((v,i)=>v-origin[i]));
|
|
26
|
+
if(distance>1.5) return {available:false,reason:'OUT_OF_REACH',distance,targetPosition:target,maxDistance:1.5};
|
|
27
|
+
if(!runtime.physics.hasCapability?.('scene-query')) return {available:false,reason:'VISIBILITY_UNAVAILABLE'};
|
|
28
|
+
const hit=runtime.physics.raycast(origin,target,{excludeId:actorId});
|
|
29
|
+
if(hit && hit.distance < distance-.12 && !(entry.colliderId && hit.provenance?.environmentId===entry.colliderId)) return {available:false,reason:'OCCLUDED',blocker:hit.provenance || {id:hit.id},distance};
|
|
30
|
+
return {available:true,distance};
|
|
31
|
+
}
|
|
32
|
+
inspect(id,{actorId=null}={}) {
|
|
33
|
+
const entry=this.get(id);
|
|
34
|
+
if(!entry) return inspectObjectAffordances(this.runtime,id,actorId);
|
|
35
|
+
const access=actorId?this.access(entry,actorId):{available:null,reason:'ACTOR_REQUIRED_FOR_REACH_CHECK'};
|
|
36
|
+
const state=entry.kind==='text' && actorId && !access.available ? {text:null,reason:access.reason} : clone(entry.read());
|
|
37
|
+
return {schema:'agentscape.object-affordances',schemaVersion:1,source:'environment',id:entry.id,label:entry.label,kind:entry.kind,position:this.position(entry),state,
|
|
38
|
+
actions:entry.actions.map(action=>{const reason=entry.precondition?.(action);return {action,parameters:clone(entry.parameters?.[action] || {}),execution:'world-action',...access,
|
|
39
|
+
canApproach:!reason && ['OUT_OF_REACH','OCCLUDED'].includes(access.reason) && Boolean(this.runtime.navigation?.findPath && this.runtime.locomotion?.navigate),
|
|
40
|
+
...(reason?{available:false,reason}:{}),...(this.pending.has(id)?{available:false,reason:'ACTION_IN_PROGRESS',canApproach:false}:{}),...(this.runtime.simulation?.running===false && entry.evidenceKind==='animated-transform'?{available:false,reason:'SIMULATION_PAUSED',canApproach:false}:{})};}),evidenceKind:entry.evidenceKind,
|
|
41
|
+
physicsVerified:false,pending:this.pending.has(id)};
|
|
42
|
+
}
|
|
43
|
+
list({query='',actorId=null,limit=40}={}) {
|
|
44
|
+
const term=String(query).toLocaleLowerCase();
|
|
45
|
+
const entries=[...this.contracts()];
|
|
46
|
+
const ids=new Set(entries.map(entry=>entry.id));
|
|
47
|
+
for(const [id,record] of this.runtime.store?.list?.() || []) if(!ids.has(id)) entries.push({id,label:record.manifest.label || record.manifest.id,kind:record.manifest.type});
|
|
48
|
+
const matches=entries.filter(entry=>`${entry.id} ${entry.label} ${entry.kind}`.toLocaleLowerCase().includes(term));
|
|
49
|
+
return {schema:'agentscape.affordances.v1',total:matches.length,entities:matches.slice(0,Math.min(100,Math.max(1,limit))).map(entry=>this.inspect(entry.id,{actorId}))};
|
|
50
|
+
}
|
|
51
|
+
execute({targetId,action,args={},actorId=null},{editor=false}={}) {
|
|
52
|
+
const entry=this.get(targetId);
|
|
53
|
+
if(!entry) return failure(targetId,'TARGET_NOT_FOUND');
|
|
54
|
+
if(!entry.actions.includes(action)) return failure(targetId,'ACTION_UNSUPPORTED');
|
|
55
|
+
if(!editor) {const access=this.access(entry,actorId);if(!access.available)return failure(targetId,access.reason,{access});}
|
|
56
|
+
const precondition=entry.precondition?.(action);
|
|
57
|
+
if(precondition)return failure(targetId,precondition);
|
|
58
|
+
const invalid=entry.validate?.(action,args);
|
|
59
|
+
if(invalid) return failure(targetId,invalid);
|
|
60
|
+
if(action==='read') return {status:'world-state-read',targetId,state:clone(entry.read()),evidenceKind:entry.evidenceKind};
|
|
61
|
+
if(this.pending.has(targetId)) return failure(targetId,'ACTION_IN_PROGRESS');
|
|
62
|
+
const before=clone(entry.read());
|
|
63
|
+
const commandId=`world-action-${++this.sequence}`;
|
|
64
|
+
const complete=()=>{
|
|
65
|
+
const result={status:'world-action-completed',commandId,targetId,action,verified:true,physicsVerified:false,evidenceKind:entry.evidenceKind,before,after:clone(entry.read())};
|
|
66
|
+
this.lastResult=result;
|
|
67
|
+
this.runtime.events?.emit('world.action.completed',result);
|
|
68
|
+
return result;
|
|
69
|
+
};
|
|
70
|
+
if(this.runtime.simulation?.running===false && entry.evidenceKind==='animated-transform') return failure(targetId,'SIMULATION_PAUSED');
|
|
71
|
+
entry.request(action,args);
|
|
72
|
+
if(entry.verify(action,args)) return complete();
|
|
73
|
+
return new Promise(resolve=>{
|
|
74
|
+
const pending={entry,action,args,elapsed:0,resolve,complete,commandId};
|
|
75
|
+
pending.timer=setTimeout(()=>this.finishUnverified(targetId,'SIMULATION_NOT_ADVANCING'),12000);
|
|
76
|
+
pending.timer.unref?.();
|
|
77
|
+
this.pending.set(targetId,pending);
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
async approachAndExecute(command) {
|
|
81
|
+
const {targetId,actorId,action,args={}}=command,entry=this.get(targetId),epoch=this.epoch;
|
|
82
|
+
if(!entry)return failure(targetId,'TARGET_NOT_FOUND');
|
|
83
|
+
if(!entry.actions.includes(action))return failure(targetId,'ACTION_UNSUPPORTED');
|
|
84
|
+
if(this.runtime.simulation?.running===false && entry.evidenceKind==='animated-transform')return failure(targetId,'SIMULATION_PAUSED');
|
|
85
|
+
const invalid=entry.precondition?.(action) || entry.validate?.(action,args);
|
|
86
|
+
if(invalid)return failure(targetId,invalid);
|
|
87
|
+
const finish=result=>{
|
|
88
|
+
const changed=['world-action-completed','world-action-unverified'].includes(result.status);
|
|
89
|
+
if(changed)this.runtime.navigation?.invalidate?.('environment-contract-changed');
|
|
90
|
+
return {...result,navigationInvalidated:changed};
|
|
91
|
+
};
|
|
92
|
+
const current=this.access(entry,actorId);
|
|
93
|
+
if(current.available)return finish(await this.execute(command));
|
|
94
|
+
if(!['OUT_OF_REACH','OCCLUDED'].includes(current.reason))return failure(targetId,current.reason);
|
|
95
|
+
const runtime=this.runtime,start=runtime.physics.getPosition(actorId),target=this.position(entry);
|
|
96
|
+
if(!runtime.navigation?.findPath || !runtime.locomotion?.navigate)return failure(targetId,'NAVIGATION_UNAVAILABLE');
|
|
97
|
+
const poses=[];
|
|
98
|
+
for(const height of [...new Set([start[1],target[1]-1.2])]) for(const radius of [.7,1.05,1.3]) for(let i=0;i<8;i++) {
|
|
99
|
+
if(epoch!==this.epoch)return failure(targetId,'ACTION_CANCELLED');
|
|
100
|
+
const angle=i*Math.PI/4,candidate=[target[0]+Math.cos(angle)*radius,height,target[2]+Math.sin(angle)*radius];
|
|
101
|
+
const route=await runtime.navigation.findPath(start,candidate);
|
|
102
|
+
if(!route.reachable || !Array.isArray(route.end?.snapped))continue;
|
|
103
|
+
const position=route.end.snapped;
|
|
104
|
+
if(this.access(entry,actorId,position).available)poses.push({position,cost:route.cost ?? Infinity});
|
|
105
|
+
}
|
|
106
|
+
if(epoch!==this.epoch)return failure(targetId,'ACTION_CANCELLED');
|
|
107
|
+
if(this.get(targetId)!==entry)return failure(targetId,'TARGET_CHANGED');
|
|
108
|
+
poses.sort((a,b)=>a.cost-b.cost);
|
|
109
|
+
if(!poses.length)return failure(targetId,'NO_APPROACH_POSE',{access:current});
|
|
110
|
+
const locomotion=await runtime.locomotion.navigate(actorId,poses[0].position);
|
|
111
|
+
if(epoch!==this.epoch)return failure(targetId,'ACTION_CANCELLED');
|
|
112
|
+
if(this.get(targetId)!==entry)return failure(targetId,'TARGET_CHANGED');
|
|
113
|
+
if(locomotion.status!=='arrived')return failure(targetId,'APPROACH_FAILED',{locomotion});
|
|
114
|
+
return {...finish(await this.execute(command)),approach:poses[0].position,locomotion};
|
|
115
|
+
}
|
|
116
|
+
finishUnverified(id,reason) {
|
|
117
|
+
const item=this.pending.get(id);if(!item)return;
|
|
118
|
+
clearTimeout(item.timer);this.pending.delete(id);
|
|
119
|
+
const result={status:'world-action-unverified',commandId:item.commandId,targetId:id,verified:false,reason,after:clone(item.entry.read())};
|
|
120
|
+
this.lastResult=result;item.resolve(result);
|
|
121
|
+
}
|
|
122
|
+
update(dt) {
|
|
123
|
+
for(const [id,item] of this.pending) {
|
|
124
|
+
item.elapsed+=dt;
|
|
125
|
+
if(item.entry.verify(item.action,item.args)) {clearTimeout(item.timer);this.pending.delete(id);item.resolve(item.complete());}
|
|
126
|
+
else if(item.elapsed>=8)this.finishUnverified(id,'POSTCONDITION_TIMEOUT');
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
cancel(reason='WORLD_REPLACED') {this.epoch++;for(const id of [...this.pending.keys()])this.finishUnverified(id,reason);}
|
|
130
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
export const BEHAVIOR_COMMAND_SCHEMA='agentscape.runtime-command';
|
|
2
|
+
export const BEHAVIOR_COMMAND_VERSION=1;
|
|
3
|
+
|
|
4
|
+
const clean=v=>typeof v==='string'?v.trim():'';
|
|
5
|
+
const SUPPORTED_CAPABILITIES=new Set(['OPEN','CLOSE','PICKUP','PLACE','SWITCH']);
|
|
6
|
+
|
|
7
|
+
export function compileInteractionIntent(intent,{worldRevisionId=null}={}){
|
|
8
|
+
if(!intent||typeof intent!=='object'||Array.isArray(intent)) throw new TypeError('Interaction intent must be an object');
|
|
9
|
+
const id=clean(intent.id); const targetId=clean(intent.targetId); const supportId=clean(intent.supportId); const capability=clean(intent.capability).toUpperCase();
|
|
10
|
+
if(!id||!capability) throw new TypeError('Interaction intent requires id and capability');
|
|
11
|
+
if((capability==='OPEN'||capability==='CLOSE'||capability==='PICKUP') && !targetId) throw new TypeError(`${capability} interaction intent requires targetId`);
|
|
12
|
+
if(!SUPPORTED_CAPABILITIES.has(capability)) { const error=new TypeError(`Unsupported interaction capability: ${capability}`); error.code='BEHAVIOR_CAPABILITY_UNSUPPORTED'; throw error; }
|
|
13
|
+
const actorId=clean(intent.actorId)||null;
|
|
14
|
+
const command={
|
|
15
|
+
schema:BEHAVIOR_COMMAND_SCHEMA,schemaVersion:BEHAVIOR_COMMAND_VERSION,
|
|
16
|
+
commandId:`interaction:${id}`,kind:'interaction',capability,...(actorId?{actorId}:{}),
|
|
17
|
+
preconditions:[],effects:[],verifierTarget:{type:'interaction-contract',capability,settledRequired:true},
|
|
18
|
+
source:{interactionId:id,...(worldRevisionId?{worldRevisionId}:{})}
|
|
19
|
+
};
|
|
20
|
+
if(capability==='OPEN'||capability==='CLOSE'){
|
|
21
|
+
command.targetId=targetId;
|
|
22
|
+
command.preconditions=[{kind:'target-supports-capability',targetId,capability}];
|
|
23
|
+
command.effect={kind:'execute-interaction-contract',capability,targetId};
|
|
24
|
+
command.verifierTarget.targetId=targetId;
|
|
25
|
+
} else if(capability==='PICKUP'){
|
|
26
|
+
command.targetId=targetId;
|
|
27
|
+
command.preconditions=[{kind:'target-carryable',targetId}];
|
|
28
|
+
command.effect={kind:'execute-pickup',targetId};
|
|
29
|
+
command.verifierTarget={type:'pickup',targetId,heldRequired:true};
|
|
30
|
+
} else if(capability==='PLACE'){
|
|
31
|
+
const supportId=clean(intent.supportId);
|
|
32
|
+
if(!supportId) throw new TypeError('PLACE interaction intent requires supportId');
|
|
33
|
+
command.supportId=supportId; command.targetId=supportId;
|
|
34
|
+
command.preconditions=[{kind:'actor-holds-object'},{kind:'support-target',supportId}];
|
|
35
|
+
command.effect={kind:'execute-place',supportId};
|
|
36
|
+
command.verifierTarget={type:'place',supportId,supportVerifiedRequired:true,settledRequired:true};
|
|
37
|
+
} else if(capability==='SWITCH'){
|
|
38
|
+
const stateKey=clean(intent.stateKey); if(!stateKey) throw new TypeError('SWITCH interaction intent requires stateKey');
|
|
39
|
+
if(!Object.prototype.hasOwnProperty.call(intent,'value')) throw new TypeError('SWITCH interaction intent requires value');
|
|
40
|
+
if(typeof intent.value!=='string' && typeof intent.value!=='number' && typeof intent.value!=='boolean' && intent.value!==null) throw new TypeError('SWITCH value must be JSON scalar');
|
|
41
|
+
command.targetId=targetId;
|
|
42
|
+
command.stateKey=stateKey; command.value=intent.value;
|
|
43
|
+
command.preconditions=[{kind:'state-target',targetId,stateKey}];
|
|
44
|
+
command.effect={kind:'set-state',targetId,stateKey,value:intent.value};
|
|
45
|
+
command.verifierTarget={type:'state-transition',targetId,stateKey,value:intent.value};
|
|
46
|
+
}
|
|
47
|
+
return command;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function compileBehaviorGraph(interactions=[],opts={}){
|
|
51
|
+
if(!Array.isArray(interactions)) throw new TypeError('Interactions must be an array');
|
|
52
|
+
const commands=interactions.map(item=>compileInteractionIntent(item,opts));
|
|
53
|
+
const ids=new Set();
|
|
54
|
+
for(const command of commands){if(ids.has(command.commandId)) throw new TypeError(`Duplicate runtime command: ${command.commandId}`); ids.add(command.commandId);}
|
|
55
|
+
return {schema:BEHAVIOR_COMMAND_SCHEMA,schemaVersion:BEHAVIOR_COMMAND_VERSION,commands};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function verifyBehaviorCommand(command,result){
|
|
59
|
+
const verifier=command?.verifierTarget;
|
|
60
|
+
if(!verifier) return {verified:false,reason:'VERIFIER_TARGET_MISSING'};
|
|
61
|
+
if(verifier.type==='interaction-contract'){
|
|
62
|
+
const verified=result?.status==='action-completed'&&result?.targetReached===true&&result?.settled===true&&result?.targetId===verifier.targetId&&result?.action?.toUpperCase()===verifier.capability;
|
|
63
|
+
return verified?{verified:true}:{verified:false,reason:'POST_CONDITION_NOT_VERIFIED'};
|
|
64
|
+
}
|
|
65
|
+
if(verifier.type==='pickup') return result?.status==='held' && result?.targetId===verifier.targetId ? {verified:true}:{verified:false,reason:'PICKUP_NOT_VERIFIED'};
|
|
66
|
+
if(verifier.type==='place') return result?.status==='placed' && result?.supportVerified===true && result?.settled===true && result?.targetId===verifier.supportId ? {verified:true}:{verified:false,reason:'PLACE_NOT_VERIFIED'};
|
|
67
|
+
if(verifier.type==='state-transition') return result?.status==='state-transition-applied' && result?.targetId===verifier.targetId && result?.stateKey===verifier.stateKey && Object.is(result?.value,verifier.value) ? {verified:true}:{verified:false,reason:'STATE_TRANSITION_NOT_VERIFIED'};
|
|
68
|
+
return {verified:false,reason:'VERIFIER_TYPE_UNSUPPORTED'};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function executeBehaviorCommand(runtime,command){
|
|
72
|
+
if(command?.schema!==BEHAVIOR_COMMAND_SCHEMA || command.schemaVersion!==BEHAVIOR_COMMAND_VERSION){ const error=new TypeError('Unsupported RuntimeCommand'); error.code='RUNTIME_COMMAND_UNSUPPORTED'; throw error; }
|
|
73
|
+
if(command.kind!=='interaction') { const error=new TypeError(`Unsupported RuntimeCommand kind: ${command.kind}`); error.code='RUNTIME_COMMAND_KIND_UNSUPPORTED'; throw error; }
|
|
74
|
+
if(command.capability==='OPEN'||command.capability==='CLOSE') return runtime.commands?.approachAndInteract ? runtime.commands.approachAndInteract(command.actorId,command.targetId,command.capability.toLowerCase()) : runtime.interactions.approachAndInteract(command.actorId,command.targetId,command.capability.toLowerCase());
|
|
75
|
+
if(command.capability==='PICKUP') return runtime.commands?.approachAndPickup ? runtime.commands.approachAndPickup(command.actorId,command.targetId) : runtime.interactions.approachAndPickup(command.actorId,command.targetId);
|
|
76
|
+
if(command.capability==='PLACE') return runtime.commands?.approachAndPlace ? runtime.commands.approachAndPlace(command.actorId,command.supportId) : runtime.interactions.approachAndPlace(command.actorId,command.supportId);
|
|
77
|
+
if(command.capability==='SWITCH') return runtime.commands?.applyStateTransition ? runtime.commands.applyStateTransition(command.targetId,command.stateKey,command.value,{source:'behavior-command',commandId:command.commandId}) : runtime.applyStateTransition(command.targetId,command.stateKey,command.value,{source:'behavior-command',commandId:command.commandId});
|
|
78
|
+
const error=new TypeError(`Unsupported RuntimeCommand capability: ${command.capability}`); error.code='RUNTIME_COMMAND_CAPABILITY_UNSUPPORTED'; throw error;
|
|
79
|
+
}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
// A declarative, project-owned behavior model. It never creates colliders or
|
|
2
|
+
// claims physics verification: visuals and persistence belong to Code Project.
|
|
3
|
+
const error = code => Object.assign(new Error(code), { code });
|
|
4
|
+
const keyName = value => typeof value === 'string' && /^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(value);
|
|
5
|
+
const scalar = value => value === null || ['string', 'boolean'].includes(typeof value)
|
|
6
|
+
|| (typeof value === 'number' && Number.isFinite(value));
|
|
7
|
+
const plain = value => value && typeof value === 'object' && !Array.isArray(value)
|
|
8
|
+
&& [Object.prototype, null].includes(Object.getPrototypeOf(value));
|
|
9
|
+
const assert = value => { if (!value) throw error('PROJECT_MACHINE_DEFINITION_INVALID'); };
|
|
10
|
+
const copy = value => structuredClone(value);
|
|
11
|
+
const ops = new Set(['eq', 'ne', 'lt', 'lte', 'gt', 'gte']);
|
|
12
|
+
const checkCount = (value, max) => Array.isArray(value) && value.length <= max;
|
|
13
|
+
|
|
14
|
+
function compileConditions(conditions, initial) {
|
|
15
|
+
assert(checkCount(conditions, 16));
|
|
16
|
+
return conditions.map(item => {
|
|
17
|
+
assert(plain(item) && keyName(item.field) && Object.hasOwn(initial, item.field) && ops.has(item.op));
|
|
18
|
+
const valueDefined = Object.hasOwn(item, 'value'), otherDefined = Object.hasOwn(item, 'other');
|
|
19
|
+
assert(valueDefined !== otherDefined && Object.keys(item).every(k => ['field', 'op', 'value', 'other'].includes(k)));
|
|
20
|
+
if (otherDefined) assert(keyName(item.other) && Object.hasOwn(initial, item.other));
|
|
21
|
+
else assert(scalar(item.value));
|
|
22
|
+
if (!['eq', 'ne'].includes(item.op)) {
|
|
23
|
+
assert(typeof initial[item.field] === 'number');
|
|
24
|
+
assert(otherDefined ? typeof initial[item.other] === 'number' : typeof item.value === 'number');
|
|
25
|
+
}
|
|
26
|
+
return copy(item);
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function compileEffects(effects, initial) {
|
|
31
|
+
assert(checkCount(effects, 16) && effects.length > 0);
|
|
32
|
+
const fields = new Set();
|
|
33
|
+
return effects.map(item => {
|
|
34
|
+
assert(plain(item) && keyName(item.field) && Object.hasOwn(initial, item.field) && !fields.has(item.field));
|
|
35
|
+
assert(['set', 'add'].includes(item.op) && scalar(item.value));
|
|
36
|
+
assert(Object.keys(item).every(k => ['field', 'op', 'value'].includes(k)));
|
|
37
|
+
if (item.op === 'add') assert(typeof initial[item.field] === 'number' && typeof item.value === 'number');
|
|
38
|
+
else assert(typeof initial[item.field] === typeof item.value
|
|
39
|
+
&& (initial[item.field] !== null || item.value === null));
|
|
40
|
+
fields.add(item.field);
|
|
41
|
+
return copy(item);
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function compileProjectStateMachine({ initialState, transitions, timers = [], ranges = {} }) {
|
|
46
|
+
assert(plain(initialState) && Object.keys(initialState).length > 0 && Object.keys(initialState).length <= 64);
|
|
47
|
+
for (const [key, value] of Object.entries(initialState)) assert(keyName(key) && scalar(value));
|
|
48
|
+
assert(plain(ranges) && Object.keys(ranges).every(key => Object.hasOwn(initialState, key)));
|
|
49
|
+
const limits = {};
|
|
50
|
+
for (const [key, range] of Object.entries(ranges)) {
|
|
51
|
+
assert(typeof initialState[key] === 'number' && plain(range) && Object.keys(range).every(k=>['min','max'].includes(k)));
|
|
52
|
+
assert(Number.isFinite(range.min) && Number.isFinite(range.max) && range.min <= range.max);
|
|
53
|
+
limits[key] = copy(range);
|
|
54
|
+
}
|
|
55
|
+
assert(checkCount(transitions, 64) && transitions.length > 0);
|
|
56
|
+
const compiled = new Map();
|
|
57
|
+
const knownValues = new Map(Object.entries(initialState)
|
|
58
|
+
.filter(([,value]) => typeof value !== 'number')
|
|
59
|
+
.map(([key,value]) => [key, new Set([value])]));
|
|
60
|
+
for (const item of transitions) {
|
|
61
|
+
assert(plain(item) && keyName(item.name) && !compiled.has(item.name)
|
|
62
|
+
&& (item.description == null || typeof item.description === 'string')
|
|
63
|
+
&& (item.expose == null || typeof item.expose === 'boolean'));
|
|
64
|
+
assert(Object.keys(item).every(k=>['name','description','expose','when','effects'].includes(k)));
|
|
65
|
+
const effects = compileEffects(item.effects, initialState);
|
|
66
|
+
for (const effect of effects) if (effect.op === 'set' && knownValues.has(effect.field)) {
|
|
67
|
+
knownValues.get(effect.field).add(effect.value);
|
|
68
|
+
}
|
|
69
|
+
compiled.set(item.name, { name:item.name, description:item.description || '', expose:item.expose !== false,
|
|
70
|
+
when:compileConditions(item.when || [], initialState), effects });
|
|
71
|
+
}
|
|
72
|
+
assert(checkCount(timers, 16));
|
|
73
|
+
const usedTimerFields = new Set();
|
|
74
|
+
const clocks = timers.map(item => {
|
|
75
|
+
assert(plain(item) && keyName(item.field) && !usedTimerFields.has(item.field));
|
|
76
|
+
assert(typeof initialState[item.field] === 'number' && Number.isFinite(item.rate) && item.rate > 0
|
|
77
|
+
&& Number.isFinite(item.max) && item.max >= initialState[item.field]);
|
|
78
|
+
assert(Object.keys(item).every(k=>['field','rate','max','when','onComplete'].includes(k)));
|
|
79
|
+
if (item.onComplete != null) assert(compiled.has(item.onComplete) && compiled.get(item.onComplete).expose === false);
|
|
80
|
+
usedTimerFields.add(item.field);
|
|
81
|
+
return {field:item.field,rate:item.rate,max:item.max,
|
|
82
|
+
when:compileConditions(item.when || [], initialState),onComplete:item.onComplete || null};
|
|
83
|
+
});
|
|
84
|
+
const definition = { initial:copy(initialState), transitions:compiled, timers:clocks, ranges:limits, knownValues };
|
|
85
|
+
validateProjectMachineState(definition, initialState);
|
|
86
|
+
return definition;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function validateProjectMachineState(definition, state) {
|
|
90
|
+
if (!plain(state)) throw error('PROJECT_MACHINE_STATE_INVALID');
|
|
91
|
+
const initial = definition.initial;
|
|
92
|
+
if (Object.keys(state).length !== Object.keys(initial).length) throw error('PROJECT_MACHINE_STATE_INVALID');
|
|
93
|
+
for (const [field, original] of Object.entries(initial)) {
|
|
94
|
+
const value = state[field];
|
|
95
|
+
if (!Object.hasOwn(state, field) || !scalar(value) || typeof value !== typeof original
|
|
96
|
+
|| (original === null && value !== null)) throw error('PROJECT_MACHINE_STATE_INVALID');
|
|
97
|
+
const range = definition.ranges[field];
|
|
98
|
+
if (range && (value < range.min || value > range.max)) throw error('PROJECT_MACHINE_STATE_INVALID');
|
|
99
|
+
if (definition.knownValues.has(field) && !definition.knownValues.get(field).has(value)) {
|
|
100
|
+
throw error('PROJECT_MACHINE_STATE_INVALID');
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return copy(state);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function eligible(when, state) {
|
|
107
|
+
return when.every(c => {
|
|
108
|
+
const value = c.other ? state[c.other] : c.value;
|
|
109
|
+
switch (c.op) {
|
|
110
|
+
case 'eq': return Object.is(state[c.field], value);
|
|
111
|
+
case 'ne': return !Object.is(state[c.field], value);
|
|
112
|
+
case 'lt': return state[c.field] < value;
|
|
113
|
+
case 'lte': return state[c.field] <= value;
|
|
114
|
+
case 'gt': return state[c.field] > value;
|
|
115
|
+
case 'gte': return state[c.field] >= value;
|
|
116
|
+
default: return false;
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function step(definition, transition, state) {
|
|
122
|
+
if (!eligible(transition.when, state)) throw error('PROJECT_MACHINE_GUARD_FAILED');
|
|
123
|
+
const next = copy(state);
|
|
124
|
+
for (const effect of transition.effects) {
|
|
125
|
+
next[effect.field] = effect.op === 'add' ? next[effect.field] + effect.value : effect.value;
|
|
126
|
+
}
|
|
127
|
+
return validateProjectMachineState(definition, next);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export class ProjectStateMachine {
|
|
131
|
+
constructor(config) {
|
|
132
|
+
this.definition = compileProjectStateMachine(config);
|
|
133
|
+
this.state = copy(this.definition.initial);
|
|
134
|
+
this.object = config.object || null;
|
|
135
|
+
this.onChange = config.onChange || null;
|
|
136
|
+
this.verifyVisual = config.verifyVisual || null;
|
|
137
|
+
assert(this.onChange == null || typeof this.onChange === 'function');
|
|
138
|
+
assert(this.verifyVisual == null || typeof this.verifyVisual === 'function');
|
|
139
|
+
this.sync(this.state, this.state, { kind:'initialize' });
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
read() { return copy(this.state); }
|
|
143
|
+
available(name) {
|
|
144
|
+
const action = this.definition.transitions.get(name);
|
|
145
|
+
return Boolean(action?.expose && eligible(action.when, this.state));
|
|
146
|
+
}
|
|
147
|
+
sync(next, previous, meta) {
|
|
148
|
+
const payload = copy(next), prior = copy(previous);
|
|
149
|
+
const returned = this.onChange?.(payload, prior, meta);
|
|
150
|
+
if (returned && typeof returned.then === 'function') throw error('PROJECT_MACHINE_ASYNC_CALLBACK_UNSUPPORTED');
|
|
151
|
+
const check = this.verifyVisual?.(copy(next), {object:this.object,kind:meta.kind});
|
|
152
|
+
if (check && typeof check.then === 'function') throw error('PROJECT_MACHINE_ASYNC_CALLBACK_UNSUPPORTED');
|
|
153
|
+
if (this.verifyVisual && check !== true) throw error('PROJECT_MACHINE_VISUAL_UNVERIFIED');
|
|
154
|
+
}
|
|
155
|
+
commit(next, meta) {
|
|
156
|
+
const previous = this.state;
|
|
157
|
+
if (JSON.stringify(next) === JSON.stringify(previous)) return {changed:false,state:this.read()};
|
|
158
|
+
try { this.sync(next, previous, meta); }
|
|
159
|
+
catch (failure) {
|
|
160
|
+
try { this.onChange?.(copy(previous), copy(next), {kind:'rollback'}); } catch { /* Preserve original error. */ }
|
|
161
|
+
throw failure;
|
|
162
|
+
}
|
|
163
|
+
this.state = copy(next);
|
|
164
|
+
return {changed:true,state:this.read()};
|
|
165
|
+
}
|
|
166
|
+
execute(name) {
|
|
167
|
+
const action = this.definition.transitions.get(name);
|
|
168
|
+
if (!action?.expose) throw error('PROJECT_MACHINE_ACTION_UNAVAILABLE');
|
|
169
|
+
const next = step(this.definition, action, this.state);
|
|
170
|
+
return {transition:name,...this.commit(next,{kind:'action',name})};
|
|
171
|
+
}
|
|
172
|
+
advance(seconds) {
|
|
173
|
+
if (!Number.isFinite(seconds) || seconds < 0 || seconds > 60) throw error('PROJECT_MACHINE_CLOCK_INVALID');
|
|
174
|
+
if (seconds === 0) return {changed:false,state:this.read()};
|
|
175
|
+
let next = this.read(), completed = [];
|
|
176
|
+
for (const timer of this.definition.timers) {
|
|
177
|
+
if (!eligible(timer.when, next)) continue;
|
|
178
|
+
const previous = next[timer.field];
|
|
179
|
+
next[timer.field] = Math.min(timer.max, Number((previous + seconds * timer.rate).toFixed(9)));
|
|
180
|
+
if (timer.onComplete && previous < timer.max && next[timer.field] >= timer.max) {
|
|
181
|
+
next = step(this.definition, this.definition.transitions.get(timer.onComplete), next);
|
|
182
|
+
completed.push(timer.onComplete);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
validateProjectMachineState(this.definition, next);
|
|
186
|
+
return {...this.commit(next,{kind:'clock',seconds,completed}),completed};
|
|
187
|
+
}
|
|
188
|
+
validate(state) { return validateProjectMachineState(this.definition, state); }
|
|
189
|
+
restore(state) {
|
|
190
|
+
return this.commit(this.validate(state),{kind:'restore'});
|
|
191
|
+
}
|
|
192
|
+
listedActions() {
|
|
193
|
+
return [...this.definition.transitions.values()].filter(action=>action.expose);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
const SCHEMA='agentscape.rule-graph';
|
|
2
|
+
const VERSION=1;
|
|
3
|
+
const allowedEffectKinds=new Set(['set-state']);
|
|
4
|
+
const clean=v=>typeof v==='string'?v.trim():'';
|
|
5
|
+
const scalar=v=>v===null||typeof v==='string'||typeof v==='number'||typeof v==='boolean';
|
|
6
|
+
|
|
7
|
+
export function compileRuleGraph(rules=[]){
|
|
8
|
+
if(!Array.isArray(rules)) throw new TypeError('Rules must be an array');
|
|
9
|
+
const ids=new Set();
|
|
10
|
+
const compiled=rules.map((rule,index)=>{
|
|
11
|
+
if(!rule||typeof rule!=='object'||Array.isArray(rule)) throw new TypeError(`Rule[${index}] must be an object`);
|
|
12
|
+
const id=clean(rule.id),event=clean(rule.event),effect=rule.effect;
|
|
13
|
+
if(!id||ids.has(id)) throw new TypeError(`Rule[${index}] requires unique id`); ids.add(id);
|
|
14
|
+
if(!event) throw new TypeError(`Rule[${index}] requires event`);
|
|
15
|
+
if(!effect||typeof effect!=='object'||allowedEffectKinds.has(effect.kind)===false) throw new TypeError(`Rule[${index}] unsupported effect`);
|
|
16
|
+
const targetId=clean(effect.targetId),stateKey=clean(effect.stateKey);
|
|
17
|
+
if(!targetId||!stateKey||!Object.prototype.hasOwnProperty.call(effect,'value')||!scalar(effect.value)) throw new TypeError(`Rule[${index}] set-state effect requires targetId/stateKey/scalar value`);
|
|
18
|
+
const condition=rule.condition?compileCondition(rule.condition,`Rule[${index}] condition`):null;
|
|
19
|
+
return {id,event,condition,effect:{kind:'set-state',targetId,stateKey,value:effect.value},description:clean(rule.description)||undefined};
|
|
20
|
+
});
|
|
21
|
+
return {schema:SCHEMA,schemaVersion:VERSION,rules:compiled};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function compileCondition(condition,label){
|
|
25
|
+
if(!condition||typeof condition!=='object'||Array.isArray(condition)) throw new TypeError(`${label} must be an object`);
|
|
26
|
+
const kind=clean(condition.kind);
|
|
27
|
+
if(kind==='equals'){
|
|
28
|
+
if(!clean(condition.targetId)||!clean(condition.stateKey)||!Object.prototype.hasOwnProperty.call(condition,'value')||!scalar(condition.value)) throw new TypeError(`${label} equals requires targetId/stateKey/value`);
|
|
29
|
+
return {kind:'equals',targetId:clean(condition.targetId),stateKey:clean(condition.stateKey),value:condition.value};
|
|
30
|
+
}
|
|
31
|
+
if(kind==='not-equals'){
|
|
32
|
+
if(!clean(condition.targetId)||!clean(condition.stateKey)||!Object.prototype.hasOwnProperty.call(condition,'value')||!scalar(condition.value)) throw new TypeError(`${label} not-equals requires targetId/stateKey/value`);
|
|
33
|
+
return {kind:'not-equals',targetId:clean(condition.targetId),stateKey:clean(condition.stateKey),value:condition.value};
|
|
34
|
+
}
|
|
35
|
+
throw new TypeError(`${label} unsupported kind: ${kind}`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function evaluateRuleGraph(graph,event,stateReader){
|
|
39
|
+
if(graph?.schema!==SCHEMA||graph.schemaVersion!==VERSION) throw new TypeError('Unsupported rule graph');
|
|
40
|
+
if(typeof stateReader!=='function') throw new TypeError('stateReader must be a function');
|
|
41
|
+
const matches=[];
|
|
42
|
+
for(const rule of graph.rules){
|
|
43
|
+
if(rule.event!==event) continue;
|
|
44
|
+
if(rule.condition&&!evaluateCondition(rule.condition,stateReader)) continue;
|
|
45
|
+
matches.push(structuredClone(rule.effect));
|
|
46
|
+
}
|
|
47
|
+
return matches;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function evaluateCondition(condition,stateReader){
|
|
51
|
+
const value=stateReader(condition.targetId,condition.stateKey);
|
|
52
|
+
return condition.kind==='equals' ? Object.is(value,condition.value) : !Object.is(value,condition.value);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function executeRuleEffects(runtime,effects,{source='rule-graph',eventId=null,ruleCascadeDepth=null}={}){
|
|
56
|
+
if(!Array.isArray(effects)) throw new TypeError('Rule effects must be an array');
|
|
57
|
+
if(!effects.length) return Promise.resolve({status:'no-rule-match',effects:[]});
|
|
58
|
+
return runtime.mutate(`rule:${eventId||source}`,async()=>{
|
|
59
|
+
const applied=[];
|
|
60
|
+
for(const effect of effects){
|
|
61
|
+
if(effect.kind!=='set-state') { const error=new TypeError(`Unsupported rule effect: ${effect.kind}`); error.code='RULE_EFFECT_UNSUPPORTED'; throw error; }
|
|
62
|
+
const result=runtime.applyStateTransition(effect.targetId,effect.stateKey,effect.value,{source:'rule-graph',event:eventId,...(ruleCascadeDepth == null ? {} : {ruleCascadeDepth})});
|
|
63
|
+
if(result?.status!=='state-transition-applied') throw new Error(`Rule state transition rejected: ${effect.targetId}.${effect.stateKey}`);
|
|
64
|
+
applied.push(result);
|
|
65
|
+
}
|
|
66
|
+
return {status:'rule-effects-applied',effects:applied};
|
|
67
|
+
}, ruleCascadeDepth == null ? {} : {ruleCascadeDepth});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export {SCHEMA as RULE_GRAPH_SCHEMA,VERSION as RULE_GRAPH_VERSION};
|