@decaf-ts/as-graph 0.2.0 → 0.4.0
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/README.md +160 -2
- package/dist/as-graph.cjs +1 -1
- package/dist/as-graph.cjs.map +1 -1
- package/dist/as-graph.js +1 -1
- package/dist/as-graph.js.map +1 -1
- package/lib/cjs/dagster/DagsterGraphEventBridge.cjs +344 -0
- package/lib/cjs/dagster/DagsterGraphEventBridge.cjs.map +1 -0
- package/lib/cjs/dagster/DagsterGraphExecutionBackend.cjs +789 -0
- package/lib/cjs/dagster/DagsterGraphExecutionBackend.cjs.map +1 -0
- package/lib/cjs/dagster/DagsterResultMapper.cjs +56 -0
- package/lib/cjs/dagster/DagsterResultMapper.cjs.map +1 -0
- package/lib/cjs/dagster/DagsterTypes.cjs +4 -0
- package/lib/cjs/dagster/DagsterTypes.cjs.map +1 -0
- package/lib/cjs/dagster/capabilities.cjs +102 -0
- package/lib/cjs/dagster/capabilities.cjs.map +1 -0
- package/lib/cjs/dagster/constants.cjs +92 -0
- package/lib/cjs/dagster/constants.cjs.map +1 -0
- package/lib/cjs/dagster/index.cjs +32 -0
- package/lib/cjs/dagster/index.cjs.map +1 -0
- package/lib/cjs/engine/constants.cjs +6 -1
- package/lib/cjs/engine/constants.cjs.map +1 -1
- package/lib/cjs/engine/execution/GraphCodeMode.cjs +137 -0
- package/lib/cjs/engine/execution/GraphCodeMode.cjs.map +1 -0
- package/lib/cjs/engine/execution/GraphExecutionBackend.cjs +89 -0
- package/lib/cjs/engine/execution/GraphExecutionBackend.cjs.map +1 -0
- package/lib/cjs/engine/execution/GraphExecutionBackendRegistry.cjs +107 -0
- package/lib/cjs/engine/execution/GraphExecutionBackendRegistry.cjs.map +1 -0
- package/lib/cjs/engine/execution/GraphExecutionEngine.cjs +250 -733
- package/lib/cjs/engine/execution/GraphExecutionEngine.cjs.map +1 -1
- package/lib/cjs/engine/execution/LocalGraphExecutionBackend.cjs +804 -0
- package/lib/cjs/engine/execution/LocalGraphExecutionBackend.cjs.map +1 -0
- package/lib/cjs/engine/execution/index.cjs +4 -0
- package/lib/cjs/engine/execution/index.cjs.map +1 -1
- package/lib/cjs/engine/index.cjs +5 -0
- package/lib/cjs/engine/index.cjs.map +1 -1
- package/lib/cjs/engine/loops/ConditionEvaluator.cjs +116 -0
- package/lib/cjs/engine/loops/ConditionEvaluator.cjs.map +1 -0
- package/lib/cjs/engine/loops/GraphConditionEvaluator.cjs +25 -2
- package/lib/cjs/engine/loops/GraphConditionEvaluator.cjs.map +1 -1
- package/lib/cjs/engine/loops/index.cjs +1 -0
- package/lib/cjs/engine/loops/index.cjs.map +1 -1
- package/lib/cjs/engine/runs/GraphRunService.cjs +121 -3
- package/lib/cjs/engine/runs/GraphRunService.cjs.map +1 -1
- package/lib/cjs/engine/runs/InMemoryGraphRunStore.cjs +33 -0
- package/lib/cjs/engine/runs/InMemoryGraphRunStore.cjs.map +1 -1
- package/lib/cjs/engine/runs/ownership.cjs +100 -11
- package/lib/cjs/engine/runs/ownership.cjs.map +1 -1
- package/lib/cjs/engine/services/GraphRunModelService.cjs +16 -0
- package/lib/cjs/engine/services/GraphRunModelService.cjs.map +1 -1
- package/lib/cjs/engine/services/GraphWorkflowService.cjs +153 -16
- package/lib/cjs/engine/services/GraphWorkflowService.cjs.map +1 -1
- package/lib/cjs/mastra/MastraCapabilities.cjs +171 -0
- package/lib/cjs/mastra/MastraCapabilities.cjs.map +1 -0
- package/lib/cjs/mastra/MastraConditionBridge.cjs +39 -0
- package/lib/cjs/mastra/MastraConditionBridge.cjs.map +1 -0
- package/lib/cjs/mastra/MastraEventBridge.cjs +486 -0
- package/lib/cjs/mastra/MastraEventBridge.cjs.map +1 -0
- package/lib/cjs/mastra/MastraGraphExecutionBackend.cjs +351 -0
- package/lib/cjs/mastra/MastraGraphExecutionBackend.cjs.map +1 -0
- package/lib/cjs/mastra/MastraResumeGuard.cjs +127 -0
- package/lib/cjs/mastra/MastraResumeGuard.cjs.map +1 -0
- package/lib/cjs/mastra/MastraSchemaConverter.cjs +124 -0
- package/lib/cjs/mastra/MastraSchemaConverter.cjs.map +1 -0
- package/lib/cjs/mastra/MastraWorkflowCompiler.cjs +461 -0
- package/lib/cjs/mastra/MastraWorkflowCompiler.cjs.map +1 -0
- package/lib/cjs/mastra/MastraWorkflowManager.cjs +401 -0
- package/lib/cjs/mastra/MastraWorkflowManager.cjs.map +1 -0
- package/lib/cjs/mastra/index.cjs +35 -0
- package/lib/cjs/mastra/index.cjs.map +1 -0
- package/lib/cjs/mastra/types.cjs +34 -0
- package/lib/cjs/mastra/types.cjs.map +1 -0
- package/lib/cjs/nest/graph/GraphEngineCapabilityManifest.cjs +136 -0
- package/lib/cjs/nest/graph/GraphEngineCapabilityManifest.cjs.map +1 -0
- package/lib/cjs/nest/graph/GraphEngineCapabilityService.cjs +140 -0
- package/lib/cjs/nest/graph/GraphEngineCapabilityService.cjs.map +1 -0
- package/lib/cjs/nest/graph/GraphEngineController.cjs +227 -0
- package/lib/cjs/nest/graph/GraphEngineController.cjs.map +1 -0
- package/lib/cjs/nest/graph/GraphExecutionModule.cjs +30 -2
- package/lib/cjs/nest/graph/GraphExecutionModule.cjs.map +1 -1
- package/lib/cjs/nest/graph/GraphRunController.cjs +208 -28
- package/lib/cjs/nest/graph/GraphRunController.cjs.map +1 -1
- package/lib/cjs/nest/graph/GraphWorkflowController.cjs +97 -14
- package/lib/cjs/nest/graph/GraphWorkflowController.cjs.map +1 -1
- package/lib/cjs/nest/graph/index.cjs +3 -0
- package/lib/cjs/nest/graph/index.cjs.map +1 -1
- package/lib/cjs/nest/graph/main.cjs +54 -0
- package/lib/cjs/nest/graph/main.cjs.map +1 -0
- package/lib/cjs/nest/graph/servingDates.cjs +53 -0
- package/lib/cjs/nest/graph/servingDates.cjs.map +1 -0
- package/lib/cjs/nest/graph/servingErrors.cjs +68 -0
- package/lib/cjs/nest/graph/servingErrors.cjs.map +1 -0
- package/lib/cjs/node/flow/if/node.cjs +27 -9
- package/lib/cjs/node/flow/if/node.cjs.map +1 -1
- package/lib/cjs/node/flow/loop/until/node.cjs +5 -2
- package/lib/cjs/node/flow/loop/until/node.cjs.map +1 -1
- package/lib/cjs/node/flow/loop/while/node.cjs +8 -2
- package/lib/cjs/node/flow/loop/while/node.cjs.map +1 -1
- package/lib/cjs/node/flow/switch/node.cjs +2 -37
- package/lib/cjs/node/flow/switch/node.cjs.map +1 -1
- package/lib/cjs/node/utility/code/node.cjs +11 -3
- package/lib/cjs/node/utility/code/node.cjs.map +1 -1
- package/lib/cjs/ram/GraphRunStore.cjs +14 -0
- package/lib/cjs/ram/GraphRunStore.cjs.map +1 -1
- package/lib/cjs/shared/graph/catalog/GraphManifestCompiler.cjs +2 -3
- package/lib/cjs/shared/graph/catalog/GraphManifestCompiler.cjs.map +1 -1
- package/lib/cjs/shared/graph/constants.cjs +8 -0
- package/lib/cjs/shared/graph/constants.cjs.map +1 -1
- package/lib/cjs/shared/graph/index.cjs +2 -1
- package/lib/cjs/shared/graph/index.cjs.map +1 -1
- package/lib/cjs/shared/graph/layout/GraphWorkflowLayout.cjs +146 -0
- package/lib/cjs/shared/graph/layout/GraphWorkflowLayout.cjs.map +1 -0
- package/lib/cjs/shared/graph/layout/index.cjs +23 -0
- package/lib/cjs/shared/graph/layout/index.cjs.map +1 -0
- package/lib/cjs/shared/graph/layout/layout-options.cjs +93 -0
- package/lib/cjs/shared/graph/layout/layout-options.cjs.map +1 -0
- package/lib/cjs/shared/ui/index.cjs +8 -10
- package/lib/cjs/shared/ui/index.cjs.map +1 -1
- package/lib/esm/dagster/DagsterGraphEventBridge.js +339 -0
- package/lib/esm/dagster/DagsterGraphEventBridge.js.map +1 -0
- package/lib/esm/dagster/DagsterGraphExecutionBackend.js +781 -0
- package/lib/esm/dagster/DagsterGraphExecutionBackend.js.map +1 -0
- package/lib/esm/dagster/DagsterResultMapper.js +51 -0
- package/lib/esm/dagster/DagsterResultMapper.js.map +1 -0
- package/lib/esm/dagster/DagsterTypes.js +2 -0
- package/lib/esm/dagster/DagsterTypes.js.map +1 -0
- package/lib/esm/dagster/capabilities.js +97 -0
- package/lib/esm/dagster/capabilities.js.map +1 -0
- package/lib/esm/dagster/constants.js +88 -0
- package/lib/esm/dagster/constants.js.map +1 -0
- package/lib/esm/dagster/index.js +15 -0
- package/lib/esm/dagster/index.js.map +1 -0
- package/lib/esm/engine/constants.js +5 -0
- package/lib/esm/engine/constants.js.map +1 -1
- package/lib/esm/engine/execution/GraphCodeMode.js +132 -0
- package/lib/esm/engine/execution/GraphCodeMode.js.map +1 -0
- package/lib/esm/engine/execution/GraphExecutionBackend.js +83 -0
- package/lib/esm/engine/execution/GraphExecutionBackend.js.map +1 -0
- package/lib/esm/engine/execution/GraphExecutionBackendRegistry.js +102 -0
- package/lib/esm/engine/execution/GraphExecutionBackendRegistry.js.map +1 -0
- package/lib/esm/engine/execution/GraphExecutionEngine.js +232 -716
- package/lib/esm/engine/execution/GraphExecutionEngine.js.map +1 -1
- package/lib/esm/engine/execution/LocalGraphExecutionBackend.js +799 -0
- package/lib/esm/engine/execution/LocalGraphExecutionBackend.js.map +1 -0
- package/lib/esm/engine/execution/index.js +4 -0
- package/lib/esm/engine/execution/index.js.map +1 -1
- package/lib/esm/engine/index.js +5 -0
- package/lib/esm/engine/index.js.map +1 -1
- package/lib/esm/engine/loops/ConditionEvaluator.js +108 -0
- package/lib/esm/engine/loops/ConditionEvaluator.js.map +1 -0
- package/lib/esm/engine/loops/GraphConditionEvaluator.js +25 -2
- package/lib/esm/engine/loops/GraphConditionEvaluator.js.map +1 -1
- package/lib/esm/engine/loops/index.js +1 -0
- package/lib/esm/engine/loops/index.js.map +1 -1
- package/lib/esm/engine/runs/GraphRunService.js +123 -5
- package/lib/esm/engine/runs/GraphRunService.js.map +1 -1
- package/lib/esm/engine/runs/InMemoryGraphRunStore.js +33 -0
- package/lib/esm/engine/runs/InMemoryGraphRunStore.js.map +1 -1
- package/lib/esm/engine/runs/ownership.js +97 -11
- package/lib/esm/engine/runs/ownership.js.map +1 -1
- package/lib/esm/engine/services/GraphRunModelService.js +16 -0
- package/lib/esm/engine/services/GraphRunModelService.js.map +1 -1
- package/lib/esm/engine/services/GraphWorkflowService.js +155 -18
- package/lib/esm/engine/services/GraphWorkflowService.js.map +1 -1
- package/lib/esm/mastra/MastraCapabilities.js +164 -0
- package/lib/esm/mastra/MastraCapabilities.js.map +1 -0
- package/lib/esm/mastra/MastraConditionBridge.js +34 -0
- package/lib/esm/mastra/MastraConditionBridge.js.map +1 -0
- package/lib/esm/mastra/MastraEventBridge.js +481 -0
- package/lib/esm/mastra/MastraEventBridge.js.map +1 -0
- package/lib/esm/mastra/MastraGraphExecutionBackend.js +346 -0
- package/lib/esm/mastra/MastraGraphExecutionBackend.js.map +1 -0
- package/lib/esm/mastra/MastraResumeGuard.js +123 -0
- package/lib/esm/mastra/MastraResumeGuard.js.map +1 -0
- package/lib/esm/mastra/MastraSchemaConverter.js +119 -0
- package/lib/esm/mastra/MastraSchemaConverter.js.map +1 -0
- package/lib/esm/mastra/MastraWorkflowCompiler.js +456 -0
- package/lib/esm/mastra/MastraWorkflowCompiler.js.map +1 -0
- package/lib/esm/mastra/MastraWorkflowManager.js +396 -0
- package/lib/esm/mastra/MastraWorkflowManager.js.map +1 -0
- package/lib/esm/mastra/index.js +18 -0
- package/lib/esm/mastra/index.js.map +1 -0
- package/lib/esm/mastra/types.js +30 -0
- package/lib/esm/mastra/types.js.map +1 -0
- package/lib/esm/nest/graph/GraphEngineCapabilityManifest.js +129 -0
- package/lib/esm/nest/graph/GraphEngineCapabilityManifest.js.map +1 -0
- package/lib/esm/nest/graph/GraphEngineCapabilityService.js +131 -0
- package/lib/esm/nest/graph/GraphEngineCapabilityService.js.map +1 -0
- package/lib/esm/nest/graph/GraphEngineController.js +218 -0
- package/lib/esm/nest/graph/GraphEngineController.js.map +1 -0
- package/lib/esm/nest/graph/GraphExecutionModule.js +30 -2
- package/lib/esm/nest/graph/GraphExecutionModule.js.map +1 -1
- package/lib/esm/nest/graph/GraphRunController.js +209 -29
- package/lib/esm/nest/graph/GraphRunController.js.map +1 -1
- package/lib/esm/nest/graph/GraphWorkflowController.js +98 -15
- package/lib/esm/nest/graph/GraphWorkflowController.js.map +1 -1
- package/lib/esm/nest/graph/index.js +3 -0
- package/lib/esm/nest/graph/index.js.map +1 -1
- package/lib/esm/nest/graph/main.js +51 -0
- package/lib/esm/nest/graph/main.js.map +1 -0
- package/lib/esm/nest/graph/servingDates.js +49 -0
- package/lib/esm/nest/graph/servingDates.js.map +1 -0
- package/lib/esm/nest/graph/servingErrors.js +63 -0
- package/lib/esm/nest/graph/servingErrors.js.map +1 -0
- package/lib/esm/node/flow/if/node.js +27 -9
- package/lib/esm/node/flow/if/node.js.map +1 -1
- package/lib/esm/node/flow/loop/until/node.js +5 -2
- package/lib/esm/node/flow/loop/until/node.js.map +1 -1
- package/lib/esm/node/flow/loop/while/node.js +8 -2
- package/lib/esm/node/flow/loop/while/node.js.map +1 -1
- package/lib/esm/node/flow/switch/node.js +2 -37
- package/lib/esm/node/flow/switch/node.js.map +1 -1
- package/lib/esm/node/utility/code/node.js +11 -3
- package/lib/esm/node/utility/code/node.js.map +1 -1
- package/lib/esm/ram/GraphRunStore.js +14 -0
- package/lib/esm/ram/GraphRunStore.js.map +1 -1
- package/lib/esm/shared/graph/GraphExecutionStateMapper.js.map +1 -1
- package/lib/esm/shared/graph/catalog/GraphManifestCompiler.js +2 -3
- package/lib/esm/shared/graph/catalog/GraphManifestCompiler.js.map +1 -1
- package/lib/esm/shared/graph/constants.js +8 -0
- package/lib/esm/shared/graph/constants.js.map +1 -1
- package/lib/esm/shared/graph/document/GraphFlowBuilder.js.map +1 -1
- package/lib/esm/shared/graph/index.js +2 -1
- package/lib/esm/shared/graph/index.js.map +1 -1
- package/lib/esm/shared/graph/layout/GraphWorkflowLayout.js +107 -0
- package/lib/esm/shared/graph/layout/GraphWorkflowLayout.js.map +1 -0
- package/lib/esm/shared/graph/layout/index.js +6 -0
- package/lib/esm/shared/graph/layout/index.js.map +1 -0
- package/lib/esm/shared/graph/layout/layout-options.js +96 -0
- package/lib/esm/shared/graph/layout/layout-options.js.map +1 -0
- package/lib/esm/shared/ui/index.js +8 -10
- package/lib/esm/shared/ui/index.js.map +1 -1
- package/lib/types/dagster/DagsterGraphEventBridge.d.cts +142 -0
- package/lib/types/dagster/DagsterGraphEventBridge.d.mts +142 -0
- package/lib/types/dagster/DagsterGraphExecutionBackend.d.cts +323 -0
- package/lib/types/dagster/DagsterGraphExecutionBackend.d.mts +323 -0
- package/lib/types/dagster/DagsterResultMapper.d.cts +50 -0
- package/lib/types/dagster/DagsterResultMapper.d.mts +50 -0
- package/lib/types/dagster/DagsterTypes.d.cts +355 -0
- package/lib/types/dagster/DagsterTypes.d.mts +355 -0
- package/lib/types/dagster/capabilities.d.cts +34 -0
- package/lib/types/dagster/capabilities.d.mts +34 -0
- package/lib/types/dagster/constants.d.cts +87 -0
- package/lib/types/dagster/constants.d.mts +87 -0
- package/lib/types/dagster/index.d.cts +14 -0
- package/lib/types/dagster/index.d.mts +14 -0
- package/lib/types/engine/constants.d.cts +5 -0
- package/lib/types/engine/constants.d.mts +5 -0
- package/lib/types/engine/execution/GraphCodeMode.d.cts +52 -0
- package/lib/types/engine/execution/GraphCodeMode.d.mts +52 -0
- package/lib/types/engine/execution/GraphExecutionBackend.d.cts +306 -0
- package/lib/types/engine/execution/GraphExecutionBackend.d.mts +306 -0
- package/lib/types/engine/execution/GraphExecutionBackendRegistry.d.cts +59 -0
- package/lib/types/engine/execution/GraphExecutionBackendRegistry.d.mts +59 -0
- package/lib/types/engine/execution/GraphExecutionEngine.d.cts +116 -135
- package/lib/types/engine/execution/GraphExecutionEngine.d.mts +116 -135
- package/lib/types/engine/execution/LocalGraphExecutionBackend.d.cts +232 -0
- package/lib/types/engine/execution/LocalGraphExecutionBackend.d.mts +232 -0
- package/lib/types/engine/execution/index.d.cts +4 -0
- package/lib/types/engine/execution/index.d.mts +4 -0
- package/lib/types/engine/index.d.cts +5 -0
- package/lib/types/engine/index.d.mts +5 -0
- package/lib/types/engine/loops/ConditionEvaluator.d.cts +87 -0
- package/lib/types/engine/loops/ConditionEvaluator.d.mts +87 -0
- package/lib/types/engine/loops/GraphConditionEvaluator.d.cts +27 -7
- package/lib/types/engine/loops/GraphConditionEvaluator.d.mts +27 -7
- package/lib/types/engine/loops/index.d.cts +1 -0
- package/lib/types/engine/loops/index.d.mts +1 -0
- package/lib/types/engine/runs/GraphRunService.d.cts +60 -1
- package/lib/types/engine/runs/GraphRunService.d.mts +60 -1
- package/lib/types/engine/runs/InMemoryGraphRunStore.d.cts +29 -0
- package/lib/types/engine/runs/InMemoryGraphRunStore.d.mts +29 -0
- package/lib/types/engine/runs/ownership.d.cts +89 -4
- package/lib/types/engine/runs/ownership.d.mts +89 -4
- package/lib/types/engine/runs/types.d.cts +12 -1
- package/lib/types/engine/runs/types.d.mts +12 -1
- package/lib/types/engine/services/GraphRunModelService.d.cts +13 -0
- package/lib/types/engine/services/GraphRunModelService.d.mts +13 -0
- package/lib/types/engine/services/GraphWorkflowService.d.cts +74 -2
- package/lib/types/engine/services/GraphWorkflowService.d.mts +74 -2
- package/lib/types/engine/types.d.cts +11 -4
- package/lib/types/engine/types.d.mts +11 -4
- package/lib/types/mastra/MastraCapabilities.d.cts +91 -0
- package/lib/types/mastra/MastraCapabilities.d.mts +91 -0
- package/lib/types/mastra/MastraConditionBridge.d.cts +38 -0
- package/lib/types/mastra/MastraConditionBridge.d.mts +38 -0
- package/lib/types/mastra/MastraEventBridge.d.cts +189 -0
- package/lib/types/mastra/MastraEventBridge.d.mts +189 -0
- package/lib/types/mastra/MastraGraphExecutionBackend.d.cts +119 -0
- package/lib/types/mastra/MastraGraphExecutionBackend.d.mts +119 -0
- package/lib/types/mastra/MastraResumeGuard.d.cts +58 -0
- package/lib/types/mastra/MastraResumeGuard.d.mts +58 -0
- package/lib/types/mastra/MastraSchemaConverter.d.cts +39 -0
- package/lib/types/mastra/MastraSchemaConverter.d.mts +39 -0
- package/lib/types/mastra/MastraWorkflowCompiler.d.cts +218 -0
- package/lib/types/mastra/MastraWorkflowCompiler.d.mts +218 -0
- package/lib/types/mastra/MastraWorkflowManager.d.cts +220 -0
- package/lib/types/mastra/MastraWorkflowManager.d.mts +220 -0
- package/lib/types/mastra/index.d.cts +17 -0
- package/lib/types/mastra/index.d.mts +17 -0
- package/lib/types/mastra/types.d.cts +222 -0
- package/lib/types/mastra/types.d.mts +222 -0
- package/lib/types/nest/graph/GraphEngineCapabilityManifest.d.cts +87 -0
- package/lib/types/nest/graph/GraphEngineCapabilityManifest.d.mts +87 -0
- package/lib/types/nest/graph/GraphEngineCapabilityService.d.cts +98 -0
- package/lib/types/nest/graph/GraphEngineCapabilityService.d.mts +98 -0
- package/lib/types/nest/graph/GraphEngineController.d.cts +74 -0
- package/lib/types/nest/graph/GraphEngineController.d.mts +74 -0
- package/lib/types/nest/graph/GraphExecutionModule.d.cts +14 -1
- package/lib/types/nest/graph/GraphExecutionModule.d.mts +14 -1
- package/lib/types/nest/graph/GraphRunController.d.cts +69 -14
- package/lib/types/nest/graph/GraphRunController.d.mts +69 -14
- package/lib/types/nest/graph/GraphWorkflowController.d.cts +50 -17
- package/lib/types/nest/graph/GraphWorkflowController.d.mts +50 -17
- package/lib/types/nest/graph/index.d.cts +3 -0
- package/lib/types/nest/graph/index.d.mts +3 -0
- package/lib/types/nest/graph/main.d.cts +1 -0
- package/lib/types/nest/graph/main.d.mts +1 -0
- package/lib/types/nest/graph/servingDates.d.cts +35 -0
- package/lib/types/nest/graph/servingDates.d.mts +35 -0
- package/lib/types/nest/graph/servingErrors.d.cts +44 -0
- package/lib/types/nest/graph/servingErrors.d.mts +44 -0
- package/lib/types/node/flow/if/node.d.cts +20 -8
- package/lib/types/node/flow/if/node.d.mts +20 -8
- package/lib/types/node/flow/loop/until/node.d.cts +4 -1
- package/lib/types/node/flow/loop/until/node.d.mts +4 -1
- package/lib/types/node/flow/loop/while/node.d.cts +4 -1
- package/lib/types/node/flow/loop/while/node.d.mts +4 -1
- package/lib/types/node/utility/code/node.d.cts +1 -1
- package/lib/types/node/utility/code/node.d.mts +1 -1
- package/lib/types/ram/GraphRunStore.d.cts +12 -0
- package/lib/types/ram/GraphRunStore.d.mts +12 -0
- package/lib/types/shared/graph/GraphExecutionStateMapper.d.cts +5 -5
- package/lib/types/shared/graph/GraphExecutionStateMapper.d.mts +5 -5
- package/lib/types/shared/graph/constants.d.cts +8 -0
- package/lib/types/shared/graph/constants.d.mts +8 -0
- package/lib/types/shared/graph/document/GraphFlowBuilder.d.cts +5 -5
- package/lib/types/shared/graph/document/GraphFlowBuilder.d.mts +5 -5
- package/lib/types/shared/graph/index.d.cts +2 -1
- package/lib/types/shared/graph/index.d.mts +2 -1
- package/lib/types/shared/graph/layout/GraphWorkflowLayout.d.cts +49 -0
- package/lib/types/shared/graph/layout/GraphWorkflowLayout.d.mts +49 -0
- package/lib/types/shared/graph/layout/index.d.cts +5 -0
- package/lib/types/shared/graph/layout/index.d.mts +5 -0
- package/lib/types/shared/graph/layout/layout-options.d.cts +46 -0
- package/lib/types/shared/graph/layout/layout-options.d.mts +46 -0
- package/lib/types/shared/graph/types.d.cts +12 -4
- package/lib/types/shared/graph/types.d.mts +12 -4
- package/lib/types/shared/ui/index.d.cts +8 -10
- package/lib/types/shared/ui/index.d.mts +8 -10
- package/package.json +49 -6
- package/lib/cjs/shared/ui/GraphNodeView.cjs +0 -114
- package/lib/cjs/shared/ui/GraphNodeView.cjs.map +0 -1
- package/lib/cjs/shared/ui/GraphRunView.cjs +0 -96
- package/lib/cjs/shared/ui/GraphRunView.cjs.map +0 -1
- package/lib/cjs/shared/ui/GraphWorkflowView.cjs +0 -78
- package/lib/cjs/shared/ui/GraphWorkflowView.cjs.map +0 -1
- package/lib/cjs/shared/ui/types.cjs +0 -4
- package/lib/cjs/shared/ui/types.cjs.map +0 -1
- package/lib/esm/shared/ui/GraphNodeView.js +0 -107
- package/lib/esm/shared/ui/GraphNodeView.js.map +0 -1
- package/lib/esm/shared/ui/GraphRunView.js +0 -90
- package/lib/esm/shared/ui/GraphRunView.js.map +0 -1
- package/lib/esm/shared/ui/GraphWorkflowView.js +0 -72
- package/lib/esm/shared/ui/GraphWorkflowView.js.map +0 -1
- package/lib/esm/shared/ui/types.js +0 -2
- package/lib/esm/shared/ui/types.js.map +0 -1
- package/lib/types/shared/ui/GraphNodeView.d.cts +0 -48
- package/lib/types/shared/ui/GraphNodeView.d.mts +0 -48
- package/lib/types/shared/ui/GraphRunView.d.cts +0 -88
- package/lib/types/shared/ui/GraphRunView.d.mts +0 -88
- package/lib/types/shared/ui/GraphWorkflowView.d.cts +0 -18
- package/lib/types/shared/ui/GraphWorkflowView.d.mts +0 -18
- package/lib/types/shared/ui/types.d.cts +0 -200
- package/lib/types/shared/ui/types.d.mts +0 -200
package/dist/as-graph.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{logParameterRegistry as e,Logging as t,LoggedEnvironment as o}from"@decaf-ts/logging";import{RenderingEngine as n,uimodel as i,uielement as r,uilistprop as a,uilistmodel as s,hidden as d}from"@decaf-ts/ui-decorators";import{Metadata as l,Decoration as c,apply as u,metadata as p,propMetadata as h,description as f,prop as g,DefaultFlavour as m}from"@decaf-ts/decoration";import{ValidationKeys as y,Model as w,required as b,type as v,date as I,model as E,option as N,min as O,max as A}from"@decaf-ts/decorator-validation";import{ValidationError as x,InternalError as k,NotFoundError as _}from"@decaf-ts/db-decorators";import{__decorate as D,__metadata as P}from"tslib";import{pk as $,column as S,index as R,table as C,BaseModel as T,ForbiddenError as L,Context as j,AuthorizationError as M,service as G,Service as U,repository as F,Repository as B,ClientBasedService as q,Adapter as V,ModelService as W}from"@decaf-ts/core";import H from"isolated-vm";import*as K from"acorn";import*as z from"acorn-walk";import*as J from"typescript";import{createHash as X}from"node:crypto";var Y,Q;y.REQUIRED,y.MIN,y.MIN_LENGTH,y.MAX,y.MAX_LENGTH,y.PATTERN,y.URL,y.STEP,y.DATE,y.EMAIL,y.PASSWORD,y.EQUALS,y.DIFF,y.LESS_THAN,y.LESS_THAN_OR_EQUAL,y.GREATER_THAN,y.GREATER_THAN_OR_EQUAL,(e=>{e.GRAPH="graph",e.NODE="graph.node",e.EDGE="graph.edge",e.PORT="graph.port",e.STATE="graph.state"})(Y||(Y={})),(e=>{e.INPUT="input",e.OUTPUT="output",e.CONNECTION="connection"})(Q||(Q={}));const Z={};function ee(e,t={}){let o=e.width??96,n=e.height??96;for(const i of e.sizeRules??[]){if("parameterCount"!==i.type)continue;const e=t[i.parameter]??0;e>0&&("width"===i.dimension?o+=e*i.perItem:n+=e*i.perItem)}return{width:o,height:n}}function te(e,t){Z[e]=t}function oe(e,t,o){const n=t?Z[t]:void 0;return n?.color?n.color:e||"#64748b"}function ne(e,t,o){const n=t?Z[t]:void 0;return n?.icon?n.icon:e||"ti-pointer"}const ie=["skip","passThroughFirstInput","emitDefaults"];function re(e){return ie.includes(e)}var ae,se,de,le;(e=>{e.PENDING="pending",e.PLANNING="planning",e.RUNNING="running",e.SUCCEEDED="succeeded",e.FAILED="failed",e.SKIPPED="skipped",e.CANCELLED="cancelled",e.CACHED="cached"})(ae||(ae={})),(e=>{e.IDLE="idle",e.RUNNING="running",e.BLOCKED="blocked",e.SUCCEEDED="succeeded",e.FAILED="failed",e.SKIPPED="skipped"})(se||(se={})),(e=>{e.NODE_ID="nodeId",e.WORKFLOW_ID="workflowId",e.RUN_ID="runId",e.USER="user",e.ROLES="roles",e.NAMESPACES="namespaces",e.ORGANIZATION="organization",e.IP="ip"})(de||(de={})),(e=>{e.WORKFLOW_STARTED="workflow.started",e.WORKFLOW_PLANNED="workflow.planned",e.WORKFLOW_COMPLETED="workflow.completed",e.WORKFLOW_FAILED="workflow.failed",e.WORKFLOW_CANCELLED="workflow.cancelled",e.NODE_QUEUED="node.queued",e.NODE_STARTED="node.started",e.NODE_OUTPUT="node.output",e.NODE_COMPLETED="node.completed",e.NODE_FAILED="node.failed",e.NODE_SKIPPED="node.skipped",e.NODE_CACHE_HIT="node.cacheHit",e.NODE_PINNED="node.pinned",e.NODE_UNPINNED="node.unpinned",e.NODE_STATE_CHANGED="node.stateChanged",e.EDGE_VALUE_ROUTED="edge.valueRouted",e.EDGE_STATE_CHANGED="edge.stateChanged",e.GRAPH_RUN_LOG="graph.run.log",e.LOOP_STARTED="loop.started",e.LOOP_ITERATION_STARTED="loop.iteration.started",e.LOOP_ITERATION_COMPLETED="loop.iteration.completed",e.LOOP_CONDITION_EVALUATED="loop.condition.evaluated",e.LOOP_COMPLETED="loop.completed",e.LOOP_LIMIT_REACHED="loop.limitReached",e.VALIDATION_STARTED="validation.started",e.VALIDATION_FAILED="validation.failed",e.VALIDATION_COMPLETED="validation.completed",e.STORE_READ="store.read",e.STORE_WRITE="store.write",e.STORE_DELETE="store.delete"})(le||(le={}));const ce={maxRequestBytes:4e6,maxConcurrentRuns:32,maxEventsPerRun:1e4,maxEventPayloadBytes:256e3,executionTimeoutMs:6e5,eventReplayWindowMs:3e5},ue=[le.WORKFLOW_COMPLETED,le.WORKFLOW_FAILED,le.WORKFLOW_CANCELLED];function pe(e){return ue.includes(e)}function he(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}function fe(e){const t=l.constr(e);if("function"==typeof t)return t;const o=e.constructor;return"function"==typeof o?o:e}function ge(e){if(null!=e)return"string"==typeof e?e:e+""}function me(e,t,o){return ge(e?.props?.label??e?.props?.name)??ge(t?.name)??o??""}function ye(e,t,o){const n=ve(e,t);if(n?.model&&"function"==typeof n.model&&w.isModel(n.model))return n.model;const i=l.type(e,t);if("function"==typeof i&&w.isModel(i))return i;const r=l.getPropDesignTypes?.(e,t)?.designTypes||[];for(const e of r)if("function"==typeof e&&w.isModel(e))return e;const a=o?.[y.TYPE]?.customTypes||[];for(const e of a)if("function"==typeof e&&w.isModel(e))return e}function we(e,t){const o=[t,e.path??e.property].filter(Boolean).join(".");return{...e,path:o,children:e.children?.map(e=>we(e,o))}}function be(e){const t=fe(e);return l.get(t,Y.NODE)}function ve(e,t){const o=fe(e);return l.get(o,l.key(Y.PORT,t+""))}function Ie(e,t,o,n=new Set){const i=ve(e,t);if(!i?.schema)return;const r=ye(e,t,l.validationFor(e,t));if(!r)return;if(n.has(r))return[];const a=new Set(n);return a.add(e),a.add(r),Oe(r,a).filter(e=>e.direction===o)}function Ee(e,t,o=new Set){const n=ve(e,t);if(!n)return;const i=l.validationFor(e,t),r=ye(e,t,i);if(n.schema&&r)return;const a=w.uiElementOf(e,t)||void 0,s=w.uiDecorationOf(e,t,"uiprop"),d=l.type(e,t),c=ge(n.type??i?.[y.TYPE]?.customTypes?.[0]?.name??a?.props?.type??s?.type??d?.name),u=(n.expand||r&&!o.has(r))&&r?(()=>{const n=new Set(o);return n.add(e),n.add(r),Oe(r,n).map(e=>we(e,t))})():void 0;return{property:t,path:t,direction:n.direction,name:t,label:me(a,s,t),type:c?.toLowerCase(),required:!!i?.[y.REQUIRED],hidden:!!w.uiIsHidden(e,t),designType:d?.name,element:a,prop:s,validation:i,graph:n,connectionRules:n.connectionRules,composite:!!u?.length,children:u,model:r?.name}}function Ne(e){return Oe(fe(e))}function Oe(e,t=new Set){const o=l.properties(e)||[],n=[];for(const i of o){const o=i+"",r=ve(e,o);if(r?.schema){const i=Ie(e,o,r.direction,t);if(i){n.push(...i);continue}}const a=Ee(e,o,t);a&&n.push(a)}return n}function Ae(e){return e.flatMap(e=>e.children&&e.children.length?Ae(e.children):[e])}function xe(e){const t=fe(e),o=w.uiModelOf(t),n=be(t)||{},i=o?.tag||t.name,r=Ne(t),a=((e,t)=>{const o=t.portGroups||[],n=new Map(o.map(e=>[e.property,e])),i=[],r=l.properties(e)||[];for(const t of r){const o=t+"",r=ve(e,o);if(!r?.schema)continue;if(!ye(e,o,l.validationFor(e,o)))continue;const a=n.get(o);i.push(a?{...a,toggle:a.toggle??"all"}:{property:o,toggle:"all"})}for(const e of o)i.some(t=>t.property===e.property)||i.push(e);return i.length?i:void 0})(t,n),s=n.namespaces?.length?n.namespaces:(e=>{if(null==e)return[];let t,o=e;try{o=l.constr(e)}catch{o=e}try{t=l.get(o,"auth-namespace")}catch{t=void 0}return he(t)??[]})(t),d=s.length?s:void 0;return{name:t.name,tag:i,kind:n.kind||i,category:n.category,color:n.color,effectiveColor:oe(n.color,n.category),group:n.group,height:n.height,icon:n.icon,effectiveIcon:ne(n.icon,n.category),labels:n.labels||[],maxChildren:n.maxChildren,minWidth:n.minWidth,width:n.width,shape:n.shape,cornerRadius:n.cornerRadius,sizeRules:n.sizeRules,props:o?.props,ui:o,graph:n,ports:r,portGroups:a,namespaces:d}}const ke=new Set,_e=new Set;function De(e,t,o){return c.for(Y.NODE).define({decorator:(e,t,o)=>{const n={kind:t?.kind||e,...t};return t=>{const r=u(i(e,o),p(Y.NODE,n))(t);var a;return a=t,ke.add(a),r}},args:[e,t,o]}).apply()}function Pe(e,t){return c.for(Y.PORT).define({decorator:(e,t)=>(o,n)=>{const i={direction:e,...t};return u(h(l.key(Y.PORT,n),i))(o,n)},args:[e,t]}).apply()}function $e(e){return Pe(Q.INPUT,{...e,schema:!0})}function Se(e){return Pe(Q.OUTPUT,{...e,schema:!0})}function Re(e){return Pe(Q.CONNECTION,e)}n.prototype.renderAsNode=(e,t,...o)=>xe(e),l.nodes=(()=>[...ke]).bind(l),l.workflows=(()=>[..._e]).bind(l);const Ce=["__proto__","prototype","constructor"];function Te(e){return Ce.includes(e)}function Le(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function je(e){return null===e||"string"==typeof e||"number"==typeof e&&Number.isFinite(e)||"boolean"==typeof e}function Me(e){return!!je(e)||(Array.isArray(e)?e.every(e=>Me(e)):!!Le(e)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&!Te(t)&&Me(e[t])))}function Ge(e){if(void 0===e)return!1;if("number"==typeof e)return Number.isFinite(e);if("function"==typeof e)return!1;if(Me(e))return!0;if(Array.isArray(e))return e.every(e=>Ge(e));if(Le(e)){const t=Reflect.ownKeys(e);for(const o of t){if("string"!=typeof o)return!1;if(Te(o))return!1;if(!Ge(e[o]))return!1}return!0}return!1}function Ue(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>Ue(e));const t={};for(const[o,n]of Object.entries(e))t[o]=Ue(n);return t}const Fe={string:"string",char:"string",text:"string",textarea:"string",radio:"string",select:"string",number:"number",integer:"number",float:"number",double:"number",decimal:"number",boolean:"boolean",bool:"boolean",checkbox:"boolean",array:"array",list:"array",set:"array",object:"object",model:"model",any:"any",unknown:"any",enum:"enum"},Be={date:"date",datetime:"date-time","date-time":"date-time",duration:"duration"};function qe(e){return e?Fe[e.toLowerCase()]??"any":"any"}function Ve(e,t){const o=e[t];if(o&&"object"==typeof o)return o.value}function We(e,t){const o=Ve(e,t);return"number"==typeof o&&Number.isFinite(o)?o:void 0}function He(e,t,o){const n=e??{},i=(e=>{const t=Ve(e,y.ENUM);if(Array.isArray(t)&&t.every(je))return t})(n);if(i)return{type:"enum",values:i};const r=(e=>{const t=e[y.TYPE],o=t?.customTypes?.[0],n="function"==typeof o?o.name:o?.name;if(n)return n})(n)??o;return r?{type:"model",name:r}:((e,t)=>{switch(qe(e)){case"string":{const t=(e=>{if(e)return Be[e.toLowerCase()]})(e);return void 0!==t?{type:"string",format:t}:{type:"string"}}case"number":{const o={type:"number"};e&&"integer"===e.toLowerCase()&&(o.integer=!0);const n=We(t,y.MIN),i=We(t,y.MAX);return void 0!==n&&(o.min=n),void 0!==i&&(o.max=i),o}case"boolean":return{type:"boolean"};case"array":return((e,t)=>{const o={type:"array",items:Ke(e,t)},n=We(e,y.MIN),i=We(e,y.MAX);return void 0!==n&&(o.minItems=n),void 0!==i&&(o.maxItems=i),o})(t,e);case"object":return{type:"object",properties:{}};case"enum":return{type:"enum",values:[]};case"model":return{type:"model",name:e??"any"};default:return{type:"any"}}})(t,n)}function Ke(e,t){if((e=>{const t=e[y.LIST];return!!t?.clazz?.length})(e))return{type:"model",name:ze(e)};const o=Ve(e,y.TYPE);if("string"==typeof o){const e=qe(o);return"model"===e?{type:"model",name:o}:{type:e}}if(t&&"array"!==t){const e=qe(t);return"model"===e?{type:"model",name:t}:{type:e}}return{type:"any"}}function ze(e){const t=e[y.LIST],o=t?.clazz?.[0];if("function"!=typeof o)return"any";if(o.name)return o.name;try{const e=o();if("function"==typeof e&&e.name)return e.name}catch{return"any"}return"any"}function Je(e){return"workflow"===e.scope}function Xe(e){return"node"===e.scope}function Ye(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"workflow"===t.scope?"string"==typeof t.port&&2===Reflect.ownKeys(t).length:"node"===t.scope&&"string"==typeof t.nodeId&&"string"==typeof t.port&&3===Reflect.ownKeys(t).length}function Qe(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e.mode;if("edge"===t)return 1===Reflect.ownKeys(e).length;if("literal"===t){const t=e.value;return 2===Object.keys(e).length&&Me(t)}return"expression"===t&&2===Object.keys(e).length&&"string"==typeof e.expression}const Ze=["any","string","number","boolean","array","object","enum","model"];function et(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&(e=>Ze.includes(e))(e.type)}function tt(e,t={seen:[]}){if(t.seen.includes(e))throw new x(`Document '${(e=>{const t=e?.id;return"string"==typeof t?t:"<unnamed document>"})(e)}' contains a loop body that references itself (cyclic document)`);if("string"!=typeof e.id||!e.id)throw new x("Document 'id' is required and must be a non-empty string");if("string"!=typeof e.name||!e.name)throw new x("Document 'name' is required and must be a non-empty string");const o=new Set;for(const t of[...e.inputs,...e.outputs]){if("string"!=typeof t.id||!t.id)throw new x("Workflow port 'id' is required and must be a non-empty string");if(o.has(t.id))throw new x(`Workflow port '${t.id}' is declared more than once; workflow port ids must be unique`);if(void 0!==t.schema&&!et(t.schema))throw new x(`Workflow port '${t.id}' schema must be a valid GraphValueSchema`);o.add(t.id)}const n={seen:[...t.seen,e]},i=new Set;for(const t of e.nodes)ot(t,i);for(const t of e.nodes)t.loop&&nt(t,t.loop,n),t.errorBoundary&&it(t,t.errorBoundary,n);const r=new Set;for(const t of e.edges)at(t,r);for(const t of e.edges)st(t.source,0,o,i,`Edge '${t.id}' source`),st(t.target,0,o,i,`Edge '${t.id}' target`);if(void 0!==e.settings&&!Ge(e.settings))throw new x("Document settings must be JSON-safe (a map of JSON-safe values)");if(void 0!==e.metadata&&!Ge(e.metadata))throw new x("Document metadata must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed");if(void 0!==e.ui&&!Ge(e.ui))throw new x("Document ui must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed")}function ot(e,t){if("string"!=typeof e.id||!e.id)throw new x("Node 'id' is required and must be a non-empty string");if(t.has(e.id))throw new x(`Node id '${e.id}' is declared more than once; node ids must be unique`);if("string"!=typeof e.kind||!e.kind)throw new x(`Node '${e.id}' must declare a non-empty string 'kind'`);if(void 0===e.parameters||null===e.parameters)throw new x(`Node '${e.id}' parameters must be present (an empty object when there are none)`);if(t.add(e.id),e.inputBindings)for(const[t,o]of Object.entries(e.inputBindings)){if(Te(t))throw new x(`Node '${e.id}' input binding key '${t}' is not allowed (unsafe prototype-pollutant key)`);if(!Qe(o))throw new x(`Node '${e.id}' input binding for '${t}' must be a valid GraphInputBinding (edge, literal, or expression)`);if("literal"===o.mode&&!Ge(o.value))throw new x(`Node '${e.id}' literal binding for '${t}' must contain JSON-safe values`);if("expression"===o.mode&&!o.expression)throw new x(`Node '${e.id}' expression binding for '${t}' must contain a non-empty expression`)}if(e.outputBindings)for(const[t,o]of Object.entries(e.outputBindings)){if(Te(t))throw new x(`Node '${e.id}' output binding key '${t}' is not allowed (unsafe prototype-pollutant key)`);if(!o||"object"!=typeof o||Array.isArray(o))throw new x(`Node '${e.id}' output binding for '${t}' must be an object with enabled and alias settings`)}if(!Ge(e.parameters))throw new x(`Node '${e.id}' parameters must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed`);if(void 0!==e.state){if(!e.state||"object"!=typeof e.state||Array.isArray(e.state))throw new x(`Node '${e.id}' state must be an object when present`);if(!Ge(e.state))throw new x(`Node '${e.id}' state must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed`)}}function nt(e,t,o){if(!t.body||"object"!=typeof t.body)throw new x(`Node '${e.id}' loop configuration requires a body document`);if(tt(t.body,o),!(void 0===t.maxIterations||Number.isFinite(t.maxIterations)&&t.maxIterations>0))throw new x(`Node '${e.id}' loop maxIterations must be a positive number`);if(void 0!==t.timeoutMs&&("number"!=typeof t.timeoutMs||0>=t.timeoutMs))throw new x(`Node '${e.id}' loop timeoutMs must be a positive number in milliseconds`);if(void 0!==t.concurrency&&("number"!=typeof t.concurrency||0>=t.concurrency))throw new x(`Node '${e.id}' loop concurrency must be a positive number`);for(const o of[t.inputMappings,t.outputMappings])if(o)for(const[t,n]of Object.entries(o)){if(Te(t))throw new x(`Node '${e.id}' loop mapping key '${t}' is not allowed (unsafe prototype-pollutant key)`);rt(n,e.id,t)}}function it(e,t,o){if(!t.try||"object"!=typeof t.try)throw new x(`Node '${e.id}' error-boundary configuration requires a try body document`);tt(t.try,o);for(const[n,i]of[["catch",t.catch],["finally",t.finally]])if(void 0!==i){if(!i||"object"!=typeof i)throw new x(`Node '${e.id}' error-boundary ${n} body must be a document`);tt(i,o)}}function rt(e,t,o){if(!e||"object"!=typeof e)throw new x(`Node '${t}' loop mapping '${o}' must reference a workflow port, node port, literal, or expression`);switch(e.source){case"workflow":if("string"!=typeof e.port||!e.port)throw new x(`Node '${t}' loop mapping '${o}' referencing a workflow must reference a port identifier`);break;case"node":if("string"!=typeof e.nodeId||!e.nodeId||"string"!=typeof e.port||!e.port)throw new x(`Node '${t}' loop mapping '${o}' referencing a node must reference a node id and a port`);break;case"literal":if(!Ge(e.value))throw new x(`Node '${t}' loop mapping '${o}' literal references must be JSON-safe values`);break;case"expression":if("string"!=typeof e.expression||!e.expression)throw new x(`Node '${t}' loop mapping '${o}' expression references must be non-empty expressions`);break;default:throw new x(`Node '${t}' loop mapping '${o}' must use a workflow, node, literal, or expression reference source`)}}function at(e,t){if("string"!=typeof e.id||!e.id)throw new x("Edge 'id' is required and must be a non-empty string");if(t.has(e.id))throw new x(`Edge id '${e.id}' is declared more than once; edge ids must be unique`);if(!Ye(e.source))throw new x(`Edge '${e.id}' source endpoint is not a valid GraphEndpoint`);if(!Ye(e.target))throw new x(`Edge '${e.id}' target endpoint is not a valid GraphEndpoint`);if("data"!==e.type&&"connection"!==e.type)throw new x(`Edge '${e.id}' type '${e.type+""}' is not a valid edge type (data or connection are allowed)`);if(t.add(e.id),!Ge(e))throw new x(`Edge '${e.id}' contains values that are not JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed`)}function st(e,t,o,n,i){if(Je(e)){if(!o.has(e.port))throw new x(`${i} references workflow port '${e.port}' which is not declared on the document`)}else if(Xe(e)){if(!n.has(e.nodeId))throw new x(`${i} references node '${e.nodeId}' which is not part of the document`);if("string"!=typeof e.port||!e.port)throw new x(i+" node endpoints must reference a non-empty port identifier")}}const dt=["expression","template"],lt=["javascript","typescript","json","text"];function ct(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return!(!(e=>dt.includes(e))(t.mode)||"string"!=typeof t.expression||!t.expression||void 0!==t.language&&!(e=>lt.includes(e))(t.language)||void 0!==t.metadata&&!Me(t.metadata))}function ut(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.name&&Array.isArray(t.inputs)&&Array.isArray(t.outputs)&&Array.isArray(t.nodes)&&Array.isArray(t.edges)}function pt(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.type&&(void 0===t.required||"boolean"==typeof t.required)&&(void 0===t.displayName||"string"==typeof t.displayName)&&(void 0===t.allowedOperations||Array.isArray(t.allowedOperations)&&t.allowedOperations.every(e=>"string"==typeof e))}const ht=["trigger","loop","branching","stateful","retryable","cancellable","parallel","resource"];function ft(e){return ht.includes(e)}function gt(e){if(!(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.kind&&"object"==typeof t.display&&Array.isArray(t.inputs)&&Array.isArray(t.outputs)&&Array.isArray(t.parameters)})(e))throw new x("Graph node manifest does not conform to the required shape");if(!Ge(e))throw new x("Graph node manifest contains values that are not JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys or unsafe prototype keys are not allowed on manifests")}const mt=["loadOptions","listSearch","resourceLocator","resourceMapping","validateParameter","action"];function yt(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.name&&(e=>mt.includes(e))(t.type)&&(void 0===t.parameter||"string"==typeof t.parameter)&&(void 0===t.dependencies||Array.isArray(t.dependencies)&&t.dependencies.every(e=>"string"==typeof e))}function wt(e){const t=e.element?.props?.value,o=t??e.prop?.value??e.validation?.defaultValue;if(void 0!==o&&"function"!=typeof o&&Ge(o))try{return JSON.parse(JSON.stringify(o))}catch{return}}function bt(e){if(e.type&&e.type in Be)return{type:"string",format:Be[e.type]};const t=(e=>{for(const t of[e.graph?.type,e.element?.props?.type,e.prop?.type])if("string"==typeof t&&"any"!==qe(t))return t})(e);return t?He((e=>{if(!e)return;const t=Object.entries(e).filter(([e])=>e!==y.TYPE);return Object.fromEntries(t)})(e.validation),t):He(e.validation,e.type,e.model)}function vt(e){const t={};for(const[o,n]of Object.entries(e.graph?.metadata??{}))Ge(n)&&(t[o]=JSON.parse(JSON.stringify(n)));return Object.keys(t).length?t:void 0}function It(e){switch(e){case"output":return"output";case"connection":return"connection";default:return"input"}}function Et(e){const t=e.graph?.handle;return"connection"!==e.direction&&"string"==typeof t&&t?t:e.path??e.property}function Nt(e,t){const o={id:Et(e),label:e.label,direction:It(e.direction),schema:bt(e)};e.required&&(o.required=!0),e.hidden&&(o.hidden=!0);const n=e.graph?.category;"string"==typeof n&&(o.category=n),!0===e.graph?.userControlled&&(o.configurable=!0);const i=e.graph?.handle;"string"==typeof i&&(o.handle=i);const r=Rt(e.graph?.connectionRules)??t;r&&(o.connectionPolicy=r);const a=(e=>{const t=e.element;if(!t||!Ge(t))return;const o=t.tag;if("string"!=typeof o)return;const n=t.props;return{tag:o,serialize:!0===t.serialize,props:n&&"object"==typeof n&&!Array.isArray(n)?Ue(n):{}}})(e);a&&(o.element=a);const s=vt(e);return s&&(o.metadata=s),o}function Ot(e){const t={type:"string",id:Et(e),label:e.label,required:e.required};if(e.hidden)return((e,t)=>{const o={...t,type:"hidden"},n=wt(e);return void 0!==n&&(o.defaultValue=n),At(o)})(e,t);const o=wt(e);void 0!==o&&(t.defaultValue=o);const n=(e=>{const t=e.element?.props?.placeholder??e.prop?.placeholder;return"string"==typeof t?t:void 0})(e);n&&(t.placeholder=n);const i=vt(e);if(i&&(t.metadata=i),(e=>{const t=_t(e);return"code"===t||"code-editor"===t})(e))return At({...t,type:"code",language:$t(e)});const r=bt(e);switch(r.type){case"number":{const o={...t,type:"number",integer:r.integer,min:r.min,max:r.max},n=kt(e.validation?.step);return void 0!==n&&(o.step=n),At(o)}case"boolean":return At({...t,type:"boolean"});case"enum":return At({...t,type:"options",options:r.values.map(e=>({value:e,label:e+""}))});case"array":{const e={...t,type:"collection"};return void 0!==r.maxItems&&(e.maxItems=r.maxItems),At(e)}case"object":case"model":return At({...t,type:"object"});default:return At({...t,type:"string",multiline:!!Dt(e)||void 0,pattern:xt(e.validation?.pattern),minLength:kt(e.validation?.minlength),maxLength:kt(e.validation?.maxlength)})}}function At(e){const t=e;for(const e of Object.keys(t))void 0===t[e]&&delete t[e];return e}function xt(e){const t=e?.value;return"string"==typeof t?t:void 0}function kt(e){const t=e?.value;return"number"==typeof t&&Number.isFinite(t)?t:void 0}function _t(e){const t=e.element?.tag;return"string"==typeof t&&t?t:void 0}function Dt(e){return"textarea"===_t(e)||"textarea"===(e=>{const t=e.element?.props?.type;return"string"==typeof t?t:void 0})(e)}const Pt=["javascript","typescript","json","text"];function $t(e){const t=e.element?.props?.language;return"string"==typeof t&&Pt.includes(t)?t:"javascript"}function St(e,t){const o={name:t.name??e.name},n=e.graph?.metadata?.description??void 0;"string"==typeof n&&n&&(o.description=n);const i=t.category??e.category;"string"==typeof i&&i&&(o.category=i),"string"==typeof e.group&&e.group&&(o.group=e.group),Array.isArray(e.labels)&&(o.labels=e.labels.slice());const r=((e,t)=>{if(t.icon)return t.icon;const o=e.effectiveIcon??e.icon;return"string"==typeof o?{type:"catalogue",name:o}:{type:"catalogue",name:"ph:circuitry"}})(e,t);return r&&(o.icon=r),"string"==typeof e.color&&e.color&&(o.color=e.color),"number"==typeof e.width&&Number.isFinite(e.width)&&(o.width=e.width),"number"==typeof e.minWidth&&Number.isFinite(e.minWidth)&&(o.minWidth=e.minWidth),"number"==typeof e.height&&Number.isFinite(e.height)&&(o.height=e.height),"string"==typeof e.shape&&(o.shape=e.shape),"number"==typeof e.cornerRadius&&Number.isFinite(e.cornerRadius)&&(o.cornerRadius=e.cornerRadius),Array.isArray(e.sizeRules)&&(o.sizeRules=e.sizeRules),o}function Rt(e){if(!e)return;const t=e,o={};"boolean"==typeof t.allowSelf&&(o.allowSelf=t.allowSelf),"boolean"==typeof t.allowMultiple&&(o.allowMultiple=t.allowMultiple);const n=t.allowedKinds;Array.isArray(n)&&n.every(e=>"string"==typeof e)&&(o.allowedNodeKinds=n);const i=t.blockedKinds;Array.isArray(i)&&i.every(e=>"string"==typeof e)&&(o.blockedNodeKinds=i);const r=t.maxConnections;return"number"==typeof r&&Number.isFinite(r)&&(o.maxConnections=r),Object.keys(o).length?o:void 0}function Ct(e,t={}){const o="function"==typeof e?e:e.constructor;if(!be(o))throw new x(`Node '${o?.name??e+""}' is not decorated with @node and cannot produce a manifest`);const n=xe(o),i=Ae(Ne(o)),r=[],a=[],s=[],d=[],l=Rt(n.graph?.connectionRules);for(const e of i)("connection"===e.direction?s:"output"===e.direction?a:r).push(Nt(e,l)),"input"===e.direction&&d.push(Ot(e));const c={kind:t.kind??n.kind??n.name,display:St(n,t),inputs:r,outputs:a,parameters:d};return s.length&&(c.connections=s),n.namespaces?.length&&(c.namespaces=n.namespaces.slice()),gt(c),c}let Tt=class extends T{constructor(e){super(e)}};D([$({type:String,generated:!1}),f("Unique graph run id"),r("ngx-decaf-crud-field",{label:"graph.run.id.label",readonly:!0}),P("design:type",String)],Tt.prototype,"runId",void 0),D([S(),b(),R(),f("Workflow document id the run executes"),a("workflowId"),r("ngx-decaf-crud-field",{label:"graph.run.workflowId.label"}),P("design:type",String)],Tt.prototype,"workflowId",void 0),D([S(),f("Owning user; absent for anonymous callers"),r("ngx-decaf-crud-field",{label:"graph.run.owner.label"}),P("design:type",String)],Tt.prototype,"owner",void 0),D([S(),b(),v(String),R(),f("Current run lifecycle status"),a("status"),r("ngx-decaf-crud-field",{label:"graph.run.status.label",readonly:!0}),P("design:type",String)],Tt.prototype,"status",void 0),D([S(),f("Fingerprint of the executed document"),r("ngx-decaf-crud-field",{label:"graph.run.fingerprint.label",readonly:!0}),P("design:type",String)],Tt.prototype,"documentFingerprint",void 0),D([S(),g(),f("Workflow input values keyed by input port id"),P("design:type",Object)],Tt.prototype,"inputs",void 0),D([S(),g(),f("Execution result, present on successful completion"),P("design:type",Object)],Tt.prototype,"result",void 0),D([S(),g(),f("Structured error payload, present on failure"),P("design:type",Object)],Tt.prototype,"error",void 0),D([I(),S(),f("Run creation timestamp"),P("design:type",Date)],Tt.prototype,"createdAt",void 0),D([I(),S(),f("Execution start timestamp, once it has started"),P("design:type",Date)],Tt.prototype,"startedAt",void 0),D([I(),S(),f("Terminal-state timestamp, once the run has finished"),P("design:type",Date)],Tt.prototype,"finishedAt",void 0),Tt=D([s("ngx-decaf-list-item",{icon:"ti-player-play"}),i("ngx-decaf-crud-form"),f("Persistable graph run lifecycle record"),C("graph_run"),E(),P("design:paramtypes",[Object])],Tt);let Lt=class extends T{constructor(e){super(e)}};D([$({type:String,generated:!1}),P("design:type",String)],Lt.prototype,"workflowId",void 0),D([S(),P("design:type",String)],Lt.prototype,"name",void 0),D([S(),P("design:type",Object)],Lt.prototype,"document",void 0),D([S(),P("design:type",String)],Lt.prototype,"owner",void 0),D([S(),P("design:type",Object)],Lt.prototype,"snapshot",void 0),Lt=D([C("graph_workflow"),E(),P("design:paramtypes",[Object])],Lt),te("Trigger",{color:"#3b82f6",icon:"ti-bolt"}),te("Flow Control",{color:"#f59e0b",icon:"ti-arrows-split-2"}),te("Utility",{color:"#0d9488",icon:"ti-tool"}),te("Loop",{color:"#eab308",icon:"ti-repeat"}),te("Workflow",{color:"#f97316",icon:"ti-sitemap"}),te("Pipeline",{color:"#0ea5e9",icon:"ti-git-merge"}),te("Node",{color:"#8b5cf6",icon:"ti-point-filled"}),te("Agent",{color:"#7c3aed",icon:"ti-robot"}),te("model",{color:"#3b82f6",icon:"ti-cpu"}),te("memory",{color:"#10b981",icon:"ti-database"}),te("workspace",{color:"#f59e0b",icon:"ti-folder"});const jt=new Set;function Mt(e,t){return e.config[t]}function Gt(e){return Array.isArray(e)?e.map(e=>e+"").join(", "):e+""}(()=>{const t=[{key:de.NODE_ID,shouldInclude:e=>null!=Mt(e,de.NODE_ID),render:e=>Mt(e,de.NODE_ID)+""},{key:de.WORKFLOW_ID,shouldInclude:e=>null!=Mt(e,de.WORKFLOW_ID),render:e=>Mt(e,de.WORKFLOW_ID)+""},{key:de.RUN_ID,shouldInclude:e=>null!=Mt(e,de.RUN_ID),render:e=>Mt(e,de.RUN_ID)+""},{key:de.USER,shouldInclude:e=>null!=Mt(e,de.USER),render:e=>Mt(e,de.USER)+""},{key:de.ROLES,shouldInclude(e){const t=Mt(e,de.ROLES);return Array.isArray(t)&&t.length>0},render:e=>Gt(Mt(e,de.ROLES))},{key:de.NAMESPACES,shouldInclude(e){const t=Mt(e,de.NAMESPACES);return Array.isArray(t)&&t.length>0},render:e=>Gt(Mt(e,de.NAMESPACES))},{key:de.ORGANIZATION,shouldInclude:e=>null!=Mt(e,de.ORGANIZATION),render:e=>Mt(e,de.ORGANIZATION)+""},{key:de.IP,shouldInclude:e=>null!=Mt(e,de.IP),render:e=>Mt(e,de.IP)+""}];for(const o of t)jt.has(o.key)||(e.register(o),jt.add(o.key))})();const Ut="$workflow",Ft=4,Bt=100,qt=1e3,Vt=1e3,Wt=1e4,Ht=3e4,Kt="graph.pinnable";var zt,Jt;(e=>{e.MANUAL="manual",e.AUTOMATIC="automatic",e.DISABLED="disabled"})(zt||(zt={})),(e=>{e.TRUTHY="truthy",e.FALSY="falsy",e.EQUALS="equals",e.NOT_EQUALS="notEquals",e.GREATER_THAN="greaterThan",e.GREATER_THAN_OR_EQUAL="greaterThanOrEqual",e.LESS_THAN="lessThan",e.LESS_THAN_OR_EQUAL="lessThanOrEqual",e.EXISTS="exists",e.CUSTOM="custom"})(Jt||(Jt={}));const Xt={FOREACH:"core.loop.foreach",WHILE:"core.loop.while",UNTIL:"core.loop.until"};class Yt extends k{constructor(e,t="GRAPH_EXECUTION_ERROR",o){super(e,Yt.name,500),this.graphCode=t,this.details=o,this.name=this.constructor.name}}class Qt extends Yt{constructor(e){super("Graph workflow contains an unsupported cycle","GRAPH_CYCLE_ERROR",e)}}class Zt extends Yt{constructor(e,t){super(e,"GRAPH_INPUT_ERROR",t)}}class eo extends Yt{constructor(e,t){super(e,"GRAPH_LOOP_LIMIT_ERROR",t)}}class to extends Yt{constructor(e,t){super(e,"GRAPH_PINNING_ERROR",t)}}class oo extends Yt{constructor(e,t){super(e,"GRAPH_PORT_ERROR",t)}}class no extends Yt{constructor(e,t){super(e,"GRAPH_STORE_ERROR",t)}}class io extends Yt{constructor(e,t){super(e,"GRAPH_TOPOLOGY_ERROR",t)}}class ro extends Yt{constructor(e){super("Break signal","GRAPH_BREAK_SIGNAL",{value:e}),this.isBreakSignal=!0,this.name="GraphBreakSignal"}}class ao extends Yt{constructor(e){super(`Graph run '${e}' was cancelled`,"GRAPH_RUN_CANCELLED",{runId:e}),this.name=ao.name}}class so extends x{constructor(e){super(`Graph workflow document rejected with ${e.length} issue(s): ${e.map(e=>`${e.code} at ${e.path} (${e.message})`).join("; ")}`),this.name=so.name,this.issues=e}}class lo{constructor(){this.observers=new Set}observe(e){return this.observers.add(e),()=>this.unObserve(e)}unObserve(e){this.observers.delete(e)}async updateObservers(e){await Promise.all(Array.from(this.observers).map(async t=>{try{await Promise.resolve(t.refresh(e))}catch{}}))}}class co{constructor(){this.sequence=0}create(e){return{...e,id:this.createEventId(),sequence:++this.sequence,timestamp:new Date}}createEventId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new Yt("Cannot generate a graph event id: crypto.randomUUID is unavailable in this runtime","GRAPH_EVENT_ID_ERROR",{runtime:typeof globalThis.crypto});return e.randomUUID()}}function uo(e){if("string"!=typeof e)return;const t=e.trim();if(!t)return;const o=t.split(".");if(3!==o.length)return;const n=o[0].trim(),i=o[2].trim(),r=o[1].split(",").map(e=>e.trim()).filter(e=>e.length>0);return n&&i&&0!==r.length?{organization:n,departments:r,role:i}:void 0}function po(e){return`${e.organization}.${e.departments.join(",")}.${e.role}`}function ho(e){if(!e||"string"!=typeof e.namespace||!e.parts)return!1;const t=uo(e.namespace);return!!t&&po(t)===po(e.parts)}function fo(e,t){const o="string"==typeof e?e.trim():"";if(o){if(t)for(const e of t)if(e&&e.namespace===o&&ho(e))return e.parts;return uo(o)}}function go(e,t,o={},n){const i=fo(e,n),r=fo(t,n);return!(!i||!r)&&i.organization===r.organization&&i.role===r.role&&("exact"===(o.mode??"inherit")?i.departments.length===r.departments.length&&i.departments.every((e,t)=>e===r.departments[t]):i.departments.length<=r.departments.length&&i.departments.every((e,t)=>e===r.departments[t]))}function mo(e,t,o={},n){return e.filter(e=>!t.some(t=>go(t,e,o,n)))}function yo(e){return e.filter(e=>void 0===uo(e))}function wo(e,t){const o=new Set;for(const n of e){const e=fo(n,t);e&&o.add(e.role)}return[...o]}function bo(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}function vo(e,t){try{const o=e.cache;if(o&&void 0!==o[t]&&null!==o[t])return o[t]}catch{}try{return e.get(t)}catch{return}}function Io(e){if(!e)return{};const t={},o=e.user;"string"==typeof o&&o&&(t.user=o);const n=e.organization;"string"==typeof n&&n&&(t.organization=n);const i=e.ip;"string"==typeof i&&i&&(t.ip=i);const r=bo(e.roles);r&&(t.roles=r);const a=bo(e.namespaces);return a&&(t.namespaces=a,t.namespaceCache=No(a)),t}function Eo(e){return e?Io({user:vo(e,"user"),organization:vo(e,"organization"),ip:vo(e,"ip"),roles:vo(e,"roles"),namespaces:vo(e,"namespaces")}):{}}function No(e){const t=[];for(const o of e){const e=uo(o);e&&t.push({namespace:o,parts:e})}return t}function Oo(...e){const t={};for(const o of e)o&&(void 0!==o.user&&(t.user=o.user),void 0!==o.organization&&(t.organization=o.organization),void 0!==o.ip&&(t.ip=o.ip),void 0!==o.roles&&(t.roles=o.roles),void 0!==o.namespaces&&(t.namespaces=o.namespaces),void 0!==o.namespaces?t.namespaceCache=o.namespaceCache??No(o.namespaces):void 0!==o.namespaceCache&&(t.namespaceCache=o.namespaceCache));return t}class Ao{constructor(e={}){this.options=e}get enabled(){return!0===this.options.enabled}validate(e,o,n,i){if(!this.enabled)return;const r=i??this.options.logger??t.for("GraphAuth"),a=e.id||e.name||o.workflowId,s=(e=>{if(!e||"object"!=typeof e)return;const t=e.auth;return t&&"object"==typeof t&&!Array.isArray(t)?(e=>{if(!e)return;const t=he(e.namespaces),o=he(e.roles);if(!t&&!o)return;const n={};return t&&(n.namespaces=t),o&&(n.roles=o),n})(t):void 0})(e.metadata);this.assertGranted(`workflow '${a}'`,s?.namespaces??[],n,s?.roles??[],r);for(const e of o.nodes)this.assertGranted(`node '${e.id}'`,e.manifest.namespaces??[],n,[],r)}assertGranted(e,t,o,n,i){const r=o.namespaces??[],a=mo(t,r,this.options.match,o.namespaceCache),s=wo(r,o.namespaceCache),d=n.filter(e=>!s.includes(e));if(0===a.length&&0===d.length)return;const l=[...new Set([...yo(t),...yo(r)])],c=[];throw a.length&&c.push("namespace(s) "+a.join(", ")),d.length&&c.push("role(s) "+d.join(", ")),i.warn(`Graph access denied for ${e} for user ${o.user??"anonymous"}: missing ${c.join(" and ")}${l.length?`; malformed namespace(s) ${l.join(", ")} failed closed`:""}`),new L(`Access to ${e} requires ${c.join(" and ")}`)}}class xo{constructor(e){this.baseOptions=e,this.inner=t.for("GraphRun").for(this.attributeConfig(e))}attributeConfig(e){return{[de.NODE_ID]:e.nodeId,[de.WORKFLOW_ID]:e.workflowId,[de.RUN_ID]:e.runId,[de.USER]:e.user??null,[de.ROLES]:e.roles,[de.NAMESPACES]:e.namespaces,[de.ORGANIZATION]:e.organization,[de.IP]:e.ip}}emit(e,t,o){const n="string"==typeof t?t:t instanceof Error?t.message:t+"",i={level:e,message:n,timestamp:(new Date).toISOString(),runId:this.baseOptions.runId,workflowId:this.baseOptions.workflowId,nodeId:this.baseOptions.nodeId,user:this.baseOptions.user??null};void 0!==this.baseOptions.roles&&(i.roles=this.baseOptions.roles),void 0!==this.baseOptions.namespaces&&(i.namespaces=this.baseOptions.namespaces),void 0!==this.baseOptions.organization&&(i.organization=this.baseOptions.organization),void 0!==this.baseOptions.ip&&(i.ip=this.baseOptions.ip),void 0!==o&&(i.payload=o),this.baseOptions.forward({type:le.GRAPH_RUN_LOG,payload:i}).catch(()=>{}),{benchmark:(e,t)=>this.inner.benchmark(e,t),fatal:(e,t)=>this.inner.fatal(e,t),critical:(e,t)=>this.inner.critical(e,t),silly:(e,t)=>this.inner.silly(e,t),trace:(e,t)=>this.inner.trace(e,t),verbose:(e,t)=>this.inner.verbose(e,t),info:(e,t)=>this.inner.info(e,t),warn:(e,t)=>this.inner.warn(e,t),error:(e,t)=>this.inner.error(e,t),debug:(e,t)=>this.inner.debug(e,t)}[e](n,o)}benchmark(e,t){this.emit("benchmark",e,t)}fatal(e,t,o){this.emit("fatal",e,t??o)}critical(e,t,o){this.emit("critical",e,t??o)}silly(e,t,o){this.emit("silly",e,"object"==typeof t?t:o)}trace(e,t){this.emit("trace",e,t)}verbose(e,t,o){this.emit("verbose",e,"object"==typeof t?t:o)}info(e,t){this.emit("info",e,t)}error(e,t,o){this.emit("error",e,t??o)}warn(e,t){this.emit("warn",e,t)}debug(e,t){this.emit("debug",e,t)}action(e,t,o){this.inner.action(e,t,o)}setConfig(){}for(e,t,...o){return this}clear(){return this}get root(){return this.inner.root}}function ko(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}class _o extends j{constructor(e,t,o,n,i,r,a,s,d={},l,c,u){super(),this.runId=e,this.parentRunId=t,this.workflowId=o,this.document=n,this.node=i,this.manifest=r,this.path=a,this.emitFn=s,this.metadata=d,this.engine=l,this.abortSignal=c,this.limits=u;const p=Io(d);this.accumulate({...p,operation:"execute"});const h="string"==typeof d?.user?d.user:null;this.runLogger=new xo({runId:e,workflowId:o,nodeId:i.id,user:h,roles:ko(d?.roles),namespaces:ko(d?.namespaces),organization:"string"==typeof d?.organization?d.organization:void 0,ip:"string"==typeof d?.ip?d.ip:void 0,forward:async e=>{await this.emit(e)}})}get logger(){return this.runLogger}get auth(){return Eo(this)}async emit(e){await this.emitFn({...e,runId:this.runId,parentRunId:this.parentRunId,workflowId:this.workflowId,nodeId:this.node.id,path:e.path??this.path})}async progress(e){await this.emit({type:le.NODE_OUTPUT,payload:e})}async log(e,t){await this.emit({type:le.NODE_OUTPUT,payload:{message:e,payload:t}})}}class Do{constructor(e,t,o,n){this.nodeResults=new Map,this.events=[],this.activeDataEdges=new Set,this.runId=e,this.plan=t,this.valueStore=o,this.eventFactory=n,this.startedAt=new Date}recordNodeResult(e){this.nodeResults.set(e.nodeId,e)}activateDataEdge(e){this.activeDataEdges.add(e)}isDataEdgeActive(e){return this.activeDataEdges.has(e)}appendEvent(e){this.events.push(e)}finish(){this.finishedAt=new Date}}function Po(e,t,o,n,i){const r=e.valueStore.getWorkflowValues(),a={};for(const[t,o]of e.nodeResults)a[t]=o;const s=[...e.events];return{runId:e.runId,workflowId:t.id||t.name,status:n,document:t,inputs:{...o},outputs:r,nodeResults:a,events:s,startedAt:e.startedAt,finishedAt:e.finishedAt,metadata:i}}class $o{constructor(e){this.catalogue=e}async resolveNodes(e,t,o,...n){const i=new Map;for(const[r,a]of e.entries()){const e=`nodes[${r}]`;if(this.catalogue.has(a.kind,...n))try{const e=await this.catalogue.resolveManifest(a.kind,a,o,...n),t=this.catalogue.getExecutor(a.kind,...n);i.set(a.id,{instance:a,manifest:e,executor:t})}catch(o){t.push({code:"kind.resolution-failed",path:e+".kind",message:`Node '${a.id}' kind '${a.kind}' failed to resolve: ${o.message}`,nodeId:a.id,details:{kind:a.kind}})}else t.push({code:"kind.unknown",path:e+".kind",message:`Node '${a.id}' references kind '${a.kind}' which is not registered in the backend catalogue`,nodeId:a.id,details:{kind:a.kind}})}return i}validateEffectivePorts(e,t,o,n){const i=!0===t.policies?.allowUndeclaredParameters,r=new Set(t.inputs.map(e=>e.id)),a=new Set(t.outputs.map(e=>e.id));for(const a of Object.keys(e.inputBindings??{}))i||r.has(a)||o.push({code:"binding.unknown-port",path:`${n}.inputBindings.${a}`,message:`Node '${e.id}' input binding '${a}' does not refer to an effective input port of kind '${t.kind}'`,nodeId:e.id,details:{effectiveInputs:[...r]}});for(const r of Object.keys(e.outputBindings??{}))i||a.has(r)||o.push({code:"binding.unknown-port",path:`${n}.outputBindings.${r}`,message:`Node '${e.id}' output binding '${r}' does not refer to an effective output port of kind '${t.kind}'`,nodeId:e.id,details:{effectiveOutputs:[...a]}})}}function So(e,t,o="$"){const n=new Set;for(const t of e.edges)"node"===t.source.scope&&n.add(t.source.nodeId),"node"===t.target.scope&&n.add(t.target.nodeId);for(const i of e.nodes){n.has(i.id)||t.push({code:"topology.loose-node",path:`${o}.nodes[${i.id}]`,message:`Node '${i.id}' is connected to nothing; every node must participate in at least one edge`,nodeId:i.id});const e=i.loop?.body;e&&So(e,t,`${o}.nodes[${i.id}].loop.body`)}}function Ro(e,t){if(!t)return{valid:!0};switch(t.type){case"any":default:return{valid:!0};case"string":return"string"!=typeof e?Co("string"):{valid:!0};case"number":return"number"==typeof e&&Number.isFinite(e)?t.integer&&!Number.isInteger(e)?{valid:!1,message:"expected an integer number"}:void 0!==t.min&&e<t.min?{valid:!1,message:"expected a number >= "+t.min}:void 0!==t.max&&e>t.max?{valid:!1,message:"expected a number <= "+t.max}:{valid:!0}:Co("number");case"boolean":return"boolean"!=typeof e?Co("boolean"):{valid:!0};case"array":if(!Array.isArray(e))return Co("array");if(void 0!==t.minItems&&e.length<t.minItems)return{valid:!1,message:`expected at least ${t.minItems} items`};if(void 0!==t.maxItems&&e.length>t.maxItems)return{valid:!1,message:`expected at most ${t.maxItems} items`};for(const o of e){const e=Ro(o,t.items);if(!e.valid)return e}return{valid:!0};case"object":case"model":{if(null===e||"object"!=typeof e||Array.isArray(e))return Co(t.type);const o=t,n=o.properties;if(!n)return{valid:!0};for(const[t,o]of Object.entries(n))if(t in e){const n=Ro(e[t],o);if(!n.valid)return{valid:!1,message:`property '${t}': ${n.message}`}}if(o.required)for(const t of o.required)if(!(t in e))return{valid:!1,message:`missing required property '${t}'`};if(!1===o.additionalProperties)for(const t of Object.keys(e))if(!(t in n))return{valid:!1,message:`unexpected property '${t}'`};return{valid:!0}}case"enum":return t.values.some(t=>t===e)?{valid:!0}:{valid:!1,message:"value is not one of the enum values"}}}function Co(e){return{valid:!1,message:`expected a ${e} value`}}function To(e){if("string"==typeof e)return e.length>0;if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.credentialId&&t.credentialId.length>0&&(void 0===t.credentialType||"string"==typeof t.credentialType)}const Lo=new Set(["loop"]),jo=["secret","secrets","password","passwd","token","accessToken","refreshToken","apiKey","api_key","privateKey","credentials"];class Mo{validate(e,t,o,n,i){this.validateParameters(e,t,o,n,i),this.validateMetadataKeys(e,t,o,n),this.validateDisabledBehavior(e,o,n),this.validateBindingShapes(e,t,o,n)}validateParameters(e,t,o,n,i){const r=!0===t.policies?.allowUndeclaredParameters,a=new Map(t.parameters.map(e=>[e.id,e]));for(const[i,s]of Object.entries(e.parameters??{})){const d=a.get(i);if(!d){r||o.push({code:"parameter.undeclared",path:`${n}.parameters.${i}`,message:`Node '${e.id}' sets parameter '${i}' which is not declared by kind '${t.kind}'`,nodeId:e.id,details:{kind:t.kind}});continue}if(void 0===s){o.push({code:"parameter.invalid",path:`${n}.parameters.${i}`,message:`Node '${e.id}' parameter '${i}' must not be undefined`,nodeId:e.id});continue}const l=this.checkParameterValue(s,d);l.valid||o.push({code:"parameter.type-mismatch",path:`${n}.parameters.${i}`,message:`Node '${e.id}' parameter '${i}' is invalid: ${l.message}`,nodeId:e.id,details:{expectedType:d.type}})}for(const r of t.parameters)void 0===(e.parameters??{})[r.id]&&(this.isParameterSatisfiedByInput(e,r.id,i)||(!0===r.required||(r.validation??[]).some(e=>"required"===e.kind))&&void 0===r.defaultValue&&o.push({code:"parameter.required-missing",path:`${n}.parameters.${r.id}`,message:`Node '${e.id}' is missing required parameter '${r.id}' declared by kind '${t.kind}'`,nodeId:e.id}))}isParameterSatisfiedByInput(e,t,o){return void 0!==(e.inputBindings??{})[t]||!0===o?.has(t)}checkParameterValue(e,t){if(ct(e))return{valid:!0};switch(t.type){case"string":case"code":case"expression":return"string"!=typeof e?Co("string"):{valid:!0};case"number":return"number"==typeof e&&Number.isFinite(e)?{valid:!0}:Co("number");case"boolean":return"boolean"!=typeof e?Co("boolean"):{valid:!0};case"options":{const o=t.options;return o&&o.length&&!o.some(t=>t.value===e)?{valid:!1,message:"value is not one of the declared options"}:{valid:!0}}case"collection":return Array.isArray(e)?{valid:!0}:Co("array");case"object":case"resourceLocator":return null===e||"object"!=typeof e||Array.isArray(e)?Co("object"):{valid:!0};case"credential":return To(e)?t.credentialType&&"object"==typeof e&&void 0!==e.credentialType&&e.credentialType!==t.credentialType?{valid:!1,message:`credential type '${e.credentialType}' does not match the declared type '${t.credentialType}'`}:{valid:!0}:{valid:!1,message:"credential parameters must hold a credential reference (credentialId), never a secret"};default:return{valid:!0}}}validateMetadataKeys(e,t,o,n){const i=t.metadata?.allowedInstanceMetadataKeys;for(const r of Object.keys(e.metadata??{}))Lo.has(r)?o.push({code:"metadata.key-not-allowed",path:`${n}.metadata.${r}`,message:`Node '${e.id}' metadata key '${r}' is reserved and must not be set directly`,nodeId:e.id}):Array.isArray(i)&&!i.includes(r)&&o.push({code:"metadata.key-not-allowed",path:`${n}.metadata.${r}`,message:`Node '${e.id}' metadata key '${r}' is not in the allowed metadata keys of kind '${t.kind}'`,nodeId:e.id})}validateDisabledBehavior(e,t,o){!0!==e.disabled&&!1!==e.disabled&&void 0!==e.disabled&&t.push({code:"disabled.invalid",path:o+".disabled",message:`Node '${e.id}' disabled flag must be a boolean`,nodeId:e.id});const n=(e.metadata??{}).disabledBehavior;void 0===n||re(n)||t.push({code:"disabled.invalid-behavior",path:o+".metadata.disabledBehavior",message:`Node '${e.id}' disabled behavior '${n+""}' is not one of: ${ie.join(", ")}`,nodeId:e.id})}validateBindingShapes(e,t,o,n){for(const[i,r]of Object.entries(e.inputBindings??{})){if("literal"===r.mode){const a=t.inputs.find(e=>e.id===i);if(a?.schema){const t=Ro(r.value,a.schema);t.valid||o.push({code:"binding.literal-invalid",path:`${n}.inputBindings.${i}`,message:`Node '${e.id}' literal binding for '${i}' is schema-invalid: ${t.message}`,nodeId:e.id})}}"expression"!==r.mode||"string"==typeof r.expression&&r.expression.trim()||o.push({code:"binding.expression-invalid",path:`${n}.inputBindings.${i}`,message:`Node '${e.id}' expression binding for '${i}' must contain a non-empty expression`,nodeId:e.id})}}validateBindingSatisfaction(e,t,o,n,i,r={}){const a=new Set(o.filter(e=>"data"===e.type).map(e=>e.targetPort)),s=new Set(Object.entries(e.inputBindings??{}).map(([e])=>e));for(const t of a){const o=(e.inputBindings??{})[t];o&&"literal"===o.mode&&!0!==r.allowLiteralAndEdgeBindings&&n.push({code:"binding.conflict",path:`${i}.inputBindings.${t}`,message:`Node '${e.id}' input '${t}' has both an incoming edge and a literal binding`,nodeId:e.id})}for(const o of t.inputs)!0===o.required&&(a.has(o.id)||s.has(o.id)||void 0===(e.parameters??{})[o.id]&&n.push({code:"topology.required-input-unsatisfiable",path:i+".parameters",message:`Node '${e.id}' required input '${o.id}' has no incoming edge or binding`,nodeId:e.id,details:{port:o.id}}))}static disabledBehaviorOf(e,t){const o=(e.metadata??{}).disabledBehavior;if(re(o))return o;const n=t?.disabledBehavior;return re(n)?n:"skip"}}class Go{resolveEdges(e,t,o){const n=new Set(e.inputs.map(e=>e.id)),i=new Set(e.outputs.map(e=>e.id)),r=[];for(const[a,s]of(e.edges??[]).entries()){const e=`edges[${a}]`,d=this.resolveEndpoint(s,"source",t,n,i,o,e),l=this.resolveEndpoint(s,"target",t,n,i,o,e);if(!d||!l)continue;if(!this.validateDirectionAndType(s,d,l,t,o,e))continue;const c={id:s.id,type:s.type,sourceNodeId:d.nodeId,sourcePort:d.port,targetNodeId:l.nodeId,targetPort:l.port,metadata:s.metadata,edge:s};void 0!==s.label&&(c.label=s.label),r.push(c)}return r}resolveEndpoint(e,t,o,n,i,r,a){const s=e[t];return Je(s)?("source"===t?n.has(s.port):i.has(s.port))?{nodeId:Ut,port:s.port}:void r.push({code:"edge.unknown-port",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} references workflow port '${s.port}' which is not declared on the document boundary`,edgeId:e.id,details:{scope:"workflow",port:s.port}}):Xe(s)?o.get(s.nodeId)?{nodeId:s.nodeId,port:s.port}:void r.push({code:"edge.unknown-node",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} references node '${s.nodeId}' which is not part of the document or did not resolve`,edgeId:e.id,nodeId:s.nodeId}):void r.push({code:"edge.invalid-endpoint",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} endpoint is not a valid GraphEndpoint`,edgeId:e.id})}validateDirectionAndType(e,t,o,n,i,r){let a=!0;const s=t.nodeId===Ut?void 0:n.get(t.nodeId),d=o.nodeId===Ut?void 0:n.get(o.nodeId),l=e=>!0===e?.manifest.policies?.allowUndeclaredParameters;if("data"===e.type)!s||l(s)||this.hasPortDirection(s,t.port,"output")||(this.pushPortIssue(e,"source",t,s,i,r),a=!1),!d||l(d)||this.hasPortDirection(d,o.port,"input")||(this.pushPortIssue(e,"target",o,d,i,r),a=!1);else{if(!s||!d)return i.push({code:"edge.boundary-routing",path:r,message:`Connection edge '${e.id}' must connect two node connection ports; the workflow boundary only routes data`,edgeId:e.id}),!1;if(!(l(s)||l(d)||this.hasPortDirection(s,t.port,"connection")&&this.hasPortDirection(d,o.port,"connection")))return i.push({code:"edge.type-mismatch",path:r,message:`Connection edge '${e.id}' endpoints must both be connection ports`,edgeId:e.id,details:{sourcePort:t.port,targetPort:o.port}}),!1}return a}hasPortDirection(e,t,o){return("input"===o?e.manifest.inputs:"output"===o?e.manifest.outputs:e.manifest.connections??[]).some(e=>e.id===t)}pushPortIssue(e,t,o,n,i,r){const a="source"===t?"output":"input";i.push({code:"data"===e.type?"edge.invalid-direction":"edge.type-mismatch",path:`${r}.${t}`,message:`Edge '${e.id}' ${t} port '${o.port}' on node '${o.nodeId}' is not an ${a} port of kind '${n.manifest.kind}'`,edgeId:e.id,nodeId:o.nodeId,details:{port:o.port,expected:a}})}}class Uo{validate(e,t){this.validateDuplicates(e.edges,t),this.validatePolicies(e,t)}validateDuplicates(e,t){const o=new Map;for(const n of e){const e=`${n.sourceNodeId}:${n.sourcePort}->${n.targetNodeId}:${n.targetPort}`,i=o.get(e);i?t.push({code:"connection.duplicate-edge",path:`edges[${n.id}]`,message:`Edge '${n.id}' duplicates the routing of edge '${i.id}' (${e})`,edgeId:n.id,details:{duplicateOf:i.id,routing:e}}):o.set(e,n)}}validatePolicies(e,t){const o=new Map;for(const t of e.edges){if("connection"!==t.type)continue;const e=`${t.targetNodeId}:${t.targetPort}`,n=o.get(e)??[];n.push(t),o.set(e,n)}for(const o of e.edges){if("connection"!==o.type)continue;const n=e.nodeById.get(o.targetNodeId),i=n?.manifest.connections?.find(e=>e.id===o.targetPort)?.connectionPolicy;this.validateEdgePolicy(o,e.nodeById,i,t)}for(const[n,i]of o){const o=n.lastIndexOf(":"),r=n.slice(0,o),a=n.slice(o+1),s=e.nodeById.get(r),d=s?.manifest.connections?.find(e=>e.id===a)?.connectionPolicy;if(!d)continue;const l=void 0!==d.maxConnections?d.maxConnections:!1===d.allowMultiple?1:1/0;i.length>l&&t.push({code:"connection.max-connections",path:`edges[${i[i.length-1].id}]`,message:`Connection port '${a}' on node '${r}' accepts at most ${l} connection(s) but has ${i.length}`,nodeId:r,edgeId:i[i.length-1].id,details:{port:a,max:l,actual:i.length}})}}validateEdgePolicy(e,t,o,n){if(e.sourceNodeId===e.targetNodeId&&!o?.allowSelf)return void n.push({code:"connection.self-connection",path:`edges[${e.id}]`,message:`Edge '${e.id}' connects node '${e.sourceNodeId}' to itself, which the target port policy does not allow`,edgeId:e.id,nodeId:e.sourceNodeId});if(!o)return;const i=t.get(e.sourceNodeId),r=i?.manifest.kind;if(!o.allowedNodeKinds?.length||r&&o.allowedNodeKinds.includes(r)||n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source kind '${r??"unknown"}' is not in the allowed node kinds of target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{allowedNodeKinds:o.allowedNodeKinds}}),r&&o.blockedNodeKinds?.includes(r)&&n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source kind '${r}' is blocked by target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{blockedNodeKinds:o.blockedNodeKinds}}),o.allowedPortCategories?.length){const t=i?.manifest.connections?.find(t=>t.id===e.sourcePort)?.category;t&&o.allowedPortCategories.includes(t)||n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source port '${e.sourcePort}' category '${t??"unknown"}' is not in the allowed port categories of target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{allowedPortCategories:o.allowedPortCategories}})}}}class Fo{constructor(e){this.authorizer=e}async validate(e,t,o,n){const i=this.collectReferences(e,t);for(const r of t.credentials??[]){const a=i.find(e=>void 0===e.credentialType||e.credentialType===r.type);if(a){if(this.checkType(a,r))o.push({code:"credential.type-mismatch",path:n,message:`Node '${e.id}' credential '${a.credentialId}' has type '${a.credentialType}' but kind '${t.kind}' requires '${r.type}'`,nodeId:e.id,details:{credentialType:a.credentialType??"",requiredType:r.type}});else if(this.authorizer){if(!await this.authorizer.hasCredential(a)){o.push({code:"credential.not-found",path:n,message:`Node '${e.id}' references credential '${a.credentialId}' which does not exist`,nodeId:e.id,details:{credentialId:a.credentialId}});continue}await this.authorizer.authorize(a,r)||o.push({code:"credential.unauthorized",path:n,message:`Node '${e.id}' is not authorized to use credential '${a.credentialId}'`,nodeId:e.id,details:{credentialId:a.credentialId}})}}else!1!==r.required&&o.push({code:"credential.missing",path:n,message:`Node '${e.id}' does not provide the required credential of type '${r.type}'`,nodeId:e.id,details:{credentialType:r.type}})}this.scanPlainSecrets(e,o,n)}collectReferences(e,t){const o=[];for(const n of t.parameters){if("credential"!==n.type)continue;const t=(e.parameters??{})[n.id];To(t)&&o.push(this.normalize(t,n.credentialType))}const n=(e.metadata??{}).credentials;if(n&&"object"==typeof n&&!Array.isArray(n))for(const e of Object.values(n))To(e)&&o.push(this.normalize(e));return o}normalize(e,t){return"string"==typeof e?{credentialId:e,credentialType:t??""}:{credentialId:e.credentialId,credentialType:e.credentialType??t??""}}checkType(e,t){return void 0!==e.credentialType&&e.credentialType!==t.type}scanPlainSecrets(e,t,o){const n=new Set(jo);for(const[i,r]of Object.entries(e.parameters??{}))this.scanPlainSecretValue(r,[i],e,o+".parameters",n,t);for(const[i,r]of Object.entries(e.metadata??{}))this.scanPlainSecretValue(r,[i],e,o+".metadata",n,t)}scanPlainSecretValue(e,t,o,n,i,r,a=0){const s=t[t.length-1];if(i.has(s))r.push({code:"credential.plain-secret",path:`${n}.${t.join(".")}`,message:`Node '${o.id}' carries plain secret material in '${t.join(".")}'; workflow documents may only hold credential references`,nodeId:o.id});else if(8>a&&null!==e)if(Array.isArray(e))for(const s of e)this.scanPlainSecretValue(s,[...t,"[]"],o,n,i,r,a+1);else if("object"==typeof e)for(const[s,d]of Object.entries(e))this.scanPlainSecretValue(d,[...t,s],o,n,i,r,a+1)}}class Bo extends x{constructor(e,t=[]){super(e),this.issues=t,this.name=Bo.name}}class qo extends x{constructor(e,t){super(e),this.edgeId=t,this.name=qo.name}}class Vo extends M{constructor(e){super(e),this.name=Vo.name}}const Wo={maxDocumentBytes:2e6,maxNestingDepth:10,maxNodes:500,maxEdges:1e3},Ho=["node","definition","executor","execute","ports","component"];function Ko(e){if(!e||"object"!=typeof e)return!1;const t=e;return ut(t.document)&&Array.isArray(t.nodes)&&Array.isArray(t.edges)&&t.nodeById instanceof Map&&t.incomingByNode instanceof Map&&t.outgoingByNode instanceof Map&&t.nodes.every(e=>null!==e&&"object"==typeof e&&"object"==typeof e.instance&&"object"==typeof e.manifest&&"object"==typeof e.executor)}function zo(e,t){const o=[];for(const n of Object.keys(e))Ho.includes(n)&&o.push({code:"document.forbidden-field",path:`${t}.${n}`,message:`Field '${n}' is not accepted in a canonical workflow document: node, definition, executor, execute, ports and component fields are rejected`,details:{field:n}});return o}class Jo{constructor(e){this.options=e,this.parameterValidator=new Mo,this.edgeValidator=new Go,this.connectionPolicyValidator=new Uo,this.nodeValidator=new $o(e.catalogue),this.credentialValidator=new Fo(e.credentialAuthorizer)}async validateOrThrow(e,...t){const o=await this.validate(e,0,...t);if(!o.valid||!o.resolved)throw new Bo(`Graph workflow document '${e.id}' failed validation with ${o.issues.length} issue(s)`,o.issues);return o.resolved}async validate(e,t=0,...o){const n=[],i={...Wo,...this.options.limits};if(!await this.validateStructure(e,i,t,n,...o))return{valid:!1,issues:n};const r=await this.nodeValidator.resolveNodes(e.nodes,n,this.options.resolutionContext,...o),a=e.nodes.filter(e=>r.has(e.id)).map(e=>r.get(e.id)),s=(e=>{const t=new Map;for(const o of e.edges??[]){if("data"!==o.type)continue;const e=o.target;if("node"!==e.scope)continue;const n=t.get(e.nodeId)??new Set;n.add(e.port),t.set(e.nodeId,n)}return t})(e);for(const e of a)this.parameterValidator.validate(e.instance,e.manifest,n,`nodes[${e.instance.id}]`,s.get(e.instance.id));for(const e of a)this.nodeValidator.validateEffectivePorts(e.instance,e.manifest,n,`nodes[${e.instance.id}]`);const d=this.edgeValidator.resolveEdges(e,r,n),l=new Map,c=new Map;for(const e of d){if(e.targetNodeId!==Ut){const t=l.get(e.targetNodeId)??[];t.push(e),l.set(e.targetNodeId,t)}if(e.sourceNodeId!==Ut){const t=c.get(e.sourceNodeId)??[];t.push(e),c.set(e.sourceNodeId,t)}}this.connectionPolicyValidator.validate({edges:d,nodeById:r},n),this.validateAcyclicity(a,d,e,n),So(e,n);for(const e of a)this.parameterValidator.validateBindingSatisfaction(e.instance,e.manifest,l.get(e.instance.id)??[],n,`nodes[${e.instance.id}]`,{allowLiteralAndEdgeBindings:this.options.allowLiteralAndEdgeBindings});this.validateRequiredWorkflowOutputs(e,c,n);for(const e of a)await this.credentialValidator.validate(e.instance,e.manifest,n,`nodes[${e.instance.id}]`);return this.validateCapabilities(a,n),n.length>0?{valid:!1,issues:n}:{valid:!0,issues:n,resolved:{document:e,nodes:a,edges:d,nodeById:r,incomingByNode:l,outgoingByNode:c}}}async validateStructure(e,t,o,n,...i){if(!ut(e))return n.push({code:"document.shape",path:"$",message:"Payload is not a canonical GraphWorkflowDocument: id and name must be strings and inputs, outputs, nodes and edges must be arrays"}),!1;if(e.id&&e.id.trim()||n.push({code:"document.empty-id",path:"$.id",message:"Workflow document id must be a non-empty string"}),!Ge(e))return n.push({code:"document.json-unsafe",path:"$",message:"Document contains JSON-unsafe values: functions, class instances, undefined, NaN/Infinity, symbol keys and unsafe prototype keys are rejected"}),!1;n.push(...zo(e,"$"));for(const t of[...e.inputs,...e.outputs])n.push(...zo(t,"ports"));for(const t of e.nodes)n.push(...zo(t,`nodes[${t.id}]`));for(const t of e.edges)n.push(...zo(t,`edges[${t.id}]`));this.validateUniqueIds(e,n),this.validateLimits(e,t,o,n);try{tt(e)}catch(e){n.push({code:"document.structure",path:"$",message:e instanceof Error?e.message:e+""})}return await this.validateNestedBodies(e,o,n,...i),!0}validateUniqueIds(e,t){const o=new Set,n=new Set;for(const[i,r]of[["input",e.inputs],["output",e.outputs]]){const e="input"===i?o:n;for(const o of r)e.has(o.id)?t.push({code:"document.duplicate-port-id",path:`${"input"===i?"inputs":"outputs"}[${o.id}]`,message:`Workflow ${i} port '${o.id}' is declared more than once; workflow port ids must be unique`}):e.add(o.id)}const i=new Set;for(const o of e.nodes)i.has(o.id)?t.push({code:"document.duplicate-node-id",path:`nodes[${o.id}]`,message:`Node '${o.id}' is declared more than once; node ids must be unique`,nodeId:o.id}):i.add(o.id);const r=new Set;for(const o of e.edges)r.has(o.id)?t.push({code:"document.duplicate-edge-id",path:`edges[${o.id}]`,message:`Edge '${o.id}' is declared more than once; edge ids must be unique`,edgeId:o.id}):r.add(o.id)}validateLimits(e,t,o,n){e.nodes.length>t.maxNodes&&n.push({code:"document.limit.nodes",path:"$.nodes",message:`Document declares ${e.nodes.length} nodes; at most ${t.maxNodes} are allowed`,details:{count:e.nodes.length,limit:t.maxNodes}}),e.edges.length>t.maxEdges&&n.push({code:"document.limit.edges",path:"$.edges",message:`Document declares ${e.edges.length} edges; at most ${t.maxEdges} are allowed`,details:{count:e.edges.length,limit:t.maxEdges}}),o>t.maxNestingDepth&&n.push({code:"document.limit.depth",path:"$",message:`Document nests loop bodies ${o} levels deep; at most ${t.maxNestingDepth} levels are allowed`,details:{depth:o,limit:t.maxNestingDepth}});const i=Buffer.byteLength(JSON.stringify(e),"utf8");i>t.maxDocumentBytes&&n.push({code:"document.limit.size",path:"$",message:`Document serializes to ${i} bytes; at most ${t.maxDocumentBytes} bytes are allowed`,details:{bytes:i,limit:t.maxDocumentBytes}})}async validateNestedBodies(e,t,o,...n){for(const i of e.nodes){const e=[["loop.body",i.loop?.body],["errorBoundary.try",i.errorBoundary?.try],["errorBoundary.catch",i.errorBoundary?.catch],["errorBoundary.finally",i.errorBoundary?.finally]];for(const[r,a]of e){if(!a)continue;const e=await this.validate(a,t+1,...n);for(const t of e.issues)o.push({...t,path:`nodes[${i.id}].${r}.${t.path}`,nodeId:t.nodeId??i.id})}}}validateAcyclicity(e,t,o,n){const i=new Set(e.map(e=>e.instance.id)),r=new Map(e.map(e=>[e.instance.id,0]));for(const e of t)i.has(e.sourceNodeId)&&r.has(e.targetNodeId)&&r.set(e.targetNodeId,(r.get(e.targetNodeId)??0)+1);const a=[...r.entries()].filter(([,e])=>0===e).map(([e])=>e),s=[];for(;a.length>0;){const e=a.shift();s.push(e);for(const o of t){if(o.sourceNodeId!==e)continue;if(!r.has(o.targetNodeId))continue;const t=(r.get(o.targetNodeId)??1)-1;r.set(o.targetNodeId,t),0===t&&a.push(o.targetNodeId)}}if(s.length!==r.size){const e=[...r.keys()].filter(e=>!s.includes(e));n.push({code:"topology.cycle",path:"$.edges",message:`Workflow '${o.id}' contains an unsupported cycle involving node(s): ${e.join(", ")}`,details:{cyclicNodes:e}})}}validateRequiredWorkflowOutputs(e,t,o){const n=new Set;for(const e of t.values())for(const t of e)t.targetNodeId===Ut&&n.add(t.targetPort);for(const t of e.outputs)!0===t.required&&void 0===t.defaultValue&&(n.has(t.id)||o.push({code:"topology.required-output-unsatisfiable",path:`outputs[${t.id}]`,message:`Required workflow output '${t.id}' has no incoming edge from any node`}))}validateCapabilities(e,t){for(const o of e){const e=o.manifest;for(const n of e.capabilities??[])ft(n)||t.push({code:"capability.invalid",path:`nodes[${o.instance.id}]`,message:`Kind '${e.kind}' declares unknown capability '${n+""}'`,nodeId:o.instance.id,details:{capability:n+""}});!0!==e.policies?.allowUndeclaredParameters&&o.instance.loop&&((e.capabilities??[]).includes("loop")||t.push({code:"capability.loop-not-supported",path:`nodes[${o.instance.id}].loop`,message:`Node '${o.instance.id}' carries loop configuration but kind '${e.kind}' does not declare the 'loop' capability`,nodeId:o.instance.id}))}}}let Xo=class extends U{constructor(){super()}async plan(e,...t){const{log:o}=(await this.logCtx(t,"plan",!0)).for(this.plan);if(o.debug(`Planning resolved workflow '${e?.document?.id??"unknown"}'`),!Ko(e))throw new io("GraphExecutionPlanner.plan accepts only a GraphResolvedWorkflow produced by the nine-stage validation gate; raw workflow definitions and inline node definitions are rejected",{received:(n=e,n&&"object"==typeof n?{reason:"input is not a GraphResolvedWorkflow",looksLikeWorkflowDefinition:"nodes"in n&&"relations"in n&&!("nodeById"in n),hasResolvedNodes:Array.isArray(n.nodes)}:{reason:"input is not an object"})});var n;const i=this.buildPlanNodes(e),r=this.buildPlanEdges(e),a=this.buildIncomingMap(r),s=this.buildOutgoingMap(r),d=this.topologicalLayers(i,r);return{resolved:e,workflowId:e.document.id||e.document.name,nodes:i,edges:r,layers:d,incomingByNode:a,outgoingByNode:s}}buildPlanNodes(e){return e.nodes.map(e=>({id:e.instance.id,kind:e.manifest.kind,instance:e.instance,manifest:e.manifest,executor:e.executor,inputPorts:e.manifest.inputs.map(e=>e.id),outputPorts:e.manifest.outputs.map(e=>e.id),connectionPorts:(e.manifest.connections??[]).map(e=>e.id),metadata:e.instance.metadata}))}buildPlanEdges(e){return e.edges.map(e=>({id:e.id,type:e.type,sourceNodeId:e.sourceNodeId,sourcePort:e.sourcePort,targetNodeId:e.targetNodeId,targetPort:e.targetPort,...void 0!==e.label?{label:e.label}:{},metadata:e.metadata}))}buildIncomingMap(e){const t=new Map;for(const o of e){if(o.targetNodeId===Ut)continue;const e=t.get(o.targetNodeId)??[];e.push(o),t.set(o.targetNodeId,e)}return t}buildOutgoingMap(e){const t=new Map;for(const o of e){if(o.sourceNodeId===Ut)continue;const e=t.get(o.sourceNodeId)??[];e.push(o),t.set(o.sourceNodeId,e)}return t}topologicalLayers(e,t){const o=e.filter(e=>e.id!==Ut),n=new Set(o.map(e=>e.id)),i=t.filter(e=>n.has(e.sourceNodeId)&&n.has(e.targetNodeId)),r=new Map;for(const e of o)r.set(e.id,0);for(const e of i)r.set(e.targetNodeId,(r.get(e.targetNodeId)??0)+1);const a=[],s=new Set;let d=o.filter(e=>0===(r.get(e.id)??0)),l=0;for(;d.length>0;){const e={index:l++,nodes:d};a.push(e);const t=[];for(const e of d){s.add(e.id);const n=i.filter(t=>t.sourceNodeId===e.id);for(const e of n){const n=(r.get(e.targetNodeId)??1)-1;if(r.set(e.targetNodeId,n),0===n&&!s.has(e.targetNodeId)){const n=o.find(t=>t.id===e.targetNodeId);n&&t.push(n)}}}d=t}if(s.size!==o.length){const e=o.filter(e=>!s.has(e.id)).map(e=>e.id);throw new Qt({unplannedNodes:e,workflowId:o[0]?.manifest.kind})}return a}};Xo=D([G(),P("design:paramtypes",[])],Xo);let Yo=class extends T{constructor(e){super(e)}};function Qo(e){return[e.namespace??"default",e.workflowId,e.nodeId,e.version??"default",e.fingerprint].join(":")}function Zo(e){return new Yo({id:Qo(e.key),workflowId:e.key.workflowId,nodeId:e.key.nodeId,fingerprint:e.key.fingerprint,...void 0!==e.key.namespace?{namespace:e.key.namespace}:{},...void 0!==e.key.version?{version:e.key.version}:{},pinned:e.pinned,outputs:e.outputs,createdAt:new Date(e.createdAt),updatedAt:new Date(e.updatedAt),...e.expiresAt?{expiresAt:new Date(e.expiresAt)}:{},...e.metadata?{metadata:e.metadata}:{}})}function en(e){return{key:{workflowId:e.workflowId,nodeId:e.nodeId,fingerprint:e.fingerprint,...void 0!==e.namespace?{namespace:e.namespace}:{},...void 0!==e.version?{version:e.version}:{}},outputs:e.outputs,pinned:e.pinned,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString(),...e.expiresAt?{expiresAt:e.expiresAt.toISOString()}:{},...e.metadata?{metadata:e.metadata}:{}}}D([$({type:String,generated:!1}),P("design:type",String)],Yo.prototype,"id",void 0),D([S(),R(),P("design:type",String)],Yo.prototype,"workflowId",void 0),D([S(),R(),P("design:type",String)],Yo.prototype,"nodeId",void 0),D([S(),P("design:type",String)],Yo.prototype,"fingerprint",void 0),D([S(),P("design:type",String)],Yo.prototype,"namespace",void 0),D([S(),P("design:type",String)],Yo.prototype,"version",void 0),D([S(),P("design:type",Boolean)],Yo.prototype,"pinned",void 0),D([S(),P("design:type",Object)],Yo.prototype,"outputs",void 0),D([S(),P("design:type",Date)],Yo.prototype,"createdAt",void 0),D([S(),P("design:type",Date)],Yo.prototype,"updatedAt",void 0),D([S(),P("design:type",Date)],Yo.prototype,"expiresAt",void 0),D([S(),P("design:type",Object)],Yo.prototype,"metadata",void 0),Yo=D([C("graph_value"),E(),P("design:paramtypes",[Object])],Yo);let tn=class extends B{constructor(e){super(e,Yo,!0),this.runtimeValues=new Map}seedWorkflowInputs(e){this.runtimeValues.set(Ut,{...e})}setNodeOutputs(e,t){this.runtimeValues.set(e,{...t})}getPort(e,t){return this.runtimeValues.get(e)?.[t]}hasPort(e,t){return Object.prototype.hasOwnProperty.call(this.runtimeValues.get(e)??{},t)}setWorkflowOutput(e,t){const o=this.runtimeValues.get(Ut)??{};o[e]=t,this.runtimeValues.set(Ut,o)}getWorkflowValues(){return{...this.runtimeValues.get(Ut)??{}}}snapshot(){return Object.fromEntries(this.runtimeValues.entries())}async readCached(e,...t){try{return en(await this.read(Qo(e),...t))}catch{return}}async writeCached(e,t,...o){const n=Qo(e);let i;try{i=await this.read(n,...o)}catch{i=void 0}i?await this.update(Object.assign(i,Zo(t)),...o):await this.create(Zo(t),...o)}async deleteCached(e,...t){try{await this.delete(Qo(e),...t)}catch{}}async hasCached(e,...t){return void 0!==await this.readCached(e,...t)}async listCached(e,...t){return(await this.select().execute(...t)).map(e=>en(e)).filter(t=>((e,t)=>!(void 0!==t.workflowId&&e.workflowId!==t.workflowId||void 0!==t.nodeId&&e.nodeId!==t.nodeId||void 0!==t.namespace&&e.namespace!==t.namespace||void 0!==t.version&&e.version!==t.version||void 0!==t.fingerprint&&e.fingerprint!==t.fingerprint))(t.key,e))}async clearRun(e,...t){const o=await this.select().execute(...t);for(const e of o)await this.delete(e.id,...t)}readRuntimeValues(e){return this.runtimeValues.get(e)}writeRuntimeValues(e,t){this.runtimeValues.set(e,{...t})}getAdapter(){return this.adapter}};function on(e){return new(0,B.forModel(Yo,e.alias).constructor)(e)}tn=D([F(Yo,m),P("design:paramtypes",[Function])],tn);class nn{static upstreamNodes(e,t,o=!1){const n=new Set,i=[e];for(;i.length;){const e=i.pop(),r=t.get(e)??[];for(const e of r)!o&&this.isBoundary(e.sourceNodeId)||n.has(e.sourceNodeId)||(n.add(e.sourceNodeId),i.push(e.sourceNodeId))}return n}static downstreamNodes(e,t,o=!1){const n=new Set,i=[e];for(;i.length;){const e=i.pop(),r=t.get(e)??[];for(const e of r)!o&&this.isBoundary(e.targetNodeId)||n.has(e.targetNodeId)||(n.add(e.targetNodeId),i.push(e.targetNodeId))}return n}static isBoundary(e){return"$workflow"===e}}class rn{constructor(e,t,o){this.store=e,this.policy=t,this.dependencyResolver=o}async pinNode(e){const t=e.plan,o=e.includeDependencies??1?this.dependencyResolver.getPinSet(t,e.nodeId):new Set([e.nodeId]);for(const e of o){const o=t.nodes.find(t=>t.id===e);if(!o)throw new to(`Node '${e}' not found in plan`);if(!this.policy.canPin(o))throw new to(`Node '${e}' is not pinnable`,{nodeId:e})}const n=this.topologicalOrder(t,o);for(const o of n){const n=t.nodes.find(e=>e.id===o),i=e.result.nodeResults[o];if(!i||!i.outputs)throw new to(`Node '${o}' has no completed output to pin`);const r=i.inputs??{},a=this.dependencyFingerprints(t,o,e.result),s=this.createValueKey(e.document.id,n,r,a),d=(new Date).toISOString(),l={key:s,outputs:i.outputs,pinned:!0,createdAt:d,updatedAt:d,metadata:{...e.result.metadata,nodeId:o}};await this.store.writeCached(s,l)}}async unpinNode(e){const t={workflowId:e.document.id,nodeId:e.nodeId,fingerprint:e.fingerprint,namespace:e.namespace};await this.store.deleteCached(t)}async readPinnedValue(e,t,o,n,i){const r=this.createValueKey(e,t,o,n,i),a=await this.store.readCached(r);if(a&&a.pinned){if(a.expiresAt&&new Date(a.expiresAt)<new Date)return;return a}}createValueKey(e,t,o,n,i){return{workflowId:e,nodeId:t.id,fingerprint:this.computeFingerprint(e,t,o,n),namespace:i}}computeFingerprint(e,t,o,n){const i={workflowId:e,nodeId:t.id,nodeKind:t.kind,parameters:this.stableSerialize(t.instance.parameters??{}),inputBindings:this.stableSerialize(t.instance.inputBindings??{}),metadata:this.stableSerialize(this.relevantMetadata(t)),inputs:this.stableSerialize(o),dependencyFingerprints:this.stableSerialize(n)},r=this.stableSerialize(i);return this.simpleHash(r)}relevantMetadata(e){const t={...e.metadata??{}};return delete t.ui,delete t.position,delete t.visual,t}topologicalOrder(e,t){const o=[],n=new Set,i=r=>{if(n.has(r))return;n.add(r);const a=nn.upstreamNodes(r,e.incomingByNode,!1);for(const e of a)t.has(e)&&i(e);o.push(r)};for(const e of t)i(e);return o}dependencyFingerprints(e,t,o){const n=this.dependencyResolver.getDependencies(e,t),i={};for(const t of n){const n=e.nodes.find(e=>e.id===t);if(n){const r=o.nodeResults[t],a=r?.inputs??{},s=this.dependencyFingerprints(e,t,o);i[t]=this.computeFingerprint(e.workflowId,n,a,s)}}return i}stableSerialize(e){return null===e||"object"!=typeof e?JSON.stringify(e):Array.isArray(e)?`[${e.map(e=>this.stableSerialize(e)).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${this.stableSerialize(e[t])}`).join(",")}}`}simpleHash(e){let t=0;for(let o=0;o<e.length;o++)t=(t<<5)-t+e.charCodeAt(o),t|=0;return`fp_${Math.abs(t).toString(16).padStart(8,"0")}_${e.length}`}}const an={enabled:!0,strategy:"manual",includeDependencies:!0};function sn(e){return!0===e?.enabled&&"disabled"!==e.strategy}class dn{canPin(e){return sn(this.getPinningMetadata(e))}shouldUsePinnedValue(e){const t=this.getPinningMetadata(e);return!0===t.enabled&&"disabled"!==t.strategy}shouldAutoPin(e){const t=this.getPinningMetadata(e);return!0===t.enabled&&"automatic"===t.strategy}getPinningMetadata(e){const t=e.manifest.metadata?.pinnable??e.metadata?.pinnable;return t?{...an,...t}:{...an,enabled:!1}}}class ln{getDependencies(e,t){return nn.upstreamNodes(t,e.incomingByNode,!1)}getPinSet(e,t){const o=this.getDependencies(e,t);return o.add(t),o}}class cn extends q{constructor(){super()}async initialize(...e){const t=e[0];if(!t||"object"!=typeof t||!t.registry)return this._config=void 0,this._client=void 0,{config:void 0,client:void 0};const o=t.catalogue??t.registry.catalog,n=t.valueAdapter??V.current;if(!n)throw new Yt("GraphExecutionEngine requires a Decaf adapter for cached/pinned values: pass `valueAdapter` or configure one via `Adapter.setCurrent(...)`","GRAPH_VALUE_ADAPTER_MISSING");const i={registry:t.registry,catalogue:o,planner:t.planner??new Xo,valueAdapter:n,eventEmitter:t.eventEmitter??new lo,documentValidator:t.documentValidator??new Jo({catalogue:o,limits:t.documentLimits,credentialAuthorizer:t.credentialAuthorizer}),authValidator:new Ao({enabled:!0===t.authEnabled,...t.authMatch?{match:t.authMatch}:{}}),...t.codeSandboxEvaluator?{codeSandboxEvaluator:t.codeSandboxEvaluator}:{}};return this._config=t,this._client=i,await(t.onEngineCreated?.(this)),{config:t,client:i}}get codeSandboxEvaluator(){return this.client.codeSandboxEvaluator}get emitter(){return this.client.eventEmitter}get planner(){return this.client.planner}get valueAdapter(){return this.client.valueAdapter}get defaultOptions(){return this.config.defaultOptions??{}}get documentValidator(){return this.client.documentValidator}observe(e){return this.emitter.observe(e)}unObserve(e){this.emitter.unObserve(e)}async dispatchEvent(e){await this.emitter.updateObservers(e)}async execute(e,t={},o={},...n){const{log:i,ctx:r}=(await this.logCtx(n,"execute",!0)).for(this.execute);i.debug(`Executing workflow '${e.id||e.name}'`);const a=this.mergeOptions(o);this.assertNotAborted(a);const s=Oo(Eo(r),a.auth);a.auth=s,a.metadata={...a.metadata??{},...s};const d=a.runId??this.generateRunId(),l=a.path??[],c=new co,u=on(this.valueAdapter);u.seedWorkflowInputs(this.withWorkflowInputDefaults(e,t));const p=async t=>{await this.emitEvent(m,{type:t.type??le.NODE_OUTPUT,runId:d,parentRunId:a.parentRunId,workflowId:e.id||e.name,nodeId:t.nodeId,path:t.path??l,...t})},h=async t=>{const o=c.create({id:"",sequence:0,timestamp:new Date,runId:d,parentRunId:a.parentRunId,workflowId:e.id||e.name,path:l,...t});await this.emitter.updateObservers(o)};await h({type:le.VALIDATION_STARTED,status:ae.PLANNING});const f=await this.documentValidator.validate(e,0,r);if(!f.valid||!f.resolved)throw await h({type:le.VALIDATION_FAILED,status:ae.FAILED,payload:{issues:f.issues}}),new Bo(`Graph workflow document '${e.id}' failed validation with ${f.issues.length} issue(s)`,f.issues);await h({type:le.VALIDATION_COMPLETED,status:ae.PLANNING,payload:{issues:f.issues.length}}),this.assertNotAborted(a);const g=await this.planner.plan(f.resolved);this.client.authValidator.validate(e,g,s,i),i.debug(`Authorized workflow '${e.id||e.name}' for user ${s.user??"anonymous"}`);const m=new Do(d,g,u,c);await this.emitEvent(m,{type:le.WORKFLOW_STARTED,runId:d,parentRunId:a.parentRunId,workflowId:g.workflowId,path:l,status:ae.RUNNING,payload:{inputs:t}}),await this.emitEvent(m,{type:le.WORKFLOW_PLANNED,runId:d,parentRunId:a.parentRunId,workflowId:g.workflowId,path:l,status:ae.PLANNING,payload:{layers:g.layers.length,nodes:g.nodes.length}});try{for(const e of g.layers)this.assertNotAborted(a),await this.executeLayer(m,g,e.nodes,a,p);this.assertNotAborted(a);const o=[...m.nodeResults.values()].find(e=>e.status===ae.FAILED);if(o?.error)throw new Yt(o.error.message,o.error.code??"GRAPH_EXECUTION_ERROR",o.error.details);return m.finish(),await this.emitEvent(m,{type:le.WORKFLOW_COMPLETED,runId:d,parentRunId:a.parentRunId,workflowId:g.workflowId,path:l,status:ae.SUCCEEDED,payload:{outputs:u.getWorkflowValues()}}),Po(m,e,t,ae.SUCCEEDED,a.metadata)}catch(o){if(o instanceof ro)throw m.finish(),o;m.finish();const n=this.toErrorPayload(o);return o instanceof ao||!0===a.abortSignal?.aborted?(await this.emitEvent(m,{type:le.WORKFLOW_CANCELLED,runId:d,parentRunId:a.parentRunId,workflowId:g.workflowId,path:l,status:ae.CANCELLED,error:n}),Po(m,e,t,ae.CANCELLED,a.metadata)):(await this.emitEvent(m,{type:le.WORKFLOW_FAILED,runId:d,parentRunId:a.parentRunId,workflowId:g.workflowId,path:l,status:ae.FAILED,error:n}),Po(m,e,t,ae.FAILED,a.metadata))}}async pinNode(e){const t=this.createPinningService();await t.pinNode(e),await this.emitPinningEvent(e.nodeId,le.NODE_PINNED)}async unpinNode(e){const t=this.createPinningService();await t.unpinNode(e),await this.emitPinningEvent(e.nodeId,le.NODE_UNPINNED)}createPinningService(){const e=on(this.valueAdapter);return new rn(e,new dn,new ln)}async emitPinningEvent(e,t){const o=(new co).create({id:"",sequence:0,timestamp:new Date,runId:"pinning",workflowId:"",type:t,nodeId:e,path:[]});await this.emitter.updateObservers(o)}withWorkflowInputDefaults(e,t){const o={...t};for(const t of e.inputs)void 0===o[t.id]&&void 0!==t.defaultValue&&(o[t.id]=t.defaultValue);return o}async executeLayer(e,t,o,n,i){const r=Math.max(1,n.concurrency??4),a=[...o];for(;a.length>0;){const o=a.splice(0,r);await Promise.all(o.map(o=>this.executeNode(e,t,o,n,i)))}}async executeNode(e,t,o,n,i){if(this.assertNotAborted(n),!this.isNodeActivated(e,t,o))return void await this.skipInactiveNode(e,t,o,n);if(!0===o.instance.disabled)return void await this.executeDisabledNode(e,t,o,n);const r=new Date,a=[...n.path??[],o.id];await this.emitEvent(e,{type:le.NODE_STARTED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:ae.RUNNING}),this.emitNodeStateChanged(e,t,o,a,se.RUNNING,ae.RUNNING);const s=await this.resolveNodeInputs(e,t,o,n);if(n.usePinnedValues){const n=await this.tryPinnedValue(e,t,o,s);if(n){e.valueStore.setNodeOutputs(o.id,n.outputs),this.routeOutgoingEdges(e,t,o,n.outputs);const i=new Date,d={nodeId:o.id,status:ae.CACHED,inputs:s,outputs:n.outputs,startedAt:r,finishedAt:i,fromCache:!0,pinned:!0,events:[]};return e.recordNodeResult(d),await this.emitEvent(e,{type:le.NODE_CACHE_HIT,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:ae.CACHED,payload:{outputs:n.outputs}}),await this.emitEvent(e,{type:le.NODE_COMPLETED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:ae.SUCCEEDED,payload:{outputs:n.outputs,fromCache:!0}}),void this.emitNodeStateChanged(e,t,o,a,se.SUCCEEDED,ae.SUCCEEDED)}}try{const d=new _o(e.runId,n.parentRunId,t.workflowId,t.resolved.document,o.instance,o.manifest,a,i,n.metadata,this,n.abortSignal,this.executionLimits(n)),l=await this.resolveNodeParameters(o,s,n),c={nodeId:o.id,kind:o.kind,inputs:s,parameters:l,credentials:this.collectCredentials(o),metadata:o.instance.metadata},u=await this.invokeExecutor(o,c,d),p=this.validateNodeOutputs(o,u??{});e.valueStore.setNodeOutputs(o.id,p),this.routeOutgoingEdges(e,t,o,p);const h=new Date,f={nodeId:o.id,status:ae.SUCCEEDED,inputs:s,outputs:p,startedAt:r,finishedAt:h,events:[]};e.recordNodeResult(f),await this.emitEvent(e,{type:le.NODE_COMPLETED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:ae.SUCCEEDED,payload:{outputs:p}}),this.emitNodeStateChanged(e,t,o,a,se.SUCCEEDED,ae.SUCCEEDED)}catch(i){if(i instanceof ro)throw i;const d=new Date,l=this.toErrorPayload(i),c={nodeId:o.id,status:ae.FAILED,inputs:s,error:l,startedAt:r,finishedAt:d,events:[]};if(e.recordNodeResult(c),await this.emitEvent(e,{type:le.NODE_FAILED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:ae.FAILED,error:l}),this.emitNodeStateChanged(e,t,o,a,se.FAILED,ae.FAILED),n.failFast??1)throw i}}isNodeActivated(e,t,o){const n=(t.incomingByNode.get(o.id)??[]).filter(e=>"data"===e.type);return 0===n.length||n.some(t=>t.sourceNodeId===Ut||e.isDataEdgeActive(t.id))}async skipInactiveNode(e,t,o,n){const i=new Date,r=[...n.path??[],o.id];await this.emitEvent(e,{type:le.NODE_SKIPPED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:r,status:ae.SKIPPED,payload:{reason:"branchNotSelected"}});const a={nodeId:o.id,status:ae.SKIPPED,inputs:{},startedAt:i,finishedAt:new Date,events:[]};e.recordNodeResult(a),this.emitNodeStateChanged(e,t,o,r,se.SKIPPED,ae.SKIPPED)}async executeDisabledNode(e,t,o,n){const i=new Date,r=[...n.path??[],o.id],a=Mo.disabledBehaviorOf(o.instance,t.resolved.document.settings);if(await this.emitEvent(e,{type:le.NODE_SKIPPED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:r,status:ae.SKIPPED,payload:{disabled:!0,behavior:a}}),"skip"===a){const n={nodeId:o.id,status:ae.SKIPPED,inputs:{},startedAt:i,finishedAt:new Date,events:[]};return e.recordNodeResult(n),void this.emitNodeStateChanged(e,t,o,r,se.SKIPPED,ae.SKIPPED)}const s=await this.resolveNodeInputs(e,t,o,n);let d;if("passThroughFirstInput"===a){const n=(t.incomingByNode.get(o.id)??[]).find(e=>"data"===e.type),i=o.manifest.outputs[0]?.id??"value",r=n?e.valueStore.getPort(n.sourceNodeId,n.sourcePort):Object.values(s)[0];d={[i]:r}}else{d={};for(const e of o.manifest.outputs)d[e.id]=e.metadata?.defaultValue}e.valueStore.setNodeOutputs(o.id,d),this.routeOutgoingEdges(e,t,o,d);const l={nodeId:o.id,status:ae.SUCCEEDED,inputs:s,outputs:d,startedAt:i,finishedAt:new Date,events:[]};e.recordNodeResult(l),this.emitNodeStateChanged(e,t,o,r,se.SUCCEEDED,ae.SUCCEEDED)}async invokeExecutor(e,t,o){return await e.executor.execute(t,o)}validateNodeOutputs(e,t){const o=e.manifest;if(!0===o.policies?.allowUnknownOutputs)return t;const n=new Set(o.outputs.map(e=>e.id)),i=Object.keys(t).filter(e=>!n.has(e));if(i.length>0)throw new Yt(`Node '${e.id}' of kind '${e.kind}' produced unknown output(s): ${i.join(", ")}`,"GRAPH_OUTPUT_VALIDATION_FAILED",{nodeId:e.id,unknownOutputs:i});const r=o.outputs.filter(e=>!0===e.required&&!(e.id in t)).map(e=>e.id);if(r.length>0)throw new Yt(`Node '${e.id}' of kind '${e.kind}' did not produce required output(s): ${r.join(", ")}`,"GRAPH_OUTPUT_VALIDATION_FAILED",{nodeId:e.id,missingRequired:r});return t}collectCredentials(e){const t={};for(const o of e.manifest.parameters){if("credential"!==o.type)continue;const n=(e.instance.parameters??{})[o.id];"string"==typeof n&&n.length>0?t[o.id]={credentialId:n,credentialType:o.credentialType??""}:To(n)&&(t[o.id]={credentialId:n.credentialId,credentialType:n.credentialType})}const o=(e.instance.metadata??{}).credentials;if(o&&"object"==typeof o&&!Array.isArray(o))for(const[e,n]of Object.entries(o)){const o=n;"string"==typeof o&&o.length>0?t[e]={credentialId:o,credentialType:""}:To(o)&&(t[e]={credentialId:o.credentialId,credentialType:o.credentialType})}return t}async resolveNodeInputs(e,t,o,n){const i={},r=(t.incomingByNode.get(o.id)??[]).filter(e=>"data"===e.type),a=new Map;for(const e of r){const t=a.get(e.targetPort)??[];t.push(e),a.set(e.targetPort,t)}for(const[t,o]of a)if(1===o.length)i[t]=e.valueStore.getPort(o[0].sourceNodeId,o[0].sourcePort);else{let n,r=!1;for(const t of o){const o=e.valueStore.getPort(t.sourceNodeId,t.sourcePort);i[t.sourcePort]=o,void 0!==o&&(n=o,r=!0)}r&&void 0===i[t]&&(i[t]=n)}const s=o.instance.inputBindings??{};for(const e of o.manifest.inputs){const t=s[e.id];if("literal"===t?.mode)i[e.id]=t.value;else if("expression"===t?.mode)i[e.id]=await this.evaluateExpressionBinding(o,t.expression,i,n);else if(void 0===i[e.id]){const t=e.metadata?.defaultValue;void 0!==t&&(i[e.id]=t)}}return i}async resolveNodeParameters(e,t,o){const n=e.instance.parameters??{},i={};for(const[r,a]of Object.entries(n))i[r]=ct(a)?await this.evaluateValueTemplate(a,e,t,o):a;return i}async evaluateValueTemplate(e,t,o,n){const i=this.codeSandboxEvaluator;if(!i)throw new Yt(`Value template on node '${t.id}' requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator`,"GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{nodeId:t.id});const r=e.language??("expression"===e.mode?"javascript":"text"),a="template"===e.mode?(e=>`\`${e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\{\{\s*([\s\S]*?)\s*\}\}/g,(e,t)=>`\${${t}}`)}\``)(e.expression):e.expression,s=n.metadata;return await i.evaluate({code:a,language:"typescript"===r?"typescript":"javascript",input:o,vars:s?.vars??void 0,item:s?.item,index:s?.index,abortSignal:n.abortSignal})}async evaluateExpressionBinding(e,t,o,n){const i=this.codeSandboxEvaluator;if(!i)throw new Yt(`Expression binding on node '${e.id}' requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator`,"GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{nodeId:e.id,expression:t});const r=n.metadata;return await i.evaluate({code:t,language:"javascript",input:o,vars:r?.vars??void 0,item:r?.item,index:r?.index,abortSignal:n.abortSignal})}async tryPinnedValue(e,t,o,n){if(!(new dn).shouldUsePinnedValue(o))return;const i=this.createPinningService(),r=this.computeDependencyFingerprints(e,t,o.id);return i.readPinnedValue(t.workflowId,o,n,r)}computeDependencyFingerprints(e,t,o){const n=this.createPinningService(),i=(new ln).getDependencies(t,o),r={};for(const o of i){const i=t.nodes.find(e=>e.id===o);if(i){const a=e.nodeResults.get(o),s=a?.inputs??{},d=this.computeDependencyFingerprints(e,t,o);r[o]=n.computeFingerprint(t.workflowId,i,s,d)}}return r}routeOutgoingEdges(e,t,o,n){const i=(t.outgoingByNode.get(o.id)??[]).filter(e=>"data"===e.type);for(const r of i){if(!Object.prototype.hasOwnProperty.call(n,r.sourcePort))continue;const i=n[r.sourcePort];e.activateDataEdge(r.id),r.targetNodeId===Ut&&e.valueStore.setWorkflowOutput(r.targetPort,i),this.emitEdgeStateChanged(e,t,o,r,se.SUCCEEDED,ae.SUCCEEDED),this.emitEvent(e,{type:le.EDGE_VALUE_ROUTED,runId:e.runId,workflowId:t.workflowId,edgeId:r.id,nodeId:o.id,path:[],payload:{edge:r,value:i}}).catch(()=>{})}}async emitEvent(e,t){const o=e.eventFactory.create({id:"",sequence:0,timestamp:new Date,...t});e.appendEvent(o),await this.emitter.updateObservers(o)}emitNodeStateChanged(e,t,o,n,i,r){this.emitEvent(e,{type:le.NODE_STATE_CHANGED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:n,status:r,payload:{nodeId:o.id,state:i,runId:e.runId,workflowId:t.workflowId,status:r}}).catch(()=>{})}emitEdgeStateChanged(e,t,o,n,i,r){this.emitEvent(e,{type:le.EDGE_STATE_CHANGED,runId:e.runId,workflowId:t.workflowId,edgeId:n.id,nodeId:o.id,path:[],status:r,payload:{edgeId:n.id,state:i,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,status:r}}).catch(()=>{})}mergeOptions(e){return{concurrency:4,failFast:!0,validateInputs:!0,validateOutputs:!0,maxLoopIterations:Vt,maxForeachIterations:Wt,usePinnedValues:!0,writeThroughCache:!1,path:[],metadata:{},...this.defaultOptions,...e}}executionLimits(e){return{maxLoopIterations:e.maxLoopIterations??Vt,maxForeachIterations:e.maxForeachIterations??Wt}}assertNotAborted(e){if(!0===e.abortSignal?.aborted)throw new ao(e.runId??"unknown")}generateRunId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new Yt("Cannot generate a graph run id: crypto.randomUUID is unavailable in this runtime","GRAPH_RUN_ID_ERROR",{runtime:typeof globalThis.crypto});return e.randomUUID()}toErrorPayload(e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack,code:e.graphCode??("number"==typeof e.code?e.code+"":e.code)}:{name:"UnknownError",message:e+""}}}const un=new Set(["process","require","module","exports","global","globalThis","Function","eval","fetch","XMLHttpRequest","WebSocket","Worker","Deno","Bun","__dispatch"]);class pn extends q{constructor(){super()}async initialize(...e){const t=e[0]??{},o=t&&"object"==typeof t?t:{};return this._config=o,this._client=H,{config:o,client:H}}get defaultTimeoutMs(){return this.config.timeoutMs??1e3}get defaultMemoryMb(){return this.config.memoryMb??32}async evaluate(e,...t){(await this.logCtx(t,"evaluate",!0)).for(this.evaluate);const o=e.code;if(!o||"string"!=typeof o||0===o.trim().length)throw new Yt("Code sandbox received empty code","GRAPH_CODE_SANDBOX_EMPTY_CODE");const n=((e,t)=>"javascript"===t?e:J.transpileModule(e,{compilerOptions:{target:J.ScriptTarget.ES2022,module:J.ModuleKind.None,strict:!0,noEmitHelpers:!0,importHelpers:!1}}).outputText.replace(/^"use strict";\s*/,""))(o,e.language??"javascript");(e=>{if(e.length>1e5)throw new Yt("Code exceeds the maximum length of 100000 characters","GRAPH_CODE_SANDBOX_CODE_TOO_LONG",{length:e.length});let t;try{t=K.parse(`async function __validate() {\n${e}\n}`,{ecmaVersion:"latest",sourceType:"script"})}catch{try{t=K.parse(e,{ecmaVersion:"latest",sourceType:"module"})}catch(t){throw new Yt("Code failed to parse: "+t.message,"GRAPH_CODE_SANDBOX_PARSE_ERROR",{code:e,error:t.message})}}z.full(t,e=>{const t=e;if("ImportDeclaration"===t.type)throw new Yt("Imports are not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"import"});if("ExportNamedDeclaration"===t.type||"ExportDefaultDeclaration"===t.type)throw new Yt("Exports are not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"export"});if("Identifier"===t.type&&"string"==typeof t.name&&un.has(t.name))throw new Yt(`Identifier "${t.name}" is not allowed in Code nodes.`,"GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:t.name});if("NewExpression"===t.type&&"Function"===t.callee?.name)throw new Yt("new Function() is not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"Function"});if("CallExpression"===t.type&&"eval"===t.callee?.name)throw new Yt("eval() is not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"eval"})})})(n);const i=!(e=>/\breturn\b[\s;]/.test(e))(n),r=i?n.replace(/[\s;]+$/,""):n,a={$input:e.input??{},$vars:e.vars??{},$item:e.item,$index:e.index,$node:e.nodes??{},$output:void 0},s=Object.keys(a),d=i?`return (${r});`:r,l=`"use strict";\nasync function __userFunction(${s.join(", ")}) {\n${d}\n}\n__userFunction(${s.join(", ")}).then(function(__r) { return JSON.stringify({ v: __r }); });`,c=new H.Isolate({memoryLimit:this.defaultMemoryMb}),u=await c.createContext();try{const t=u.global;e.logger&&await this.injectConsole(u,e.logger);for(const[e,o]of Object.entries(a))await t.set(e,new H.ExternalCopy(void 0===o?null:o).copyInto());let o;try{o=await c.compileScript(l,{filename:"graph-code-node.js"})}catch(e){if(!i)throw new Yt("Code failed to compile: "+e.message,"GRAPH_CODE_SANDBOX_COMPILE_ERROR",{code:n,error:e.message});{const e=r,t=`"use strict";\nasync function __userFunction(${s.join(", ")}) {\n${e}\n}\n__userFunction(${s.join(", ")}).then(function(__r) { return JSON.stringify({ v: __r }); });`;try{o=await c.compileScript(t,{filename:"graph-code-node.js"})}catch(e){throw new Yt("Code failed to compile: "+e.message,"GRAPH_CODE_SANDBOX_COMPILE_ERROR",{code:n,error:e.message})}}}const d=e.timeoutMs??this.defaultTimeoutMs;let p;try{p=await this.runBounded(o,u,d,e.abortSignal)}catch(e){if(e instanceof Yt)throw e;const t=e.message;if(t.includes("timed out")||t.includes("timeout"))throw new Yt(`Code execution timed out after ${d} ms`,"GRAPH_CODE_SANDBOX_TIMEOUT",{timeoutMs:d});if(t.includes("memory")||t.includes("heap"))throw new Yt(`Code exceeded the memory limit of ${this.defaultMemoryMb} MB`,"GRAPH_CODE_SANDBOX_MEMORY_LIMIT",{memoryMb:this.defaultMemoryMb});throw new Yt("Code execution failed: "+t,"GRAPH_CODE_SANDBOX_RUNTIME_ERROR",{code:n,error:t})}if("string"!=typeof p)throw new Yt("Code sandbox returned an unexpected non-string result","GRAPH_CODE_SANDBOX_UNEXPECTED_RESULT",{result:p});return JSON.parse(p).v}finally{u.release(),c.dispose()}}async runBounded(e,t,o,n){const i=e.run(t,{timeout:o,promise:!0});i.catch(()=>{});const r=[i];let a,s;try{return r.push(new Promise((e,t)=>{a=setTimeout(()=>{t(new Yt(`Code execution timed out after ${o} ms`,"GRAPH_CODE_SANDBOX_TIMEOUT",{timeoutMs:o}))},o+100)})),n&&r.push(new Promise((e,t)=>{const i=()=>{const e="timeout"===n.reason;t(new Yt(e?`Code execution timed out after ${o} ms`:"Code execution aborted",e?"GRAPH_CODE_SANDBOX_TIMEOUT":"GRAPH_CODE_SANDBOX_ABORTED",{timeoutMs:o,reason:n.reason}))};n.aborted?i():(n.addEventListener("abort",i,{once:!0}),s=()=>n.removeEventListener("abort",i))})),await Promise.race(r)}finally{a&&clearTimeout(a),s?.()}}async injectConsole(e,t){const o=new H.Reference((e,o)=>{let n;try{n=JSON.parse(o)}catch{n=[o]}const i=n.map(e=>"string"==typeof e?e:JSON.stringify(e)).join(" "),r=1===n.length?n[0]:n;switch(e){case"log":case"info":default:t.info(i,r);break;case"warn":t.warn(i,r);break;case"error":t.error(i,r);break;case"debug":case"dir":case"dirxml":case"table":t.debug(i,r);break;case"trace":t.trace(i,r);break;case"group":case"groupCollapsed":t.debug("[group] "+i,r);break;case"groupEnd":t.debug("[groupEnd]",void 0);break;case"time":case"timeEnd":case"timeLog":case"count":case"countReset":t.debug(`[${e}] ${i}`,r);break;case"assert":n[0]||t.error("Assertion failed: "+i,r);case"clear":}});await e.evalClosure("\n function __ser() {\n var out = [];\n for (var i = 0; i < arguments.length; i++) {\n var a = arguments[i];\n try { out.push(typeof a === 'object' ? JSON.parse(JSON.stringify(a)) : a); }\n catch (e) { out.push(String(a)); }\n }\n return JSON.stringify(out);\n }\n function __call(level) {\n return function() {\n $0.applySync(undefined, [level, __ser.apply(null, arguments)]);\n };\n }\n globalThis.console = {\n log: __call('log'),\n info: __call('info'),\n warn: __call('warn'),\n error: __call('error'),\n debug: __call('debug'),\n trace: __call('trace'),\n dir: __call('dir'),\n dirxml: __call('dirxml'),\n table: __call('table'),\n group: __call('group'),\n groupCollapsed: __call('groupCollapsed'),\n groupEnd: __call('groupEnd'),\n time: __call('time'),\n timeEnd: __call('timeEnd'),\n timeLog: __call('timeLog'),\n assert: __call('assert'),\n count: __call('count'),\n countReset: __call('countReset'),\n clear: __call('clear')\n };\n ",[o]),o.release()}}class hn extends k{constructor(e){super(e,hn.name,500)}}class fn extends _{constructor(e){super(e),this.name=fn.name}}class gn extends _{constructor(e){super(e),this.name=gn.name}}class mn{constructor(e,t,o={}){this.kind=e,this.declarations=new Map,this.implementations=new Map;for(const e of t){if("string"!=typeof e?.name||!e.name)throw new hn(`Method declaration for kind '${this.kind}' is missing a name`);if(this.declarations.has(e.name))throw new hn(`Kind '${this.kind}' declares duplicate method '${e.name}'`);this.declarations.set(e.name,e)}for(const[e,t]of Object.entries(o)){if("function"!=typeof t)throw new hn(`Method implementation '${e}' for kind '${this.kind}' is not a function`);if(!this.declarations.has(e))throw new hn(`Kind '${this.kind}' implements method '${e}' which is not declared by its manifest`);this.implementations.set(e,t)}for(const e of this.declarations.keys())if(!this.implementations.has(e))throw new hn(`Kind '${this.kind}' declares method '${e}' with no implementation`)}has(e){return this.declarations.has(e)}getDeclaration(e){const t=this.declarations.get(e);if(!t)throw new gn(`Kind '${this.kind}' does not declare method '${e}'`);return t}get(e){return this.getDeclaration(e),this.implementations.get(e)}list(){return[...this.declarations.values()].sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}}function yn(e,t){if(!t)return;let o=e;for(const e of t.split(".")){if(!o||"object"!=typeof o)return;o=o[e]}return o}function wn(e,t,o){const n=yn(t,e.itemIdPath),i=e.itemLabelPath?yn(t,e.itemLabelPath):void 0;return{id:"string"==typeof n&&n||"number"==typeof n&&Number.isFinite(n)&&n+""||o+"",label:"string"==typeof i?i:void 0}}function bn(e,t){switch(t){case"input":return e.inputs;case"output":return e.outputs;default:return e.connections}}function vn(e,t){const o={inputs:[],outputs:[],connections:[]},n={input:new Set((e.inputs??[]).map(e=>e.id)),output:new Set((e.outputs??[]).map(e=>e.id)),connection:new Set((e.connections??[]).map(e=>e.id))},i=(e,t)=>{const o=n[e];return!o.has(t)&&(o.add(t),!0)};for(const n of e.dynamicPorts??[])if("repeatFromParameter"===n.type){const e=t[n.parameter];if(!Array.isArray(e))continue;const r=bn(o,n.direction);e.forEach((e,t)=>{const{id:o,label:a}=wn(n,e,t),s=(d={id:o,index:t,label:a??o},n.portIdTemplate.replaceAll("${id}",d.id).replaceAll("${index}",d.index+"").replaceAll("${label}",d.label));var d;if(!i(n.direction,s))return;const l=n.defaultPort?Ue(n.defaultPort):{id:s,label:a??s,direction:n.direction};l.id=s,l.direction=n.direction,a&&(l.label=a),r.push(l)})}else if("togglePort"===n.type){if(t[n.parameter]!==n.equals)continue;const e=Ue(n.port);if(!i(e.direction,e.id))continue;bn(o,e.direction).push(e)}return o}function In(e,t){const o=vn(e,t),n={kind:e.kind,display:e.display,inputs:[...e.inputs,...o.inputs],outputs:[...e.outputs,...o.outputs],parameters:e.parameters},i=[...e.connections??[],...o.connections];return i.length&&(n.connections=i),e.dynamicPorts?.length&&(n.dynamicPorts=e.dynamicPorts),e.credentials?.length&&(n.credentials=e.credentials),e.capabilities?.length&&(n.capabilities=e.capabilities),e.policies&&(n.policies=e.policies),e.metadata&&(n.metadata=e.metadata),e.namespaces?.length&&(n.namespaces=e.namespaces),Ue(n)}class En{async resolve(e,t,o,n,i){if(o){const r=await o(n,i);if(!(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.kind&&"object"==typeof t.display&&null!==t.display&&Array.isArray(t.inputs)&&Array.isArray(t.outputs)&&Array.isArray(t.parameters)})(r))throw new hn(`resolveManifest provider for kind '${e}' returned a value that does not conform to GraphResolvedNodeManifest`);if(!Ge(r))throw new hn(`resolveManifest provider for kind '${e}' returned a non-JSON-safe resolved manifest`);const a=Ue(r);return!a.namespaces?.length&&t.namespaces?.length&&(a.namespaces=t.namespaces.slice()),a}return In(t,n.parameters??{})}}const Nn=["edge","literal","expression"];function On(e){return Nn.includes(e)}function An(e,t,o){if("string"!=typeof o||!o)throw new hn(`Manifest for kind '${e}' has a ${t} with an empty port id`);if(Te(o))throw new hn(`Manifest for kind '${e}' has a ${t} with unsafe port id '${o}'`)}let xn=class extends U{constructor(){super(),this.entries=new Map,this.resolver=new En,this.fallbackContext=new j}withContext(e){return e[e.length-1]instanceof j?e:[this.fallbackContext]}register(e,t={},...o){const{log:n}=this.logCtx(this.withContext(o),"register").for(this.register);n.debug(`Registering graph node kind '${e?.manifest?.kind??"unknown"}'`),(e=>{if(!e||"object"!=typeof e)throw new hn("Graph node registration is required");if(!e.manifest||"object"!=typeof e.manifest)throw new hn("Graph node registration is missing a manifest");if(!e.executor||"function"!=typeof e.executor.execute)throw new hn(`Graph node registration for kind '${e.manifest?.kind+""}' is missing an executor`)})(e);const i=e.manifest;if("string"!=typeof i.kind||!i.kind.trim())throw new hn("Graph node manifest kind is required and must be a non-empty string");const r=i.kind;if(this.entries.has(r)&&!t.replace)throw new hn(`Graph node kind '${r}' is already registered; pass { replace: true } to replace it`);try{gt(i)}catch(e){throw new hn(`Manifest for kind '${r}' is not JSON-serializable: ${e.message}`)}((e,t)=>{const o=[["input",t.inputs],["output",t.outputs],["connection",t.connections??[]]];for(const[t,n]of o){const o=new Set;for(const i of n){if(An(e,t+" port",i?.id),o.has(i.id))throw new hn(`Manifest for kind '${e}' declares duplicate static ${t} port id '${i.id}'`);if(o.add(i.id),void 0!==i.defaultMode&&!On(i.defaultMode))throw new hn(`Manifest for kind '${e}' declares invalid default binding mode '${i.defaultMode+""}' on ${t} port '${i.id}'`)}}})(r,i);const a=((e,t)=>{const o=new Set;for(const n of t.parameters){const t=n?.id;if("string"!=typeof t||!t)throw new hn(`Manifest for kind '${e}' has a parameter with an empty id`);if(Te(t))throw new hn(`Manifest for kind '${e}' has a parameter with unsafe id '${t}'`);if(o.has(t))throw new hn(`Manifest for kind '${e}' declares duplicate parameter id '${t}'`);o.add(t)}return o})(r,i);((e,t,o)=>{for(const n of t.dynamicPorts??[]){if(!n||"string"!=typeof n.parameter||!n.parameter)throw new hn(`Manifest for kind '${e}' has a dynamic-port rule without a parameter reference`);if(!o.has(n.parameter))throw new hn(`Manifest for kind '${e}' has a dynamic-port rule referencing missing parameter '${n.parameter}'`);if("togglePort"===n.type){if(!n.port)throw new hn(`Manifest for kind '${e}' has a togglePort rule without a port`);An(e,"togglePort rule port",n.port.id)}if("repeatFromParameter"===n.type&&"string"!=typeof n.portIdTemplate)throw new hn(`Manifest for kind '${e}' has a repeatFromParameter rule without a portIdTemplate`)}})(r,i,a),((e,t)=>{for(const o of t.credentials??[]){if(!pt(o))throw new hn(`Manifest for kind '${e}' has a malformed credential requirement`);if(!o.type)throw new hn(`Manifest for kind '${e}' has a credential requirement with an empty type`)}})(r,i),((e,t)=>{for(const o of t.methods??[])if(!yt(o))throw new hn(`Manifest for kind '${e}' has a malformed method declaration`)})(r,i);const s=new mn(r,i.methods??[],e.methods??{});return this.entries.set(r,{registration:e,methods:s,placeholderManifest:!1}),this}registerExecutor(e,t,...o){const{log:n}=this.logCtx(this.withContext(o),"registerExecutor").for(this.registerExecutor);if(n.debug(`Registering graph executor for kind '${e}'`),"string"!=typeof e||!e.trim())throw new hn("Graph executor kind is required");if(!t||"function"!=typeof t.execute)throw new hn(`Executor registered for kind '${e}' is missing an execute method`);const i=this.entries.get(e);if(i)return i.registration={...i.registration,executor:t},this;const r={kind:e,display:{name:e},inputs:[],outputs:[],parameters:[],policies:{allowUndeclaredParameters:!0,allowUnknownOutputs:!0}};return this.entries.set(e,{registration:{manifest:r,executor:t},methods:new mn(e,[],{}),placeholderManifest:!0}),this}unregister(e,...t){const{log:o}=this.logCtx(this.withContext(t),"unregister").for(this.unregister);return o.debug(`Unregistering graph node kind '${e}'`),this.entries.delete(e),this}has(e,...t){return this.logCtx(this.withContext(t),"has").for(this.has),this.entries.has(e)}entry(e){const t=this.entries.get(e);if(!t)throw new fn(`No graph node kind '${e}' is registered in the catalogue`);return t}getManifest(e,...t){return this.logCtx(this.withContext(t),"getManifest").for(this.getManifest),Ue(this.entry(e).registration.manifest)}getExecutor(e,...t){return this.logCtx(this.withContext(t),"getExecutor").for(this.getExecutor),this.entry(e).registration.executor}getMethodDeclaration(e,t,...o){return this.logCtx(this.withContext(o),"getMethodDeclaration").for(this.getMethodDeclaration),this.entry(e).methods.getDeclaration(t)}getMethod(e,t,...o){return this.logCtx(this.withContext(o),"getMethod").for(this.getMethod),this.entry(e).methods.getDeclaration(t),this.entry(e).methods.get(t)}listMethodDeclarations(e,...t){return this.logCtx(this.withContext(t),"listMethodDeclarations").for(this.listMethodDeclarations),this.entry(e).methods.list()}listManifests(e,...t){this.logCtx(this.withContext(t),"listManifests").for(this.listManifests);const o=[...this.entries.keys()].sort(),n=e?.categories?.length?new Set(e.categories):void 0,i=e?.kinds?.length?new Set(e.kinds):void 0,r=[];for(const e of o){if(i&&!i.has(e))continue;const o=this.getManifest(e,...t);n&&!n.has(o.display.category??"")||r.push(o)}return r}listKinds(...e){return this.logCtx(this.withContext(e),"listKinds").for(this.listKinds),[...this.entries.keys()].sort()}get size(){return this.entries.size}async resolveManifest(e,t,o,...n){this.logCtx(this.withContext(n),"resolveManifest").for(this.resolveManifest);const i=this.entry(e);return this.resolver.resolve(e,i.registration.manifest,i.registration.resolveManifest,t,o)}};xn=D([G(),P("design:paramtypes",[])],xn);let kn=class extends U{constructor(e=new xn){super(),this.catalogue=e}get catalog(){return this.catalogue}register(e,t,...o){const{log:n}=this.logCtx(o,"register").for(this.register);if(n.debug(`Registering graph executor for kind '${e}'`),!e)throw new Yt("Graph executor kind is required");return this.catalogue.registerExecutor(e,t,...o),this}unregister(e,...t){const{log:o}=this.logCtx(t,"unregister").for(this.unregister);return o.debug(`Unregistering graph executor for kind '${e}'`),this.catalogue.unregister(e,...t),this}has(e,...t){return this.logCtx(t,"has").for(this.has),this.catalogue.has(e,...t)}resolve(e,...t){this.logCtx(t,"resolve").for(this.resolve);try{return this.catalogue.getExecutor(e,...t)}catch(t){if(t instanceof fn)throw new Yt(`No graph executor registered for kind '${e}'`,"GRAPH_EXECUTOR_NOT_FOUND",{kind:e});throw t}}};kn=D([G(),P("design:paramtypes",[xn])],kn);let _n=class extends U{constructor(e,t){super(),this.registry=e,this.defaultExecutor=t}resolve(e,...t){const{log:o}=this.logCtx(t,"resolve").for(this.resolve);return o.debug(`Resolving graph executor for kind '${e}'`),this.registry.has(e,...t)?this.registry.resolve(e,...t):this.defaultExecutor?this.defaultExecutor:this.registry.resolve(e,...t)}};function Dn(e){return e}function Pn(e){return e.methods??[]}function $n(e){if(!e)return;const t={...e.metadata??{},...e.parameters??{},...e.state??{}};return e.loop&&(t.loop=e.loop),t}_n=D([G(),P("design:paramtypes",[Function,Object])],_n);class Sn extends w{constructor(e){super(),w.fromModel(this,e)}execute(e,t){throw new Yt(`Graph node kind '${this.constructor.name}' does not implement execute`,"GRAPH_NODE_EXECUTE_NOT_IMPLEMENTED",{kind:this.constructor.name})}static applyMetadata(e){return null}static instantiate(e){return new this(e)}}let Rn=class extends Sn{execute(e,t){throw new ro(e.inputs.value)}};function Cn(e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack,code:e.graphCode??("number"==typeof e.code?e.code+"":e.code)}:{name:"UnknownError",message:e+""}}D([b(),r("ngx-decaf-crud-field",{label:"graph.node.flow_control.break.fields.value.label",placeholder:"graph.node.flow_control.break.fields.value.placeholder",type:"textarea"}),$e({handle:"value"}),P("design:type",Object)],Rn.prototype,"value",void 0),Rn=D([De("core.flow.break",{kind:"core.flow.break",category:"Flow Control",color:"#f59e0b",icon:"ti-square-arrow-right",width:96,height:96,labels:["flow","break","loop","control"],metadata:{title:"graph.node.flow_control.break.name",description:"graph.node.flow_control.break.description"}}),E()],Rn);let Tn=class extends Sn{async execute(e,t){const o=t.node.errorBoundary;if(!o?.try)return{result:e.inputs.value??e.inputs};const n=t.engine;if(!n)throw new Yt("errorBoundary node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");try{const i=await n.execute(o.try,e.inputs,{parentRunId:t.runId,path:[...t.path,"try"]}),r=Object.values(i.nodeResults).find(e=>e.status===ae.FAILED);if(r)throw new Yt(r.error?.message??"error boundary try body failed",r.error?.code??"GRAPH_ERROR_BOUNDARY",r.error?.details);return{result:i.outputs.result??i.outputs}}catch(i){let r=i;if(o.catch){const a=await n.execute(o.catch,{...e.inputs,error:Cn(i)},{parentRunId:t.runId,path:[...t.path,"catch"]});r=a.outputs.error??a.outputs}return{error:r}}finally{o.finally&&await n.execute(o.finally,e.inputs,{parentRunId:t.runId,path:[...t.path,"finally"]})}}};D([b(),r("ngx-decaf-crud-field",{label:"graph.node.flow_control.error_boundary.fields.value.label",placeholder:"graph.node.flow_control.error_boundary.fields.value.placeholder",type:"textarea"}),$e({handle:"value"}),P("design:type",Object)],Tn.prototype,"value",void 0),D([Se({handle:"result"}),P("design:type",Object)],Tn.prototype,"result",void 0),D([Se({handle:"error"}),P("design:type",Object)],Tn.prototype,"error",void 0),Tn=D([De("core.flow.errorBoundary",{kind:"core.flow.errorBoundary",category:"Flow Control",color:"#f59e0b",icon:"ti-shield-check",width:96,height:96,labels:["flow","error","try-catch"],metadata:{title:"graph.node.flow_control.error_boundary.name",description:"graph.node.flow_control.error_boundary.description",finally:!1}}),E()],Tn);let Ln=class extends Sn{execute(e){const t=e.inputs.value??e.inputs;return!1===this.approved?{rejected:t}:{approved:t}}};D([b(),$e({handle:"value"}),P("design:type",Object)],Ln.prototype,"value",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.flow_control.human_approval.fields.message.label",placeholder:"graph.node.flow_control.human_approval.fields.message.placeholder",type:"textarea"}),$e({handle:"message",userControlled:!0}),P("design:type",String)],Ln.prototype,"message",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.flow_control.human_approval.fields.approved.label",type:"checkbox"}),$e({handle:"approved",userControlled:!0}),P("design:type",Boolean)],Ln.prototype,"approved",void 0),D([Se({handle:"approved"}),P("design:type",Object)],Ln.prototype,"approvedOut",void 0),D([Se({handle:"rejected"}),P("design:type",Object)],Ln.prototype,"rejectedOut",void 0),Ln=D([De("core.flow.humanApproval",{kind:"core.flow.humanApproval",category:"Flow Control",color:"#f59e0b",icon:"ti-user-check",width:96,height:96,labels:["flow","approval","suspend"],metadata:{title:"graph.node.flow_control.human_approval.name",description:"graph.node.flow_control.human_approval.description",approvers:[],timeoutMs:864e5}}),E()],Ln);class jn{evaluate(e,t){switch(e.op){case"eq":return this.resolveValue(e.left,t)===this.resolveValue(e.right,t);case"neq":return this.resolveValue(e.left,t)!==this.resolveValue(e.right,t);case"gt":return Number(this.resolveValue(e.left,t))>Number(this.resolveValue(e.right,t));case"gte":return Number(this.resolveValue(e.left,t))>=Number(this.resolveValue(e.right,t));case"lt":return Number(this.resolveValue(e.left,t))<Number(this.resolveValue(e.right,t));case"lte":return Number(this.resolveValue(e.left,t))<=Number(this.resolveValue(e.right,t));case"and":return e.conditions.every(e=>this.evaluate(e,t));case"or":return e.conditions.some(e=>this.evaluate(e,t));case"not":return!this.evaluate(e.condition,t);case"exists":return void 0!==this.resolveValue(e.value,t)&&null!==this.resolveValue(e.value,t);default:throw new Yt(`Unknown ConditionExpression op '${e.op}'`,"GRAPH_UNKNOWN_CONDITION_OP",{expr:e})}}resolveValue(e,t){if("const"in e)return e.const;if("path"in e&&!("step"in e))return this.resolvePath(e.path,t);if("step"in e&&"path"in e){const o=t?.nodes;if(o&&"object"==typeof o){const t=o[e.step];return this.resolvePath(e.path,t)}return this.resolvePath(e.path,t)}throw new Yt("Invalid ExprValue: must have `const`, `path`, or `step`+`path`","GRAPH_INVALID_EXPR_VALUE",{ref:e})}resolvePath(e,t){if(!e)return t;const o=e.split(".");let n=t;for(const e of o){if(null==n)return;n=n[e]}return n}}let Mn=class extends Sn{execute(e){const t=e.inputs,o=t.value??t;if(!this.condition)throw new Yt("If node has no condition configured","GRAPH_IF_NO_CONDITION",{input:t});const n=(new jn).evaluate(this.condition,((e,t)=>t===e||"object"!=typeof t||null===t||Array.isArray(t)?e:{...t,...e})(t,o));if(n)return{then:o};if(!0===this.else)return{else:o};throw new Yt("If node condition evaluated to false and the else branch is disabled","GRAPH_IF_ELSE_DISABLED",{condition:this.condition})}};async function Gn(e,t,o,n){if("object"==typeof(i=e)&&null!==i&&"type"in i&&"code"===i.type){const t=n.engine?.codeSandboxEvaluator;if(!t)throw new Yt("Code conditions require a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator","GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{code:e.code});await n.log("Evaluating code condition",{language:e.language??"javascript"});const i=n.metadata;return!!await t.evaluate({code:e.code,language:e.language,input:o,vars:i?.vars??void 0,item:i?.item,index:i?.index,nodes:i?.nodes??void 0,logger:n.logger,abortSignal:n.abortSignal})}var i;if((e=>"object"==typeof e&&null!==e&&"op"in e&&"string"==typeof e.op)(e))return(new jn).evaluate(e,t);throw new Yt("Unknown switch case condition type \u2014 must be ConditionExpression (op) or CodeCondition (type: 'code')","GRAPH_UNKNOWN_SWITCH_CONDITION",{condition:e})}D([b(),r("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.value.label",placeholder:"graph.node.flow_control.if.fields.value.placeholder",type:"textarea"}),$e({handle:"value"}),P("design:type",Object)],Mn.prototype,"value",void 0),D([b(),Se({handle:"then"}),P("design:type",Object)],Mn.prototype,"then",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.condition.label",placeholder:"graph.node.flow_control.if.fields.condition.placeholder",type:"code"}),$e({handle:"condition",userControlled:!0,type:"object"}),P("design:type",Object)],Mn.prototype,"condition",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.else.label",type:"checkbox"}),$e({handle:"else",userControlled:!0}),P("design:type",Boolean)],Mn.prototype,"else",void 0),Mn=D([De("core.flow.if",{kind:"core.flow.if",category:"Flow Control",color:"#f59e0b",icon:"ti-arrows-split-2",width:96,height:96,labels:["flow","conditional","branch"],metadata:{title:"graph.node.flow_control.if.name",description:"graph.node.flow_control.if.description"}}),E()],Mn);let Un=class extends Sn{async execute(e,t){const o=((e,t)=>{const o={cases:t.cases??[],defaultPort:t.defaultPort??"default",hasDefault:!0===t.hasDefault},n=e.node.metadata?.switch;return n&&Array.isArray(n.cases)?{cases:n.cases,defaultPort:n.defaultPort??o.defaultPort,hasDefault:!0===n.hasDefault||o.hasDefault}:o})(t,this),n=o.cases,i=e.inputs,r=i.value??i,a=((e,t)=>t===e||"object"!=typeof t||null===t||Array.isArray(t)?e:{...t,...e})(i,r);for(const e of n)if(await Gn(e.condition,a,i,t))return{[e.outputPort]:r};if(!0!==o.hasDefault)throw new Yt("No switch case matched and default port is not enabled","GRAPH_SWITCH_NO_MATCH",{cases:n.map(e=>e.id)});const s=o.defaultPort??"default";return{[s]:r}}static applyMetadata(e){const t=xe(this),o=e.defaultPort??"default",n=!0===e.hasDefault,i=t.ports.filter(t=>!e.cases.some(e=>e.outputPort===t.property)),r=i.filter(e=>e.property!==o),a=i.find(e=>e.property===o),s=[...r,...e.cases.map(e=>({property:e.outputPort,name:e.label,direction:Q.OUTPUT,label:e.label,required:!1,hidden:!1,path:e.outputPort}))];return n&&a&&s.push(a),{ports:s,size:ee(t,{cases:e.cases.length}),dataPatch:{switchMetadata:e}}}};D([b(),r("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.value.label",placeholder:"graph.node.flow_control.switch.fields.value.placeholder",type:"textarea"}),$e({handle:"value"}),P("design:type",Object)],Un.prototype,"value",void 0),D([b(),Se({handle:"default"}),P("design:type",Object)],Un.prototype,"default",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.cases.label",type:"collection"}),P("design:type",Object)],Un.prototype,"cases",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.hasDefault.label",type:"checkbox"}),P("design:type",Boolean)],Un.prototype,"hasDefault",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.defaultPort.label",type:"text"}),P("design:type",String)],Un.prototype,"defaultPort",void 0),Un=D([De("core.flow.switch",{kind:"core.flow.switch",category:"Flow Control",color:"#f59e0b",icon:"ti-arrows-shuffle",width:120,height:140,sizeRules:[{type:"parameterCount",parameter:"cases",dimension:"height",perItem:24}],labels:["flow","switch","multi-branch"],metadata:{title:"graph.node.flow_control.switch.name",description:"graph.node.flow_control.switch.description"}}),E()],Un);const Fn={maxDocumentBytes:2e6,maxNestingDepth:10,maxNodes:500,maxEdges:1e3},Bn=o.accumulate({graph:{workflows:{limits:{...Fn},allowAnonymousAccess:!1},execution:{maxCodeTimeoutMs:Ht}}}),qn=1e3;function Vn(e,t){const o="number"==typeof e?e:Number(e);return Number.isFinite(o)&&o>0?Math.min(Math.floor(o),t):1e3}const Wn=["javascript","typescript"],Hn="javascript";let Kn=class extends w{constructor(){super(...arguments),this.language=Hn}};D([b(),r("ngx-decaf-crud-field",{label:"graph.node.utility.code.fields.language.label",type:"select"}),N([...Wn]),v(String),P("design:type",String)],Kn.prototype,"language",void 0),D([b(),r("code-editor",{label:"graph.node.utility.code.fields.code.label",placeholder:"graph.node.utility.code.fields.code.placeholder"}),$e({handle:"code"}),P("design:type",String)],Kn.prototype,"code",void 0),D([d(),$e({handle:"data"}),P("design:type",Object)],Kn.prototype,"data",void 0),Kn=D([E()],Kn);let zn=class extends Sn{async execute(e,t){const o=e.inputs,n=this.input,i=o.code??e.parameters?.code??n?.code??this.defaultCode,r=n?.language??Hn;if(!i||"string"!=typeof i||0===i.trim().length)throw new Zt("Code node has no code to execute (input.code is empty)",{input:o});const a=t.engine?.codeSandboxEvaluator;if(!a)throw new Yt("Code node execution requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator","GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{code:i});const s=Bn.graph.execution?.maxCodeTimeoutMs??Ht,d=Vn(this.timeoutMs,s),l=t.metadata,c={code:i,language:r,input:o,vars:l?.vars??void 0,item:l?.item,index:l?.index,nodes:l?.nodes??void 0,logger:t.logger,timeoutMs:d,abortSignal:t.abortSignal};await t.log("Executing code node",{language:r,length:i.length,timeoutMs:d});const u=await a.evaluate(c);return await t.log("Code node executed",{hasResult:void 0!==u}),{result:u}}};D([b(),$e({handle:"input",model:Kn}),P("design:type",Kn)],zn.prototype,"input",void 0),D([O(1),A(Ht),r("ngx-decaf-crud-field",{label:"graph.node.utility.code.fields.timeoutMs.label",type:"number"}),$e({handle:"timeoutMs"}),P("design:type",Number)],zn.prototype,"timeoutMs",void 0),D([r("code-editor",{label:"graph.node.utility.code.fields.defaultCode.label",placeholder:"graph.node.utility.code.fields.defaultCode.placeholder"}),$e({handle:"defaultCode",userControlled:!0}),P("design:type",String)],zn.prototype,"defaultCode",void 0),D([b(),Se({handle:"result"}),P("design:type",Object)],zn.prototype,"result",void 0),zn=D([De("core.utility.code",{kind:"core.utility.code",category:"Utility",color:"#0d9488",icon:"ti-code",width:96,height:96,labels:["utility","code","sandbox","transform"],metadata:{title:"graph.node.utility.code.name",description:"graph.node.utility.code.description"}}),E()],zn);let Jn=class extends Sn{execute(e){return{value:e.inputs.value??e.inputs}}};D([b(),$e({handle:"value"}),P("design:type",Object)],Jn.prototype,"value",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.utility.delay.fields.timeoutMs.label",type:"number"}),$e({handle:"timeoutMs"}),P("design:type",Number)],Jn.prototype,"timeoutMs",void 0),D([b(),Se({handle:"value"}),P("design:type",Object)],Jn.prototype,"valueOut",void 0),Jn=D([De("core.flow.delay",{kind:"core.flow.delay",category:"Utility",color:"#0d9488",icon:"ti-clock-hour-4",width:96,height:96,labels:["flow","delay","wait"],metadata:{title:"graph.node.utility.delay.name",description:"graph.node.utility.delay.description"}}),E()],Jn);let Xn=class extends Sn{execute(e,t){const o=e.inputs.value,n=this.level??"info";return t.logger[n](this.message??"Log node",{value:o}),{value:o}}};D([b(),$e({handle:"value"}),P("design:type",Object)],Xn.prototype,"value",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.utility.log.fields.message.label",placeholder:"graph.node.utility.log.fields.message.placeholder",type:"textarea"}),$e({handle:"message"}),P("design:type",String)],Xn.prototype,"message",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.utility.log.fields.level.label",placeholder:"graph.node.utility.log.fields.level.placeholder",type:"text"}),$e({handle:"level",userControlled:!0}),P("design:type",String)],Xn.prototype,"level",void 0),D([b(),Se({handle:"value"}),P("design:type",Object)],Xn.prototype,"valueOut",void 0),Xn=D([De("core.flow.log",{kind:"core.flow.log",category:"Utility",color:"#0d9488",icon:"ti-terminal",width:96,height:96,labels:["flow","log","debug","utility"],metadata:{title:"graph.node.utility.log.name",description:"graph.node.utility.log.description"}}),E()],Xn);let Yn=class extends Sn{execute(e){return{result:{mapped:e.inputs.value??e.inputs}}}};D([b(),r("ngx-decaf-crud-field",{label:"graph.node.utility.map.fields.value.label",placeholder:"graph.node.utility.map.fields.value.placeholder",type:"textarea"}),$e({handle:"value"}),P("design:type",Object)],Yn.prototype,"value",void 0),D([b(),Se({handle:"result"}),P("design:type",Object)],Yn.prototype,"result",void 0),Yn=D([De("core.utility.map",{kind:"core.utility.map",category:"Utility",color:"#0d9488",icon:"ti-arrows-right-left",width:96,height:96,labels:["utility","map","transform"],metadata:{title:"graph.node.utility.map.name",description:"graph.node.utility.map.description",mapper:{}}}),E()],Yn);let Qn=class extends Sn{execute(e,t){const o=e.inputs.value,n=this.level??"info";return t.logger[n](this.message??"Log node",{value:o}),{value:o}}};D([b(),$e({handle:"value"}),P("design:type",Object)],Qn.prototype,"value",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.utility.utility_log.fields.message.label",placeholder:"graph.node.utility.utility_log.fields.message.placeholder",type:"textarea"}),$e({handle:"message"}),P("design:type",String)],Qn.prototype,"message",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.utility.utility_log.fields.level.label",placeholder:"graph.node.utility.utility_log.fields.level.placeholder"}),$e({handle:"level",userControlled:!0,type:"string"}),P("design:type",String)],Qn.prototype,"level",void 0),D([b(),Se({handle:"value"}),P("design:type",Object)],Qn.prototype,"valueOut",void 0),Qn=D([De("core.utility.log",{kind:"core.utility.log",category:"Utility",color:"#0d9488",icon:"ti-terminal",width:96,height:96,labels:["utility","log","debug","observability"],metadata:{title:"graph.node.utility.utility_log.name",description:"graph.node.utility.utility_log.description"}}),E()],Qn);let Zn=class extends Sn{execute(e){return{message:e.inputs.message??null,sessionId:e.inputs.sessionId??null,userId:e.inputs.userId??null}}};D([b(),Se({handle:"message"}),P("design:type",String)],Zn.prototype,"message",void 0),D([b(),Se({handle:"sessionId"}),P("design:type",String)],Zn.prototype,"sessionId",void 0),D([b(),Se({handle:"userId"}),P("design:type",String)],Zn.prototype,"userId",void 0),Zn=D([De("core.trigger.chat",{kind:"core.trigger.chat",category:"Trigger",color:"#3b82f6",icon:"ti-message-circle",width:96,height:96,labels:["trigger","chat","entrypoint"],metadata:{title:"graph.node.trigger.chat.name",description:"graph.node.trigger.chat.description",trigger:{type:"chat"}}}),E()],Zn);let ei=class extends Sn{execute(e){return{payload:e.inputs.payload??null}}};D([b(),Se({handle:"payload"}),P("design:type",Object)],ei.prototype,"payload",void 0),ei=D([De("core.trigger.event",{kind:"core.trigger.event",category:"Trigger",color:"#3b82f6",icon:"ti-broadcast",width:96,height:96,labels:["trigger","event","bus"],metadata:{title:"graph.node.trigger.event.name",description:"graph.node.trigger.event.description",trigger:{type:"event",topic:"default"}}}),E()],ei);let ti=class extends Sn{execute(e){return{payload:e.inputs.payload??null}}};D([b(),$e({handle:"schema"}),r("ngx-decaf-model-builder",{label:"graph.node.trigger.form.fields.schema.label",placeholder:"graph.node.trigger.form.fields.schema.placeholder"}),P("design:type",Object)],ti.prototype,"schema",void 0),D([b(),Se({handle:"payload"}),P("design:type",Object)],ti.prototype,"payload",void 0),ti=D([De("core.trigger.form",{kind:"core.trigger.form",category:"Trigger",color:"#3b82f6",icon:"ti-forms",width:96,height:96,labels:["trigger","form","public"],metadata:{title:"graph.node.trigger.form.name",description:"graph.node.trigger.form.description",trigger:{type:"form",fields:[]}}}),E()],ti);let oi=class extends Sn{execute(e){return{payload:e.inputs.payload??null}}};D([b(),Se({handle:"payload"}),P("design:type",Object)],oi.prototype,"payload",void 0),oi=D([De("core.trigger.manual",{kind:"core.trigger.manual",category:"Trigger",color:"#3b82f6",icon:"ti-hand-click",width:96,height:96,labels:["trigger","manual","entrypoint"],metadata:{title:"graph.node.trigger.manual.name",description:"graph.node.trigger.manual.description",trigger:{type:"manual",inputSchema:{}}}}),E()],oi);let ni=class extends Sn{execute(e){return{payload:e.inputs.payload??null}}};D([b(),$e({handle:"cron"}),r("app-cron-selector-field",{label:"graph.node.trigger.schedule.fields.cron.label",placeholder:"graph.node.trigger.schedule.fields.cron.placeholder"}),P("design:type",String)],ni.prototype,"cron",void 0),D([b(),Se({handle:"payload"}),P("design:type",Object)],ni.prototype,"payload",void 0),ni=D([De("core.trigger.schedule",{kind:"core.trigger.schedule",category:"Trigger",color:"#3b82f6",icon:"ti-calendar-time",width:96,height:96,labels:["trigger","schedule","cron"],metadata:{title:"graph.node.trigger.schedule.name",description:"graph.node.trigger.schedule.description",trigger:{type:"schedule",schedule:"0 * * * *",timezone:"UTC"}}}),E()],ni);let ii=class extends Sn{execute(e){return{payload:e.inputs.payload??null}}};D([b(),$e({handle:"schema"}),r("ngx-decaf-model-builder",{label:"graph.node.trigger.webhook.fields.schema.label",placeholder:"graph.node.trigger.webhook.fields.schema.placeholder"}),P("design:type",Object)],ii.prototype,"schema",void 0),D([b(),Se({handle:"payload"}),P("design:type",Object)],ii.prototype,"payload",void 0),ii=D([De("core.trigger.webhook",{kind:"core.trigger.webhook",category:"Trigger",color:"#3b82f6",icon:"ti-webhook",width:96,height:96,labels:["trigger","webhook","http"],metadata:{title:"graph.node.trigger.webhook.name",description:"graph.node.trigger.webhook.description",trigger:{type:"webhook",path:"/webhook",method:"POST",auth:"none",responseMode:"onReceived"}}}),E()],ii);let ri=class extends Sn{execute(e){return{response:"[Agent response] "+(e.inputs.prompt??""),actions:[]}}};D([b(),r("ngx-decaf-crud-field",{label:"graph.node.agent.agent.fields.prompt.label",placeholder:"graph.node.agent.agent.fields.prompt.placeholder",type:"textarea"}),$e({handle:"prompt"}),P("design:type",String)],ri.prototype,"prompt",void 0),D([b(),Se({handle:"response"}),P("design:type",String)],ri.prototype,"response",void 0),D([b(),Se({handle:"actions"}),P("design:type",Array)],ri.prototype,"actions",void 0),D([Re({category:"model",handle:"model"}),P("design:type",Object)],ri.prototype,"model",void 0),D([Re({category:"memory",handle:"memory"}),P("design:type",Object)],ri.prototype,"memory",void 0),D([Re({category:"workspace",handle:"workspace"}),P("design:type",Object)],ri.prototype,"workspace",void 0),ri=D([De("core.agent",{kind:"core.agent",category:"Agent",width:140,height:120,labels:["agent","ai","orchestrator"],metadata:{title:"graph.node.agent.agent.name",description:"graph.node.agent.agent.description",shape:"rectangle"}}),E()],ri);const ai=[ri];function si(e,t,o,n){const i=t??o;if(null==e)return Math.min(o,i);const r=Number(e);if(!Number.isFinite(r)||0>=r)throw new Zt(n+" loop maxIterations must be a positive finite number");return Math.min(Math.floor(r),i)}function di(e,t,o){const n=t.node.loop,i=t.metadata?.loop;if(!n?.body&&!i?.body)throw new Zt(o+" node is missing loop configuration (instance.loop.body)");const r=t=>{const o=e[t]??n?.[t]??i?.[t],r=Number(o);return void 0!==o&&Number.isFinite(r)?r:void 0},a=t=>{const o=e[t]??i?.[t];return"string"==typeof o?o:void 0};return{body:n?.body??i?.body,maxIterations:r("maxIterations"),timeoutMs:r("timeoutMs"),concurrency:r("concurrency"),condition:e.condition??i?.condition,inputPort:a("inputPort"),outputPort:a("outputPort"),itemPort:a("itemPort"),resultPort:a("resultPort"),statePort:a("statePort"),slice:r("slice")}}let li=class extends Sn{async execute(e,t){const o=di(this,t,"foreach"),n=e.inputs,i=n.items,r=si(o.maxIterations,t.limits?.maxForeachIterations,1e3,"foreach");if(!Array.isArray(i))throw new Zt("foreach input 'items' must be an array");const a=t.engine;if(!a)throw new Yt("foreach node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");const s=Number(n.slice??o.slice??1),d=Number.isFinite(s)&&s>0?Math.floor(s):1,l=d>1?Math.ceil(i.length/d):i.length;if(l>r)throw new eo(`foreach exceeded max iterations (${l} > ${r})`);const c=o.itemPort??"item",u=o.resultPort??"result",p=o.statePort??"state",h=o.body,f=[];let g=n.state,m=!1;await t.emit({type:le.LOOP_STARTED});for(let e=0;l>e;e++){await t.emit({type:le.LOOP_ITERATION_STARTED,iteration:e});const o=d>1?i.slice(e*d,e*d+d):i[e],n={[c]:o,index:e};d>1&&(n.slice=o),void 0!==g&&(n[p]=g);try{const i=await a.execute(h,n,{parentRunId:t.runId,path:[...t.path,"iteration:"+e],metadata:{item:o,index:e,slice:d},auth:t.auth},t);f.push(i.outputs[u]),void 0!==i.outputs[p]&&(g=i.outputs[p])}catch(o){if(o instanceof ro){const n=o.details?.value;void 0!==n&&f.push(n),m=!0,await t.emit({type:le.LOOP_ITERATION_COMPLETED,iteration:e,metadata:{broken:!0}});break}throw o}await t.emit({type:le.LOOP_ITERATION_COMPLETED,iteration:e})}await t.emit({type:le.LOOP_COMPLETED,metadata:{broken:m}});const y={results:f,completed:f,iterations:f.length,broken:m};return void 0!==g&&(y[p]=g),y}};D([b(),r("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.items.label",placeholder:"graph.node.loop.foreach.fields.items.placeholder",type:"textarea"}),$e({handle:"items"}),P("design:type",Array)],li.prototype,"items",void 0),D([b(),r("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.slice.label",placeholder:"graph.node.loop.foreach.fields.slice.placeholder",type:"number"}),$e({handle:"slice"}),P("design:type",Number)],li.prototype,"slice",void 0),D([b(),Se({handle:"item"}),P("design:type",Object)],li.prototype,"item",void 0),D([b(),Re({handle:"loop",connectionRules:{allowSelf:!0,maxConnections:1}}),P("design:type",Object)],li.prototype,"loop",void 0),D([b(),Se({handle:"completed"}),P("design:type",Array)],li.prototype,"completed",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.maxIterations.label",type:"number"}),$e({handle:"maxIterations",userControlled:!0}),P("design:type",Number)],li.prototype,"maxIterations",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.condition.label",type:"code"}),$e({handle:"condition",userControlled:!0}),P("design:type",Object)],li.prototype,"condition",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.itemPort.label",type:"text"}),$e({handle:"itemPort",userControlled:!0}),P("design:type",String)],li.prototype,"itemPort",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.resultPort.label",type:"text"}),$e({handle:"resultPort",userControlled:!0}),P("design:type",String)],li.prototype,"resultPort",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.statePort.label",type:"text"}),$e({handle:"statePort",userControlled:!0}),P("design:type",String)],li.prototype,"statePort",void 0),li=D([De("graph-foreach-loop-node",{kind:"core.loop.foreach",category:"Loop",color:"#eab308",icon:"ti-repeat",width:120,height:140,labels:["loop","iteration","foreach"],metadata:{title:"graph.node.loop.foreach.name",description:"graph.node.loop.foreach.description",loop:{maxIterations:100,itemPort:"item",resultPort:"result",slice:1}}}),E()],li);class ci{constructor(){this.expressionEvaluator=new jn}evaluate(e,t){if(this.isConditionExpression(e))return this.expressionEvaluator.evaluate(e,t);const o=this.resolveValue(e.left,t),n=e.right;switch(e.type){case Jt.TRUTHY:return!!o;case Jt.FALSY:return!o;case Jt.EQUALS:return o===n;case Jt.NOT_EQUALS:return o!==n;case Jt.GREATER_THAN:return Number(o)>Number(n);case Jt.GREATER_THAN_OR_EQUAL:return Number(o)>=Number(n);case Jt.LESS_THAN:return Number(n)>Number(o);case Jt.LESS_THAN_OR_EQUAL:return Number(n)>=Number(o);case Jt.EXISTS:return null!=o;case Jt.CUSTOM:throw new Yt("Custom condition evaluators are not supported in v1","GRAPH_CUSTOM_CONDITION_UNSUPPORTED");default:throw new Yt(`Unknown condition type '${e.type}'`,"GRAPH_UNKNOWN_CONDITION_TYPE",{condition:e})}}resolveValue(e,t){if(!e)return t;const o=e.split(".");let n=t;for(const e of o){if(null==n)return;n=n[e]}return n}isConditionExpression(e){return"string"==typeof e.op}}let ui=class extends Sn{async execute(e,t){const o=di(this,t,"until"),n=e.inputs,i=si(o.maxIterations,t.limits?.maxLoopIterations,100,"until"),r=o.condition;if(!r)throw new Zt("until node is missing a condition");const a=o.statePort??"state",s=o.inputPort??a,d=o.outputPort??a,l=o.body,c=t.engine;if(!c)throw new Yt("until node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");let u=n.state,p=0;await t.emit({type:le.LOOP_STARTED});let h=!1;do{if(p>=i)throw await t.emit({type:le.LOOP_LIMIT_REACHED,iteration:p}),new eo(`until loop exceeded max iterations (${i})`);await t.emit({type:le.LOOP_ITERATION_STARTED,iteration:p}),u=(await c.execute(l,{[s]:u,iteration:p},{parentRunId:t.runId,path:[...t.path,"iteration:"+p],auth:t.auth},t)).outputs[d],await t.emit({type:le.LOOP_ITERATION_COMPLETED,iteration:p});const e=(new ci).evaluate(r,u);await t.emit({type:le.LOOP_CONDITION_EVALUATED,iteration:p,payload:{result:e}}),p++,h=e}while(!h);return await t.emit({type:le.LOOP_COMPLETED}),{state:u,iterations:p}}};D([b(),r("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.state.label",placeholder:"graph.node.loop.until.fields.state.placeholder",type:"textarea"}),$e({handle:"state"}),P("design:type",Object)],ui.prototype,"state",void 0),D([b(),Se({handle:"state"}),P("design:type",Object)],ui.prototype,"stateOut",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.maxIterations.label",type:"number"}),$e({handle:"maxIterations",userControlled:!0}),P("design:type",Number)],ui.prototype,"maxIterations",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.condition.label",type:"code"}),$e({handle:"condition",userControlled:!0}),P("design:type",Object)],ui.prototype,"condition",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.statePort.label",type:"text"}),$e({handle:"statePort",userControlled:!0}),P("design:type",String)],ui.prototype,"statePort",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.inputPort.label",type:"text"}),$e({handle:"inputPort",userControlled:!0}),P("design:type",String)],ui.prototype,"inputPort",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.outputPort.label",type:"text"}),$e({handle:"outputPort",userControlled:!0}),P("design:type",String)],ui.prototype,"outputPort",void 0),ui=D([De("graph-until-loop-node",{kind:"core.loop.until",category:"Loop",color:"#eab308",icon:"ti-player-stop",width:96,height:96,labels:["loop","conditional","until"],metadata:{title:"graph.node.loop.until.name",description:"graph.node.loop.until.description",loop:{maxIterations:50,statePort:"state",condition:{type:"greaterThanOrEqual",left:"iteration",right:2}}}}),E()],ui);let pi=class extends Sn{async execute(e,t){const o=di(this,t,"while"),n=e.inputs,i=si(o.maxIterations,t.limits?.maxLoopIterations,100,"while"),r=o.condition;if(!r)throw new Zt("while node is missing a condition");const a=o.statePort??"state",s=o.inputPort??a,d=o.outputPort??a,l=o.body,c=t.engine;if(!c)throw new Yt("while node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");let u=n.state,p=0;for(await t.emit({type:le.LOOP_STARTED});(new ci).evaluate(r,u);){if(p>=i)throw await t.emit({type:le.LOOP_LIMIT_REACHED,iteration:p}),new eo(`while loop exceeded max iterations (${i})`);await t.emit({type:le.LOOP_CONDITION_EVALUATED,iteration:p,payload:{result:!0}}),await t.emit({type:le.LOOP_ITERATION_STARTED,iteration:p}),u=(await c.execute(l,{[s]:u,iteration:p},{parentRunId:t.runId,path:[...t.path,"iteration:"+p],auth:t.auth},t)).outputs[d],await t.emit({type:le.LOOP_ITERATION_COMPLETED,iteration:p}),p++}return await t.emit({type:le.LOOP_COMPLETED}),{state:u,iterations:p}}};D([b(),r("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.state.label",placeholder:"graph.node.loop.while.fields.state.placeholder",type:"textarea"}),$e({handle:"state"}),P("design:type",Object)],pi.prototype,"state",void 0),D([b(),Se({handle:"state"}),P("design:type",Object)],pi.prototype,"stateOut",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.maxIterations.label",type:"number"}),$e({handle:"maxIterations",userControlled:!0}),P("design:type",Number)],pi.prototype,"maxIterations",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.condition.label",type:"code"}),$e({handle:"condition",userControlled:!0}),P("design:type",Object)],pi.prototype,"condition",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.statePort.label",type:"text"}),$e({handle:"statePort",userControlled:!0}),P("design:type",String)],pi.prototype,"statePort",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.inputPort.label",type:"text"}),$e({handle:"inputPort",userControlled:!0}),P("design:type",String)],pi.prototype,"inputPort",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.outputPort.label",type:"text"}),$e({handle:"outputPort",userControlled:!0}),P("design:type",String)],pi.prototype,"outputPort",void 0),pi=D([De("graph-while-loop-node",{kind:"core.loop.while",category:"Loop",color:"#eab308",icon:"ti-arrows-loop",width:96,height:96,labels:["loop","conditional","while"],metadata:{title:"graph.node.loop.while.name",description:"graph.node.loop.while.description",loop:{maxIterations:50,statePort:"state",condition:{type:"lessThan",left:"iteration",right:3}}}}),E()],pi);let hi=class extends Sn{execute(e){const t=e.inputs;return{value:t?.value??null}}};D([Se({handle:"value",connectionRules:{allowMultiple:!0}}),P("design:type",Object)],hi.prototype,"value",void 0),hi=D([De("graph-input-value-node",{kind:"value",category:"Boundary",color:"#0f766e",icon:"ti-circle-plus",labels:["workflow","input","value"],metadata:{title:"graph.node.boundary.input.name",description:"graph.node.boundary.input.description"}}),E()],hi);let fi=class extends Sn{execute(e){return{}}};function gi(e,t,o,n={}){return{id:e,label:t,direction:o,...n}}function mi(e){const t=e,o=be(t),n=o?.metadata?.title;return Ct(t,n?{name:n}:{})}D([b(),$e({handle:"value"}),P("design:type",Object)],fi.prototype,"value",void 0),fi=D([De("graph-output-value-node",{kind:"result",category:"Boundary",color:"#0f766e",icon:"ti-circle-minus",width:96,height:96,labels:["workflow","output","value"],metadata:{title:"graph.node.boundary.output.name",description:"graph.node.boundary.output.description"}}),E()],fi);const yi={kind:"core.loop.foreach",capabilities:["loop"],display:{name:"graph.node.loop.foreach.name",description:"graph.node.loop.foreach.description",category:"Loop",color:"#eab308",icon:{type:"catalogue",name:"ti-repeat"},width:120,height:140,labels:["loop","iteration","foreach"]},inputs:[gi("items","graph.node.loop.foreach.ports.input.items.label","input",{required:!0,schema:{type:"array",items:{type:"any"}}}),gi("slice","graph.node.loop.foreach.ports.input.slice.label","input",{schema:{type:"number",integer:!0,min:1}}),gi("state","graph.node.loop.foreach.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[gi("results","graph.node.loop.foreach.ports.output.results.label","output",{schema:{type:"array",items:{type:"any"}}}),gi("completed","graph.node.loop.foreach.ports.output.completed.label","output",{schema:{type:"array",items:{type:"any"}}}),gi("iterations","graph.node.loop.foreach.ports.output.iterations.label","output",{schema:{type:"number",integer:!0,min:0}}),gi("broken","graph.node.loop.foreach.ports.output.broken.label","output",{schema:{type:"boolean"}}),gi("state","graph.node.loop.foreach.ports.output.state.label","output",{schema:{type:"any"}})],parameters:[{type:"number",id:"maxIterations",label:"graph.node.loop.foreach.fields.maxIterations.label",integer:!0,min:1},{type:"object",id:"condition",label:"graph.node.loop.foreach.fields.condition.label"},{type:"string",id:"itemPort",label:"graph.node.loop.foreach.fields.itemPort.label"},{type:"string",id:"resultPort",label:"graph.node.loop.foreach.fields.resultPort.label"},{type:"string",id:"statePort",label:"graph.node.loop.foreach.fields.statePort.label"},{type:"number",id:"slice",label:"graph.node.loop.foreach.fields.slice.label",integer:!0,min:1}]},wi={kind:"core.loop.while",capabilities:["loop"],display:{name:"graph.node.loop.while.name",description:"graph.node.loop.while.description",category:"Loop",color:"#eab308",icon:{type:"catalogue",name:"ti-arrows-loop"},width:120,height:140,labels:["loop","conditional","while"]},inputs:[gi("state","graph.node.loop.while.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[gi("state","graph.node.loop.while.ports.output.state.label","output",{schema:{type:"any"}}),gi("iterations","graph.node.loop.while.ports.output.iterations.label","output",{schema:{type:"number",integer:!0,min:0}})],parameters:[{type:"number",id:"maxIterations",label:"graph.node.loop.while.fields.maxIterations.label",integer:!0,min:1},{type:"object",id:"condition",label:"graph.node.loop.while.fields.condition.label",required:!0},{type:"string",id:"statePort",label:"graph.node.loop.while.fields.statePort.label"},{type:"string",id:"inputPort",label:"graph.node.loop.while.fields.inputPort.label"},{type:"string",id:"outputPort",label:"graph.node.loop.while.fields.outputPort.label"}]},bi={kind:"core.loop.until",capabilities:["loop"],display:{name:"graph.node.loop.until.name",description:"graph.node.loop.until.description",category:"Loop",color:"#eab308",icon:{type:"catalogue",name:"ti-player-stop"},width:120,height:140,labels:["loop","conditional","until"]},inputs:[gi("state","graph.node.loop.until.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[gi("state","graph.node.loop.until.ports.output.state.label","output",{schema:{type:"any"}}),gi("iterations","graph.node.loop.until.ports.output.iterations.label","output",{schema:{type:"number",integer:!0,min:0}})],parameters:[{type:"number",id:"maxIterations",label:"graph.node.loop.until.fields.maxIterations.label",integer:!0,min:1},{type:"object",id:"condition",label:"graph.node.loop.until.fields.condition.label",required:!0},{type:"string",id:"statePort",label:"graph.node.loop.until.fields.statePort.label"},{type:"string",id:"inputPort",label:"graph.node.loop.until.fields.inputPort.label"},{type:"string",id:"outputPort",label:"graph.node.loop.until.fields.outputPort.label"}]},vi=[mi(hi),mi(fi),mi(oi),mi(ii),mi(ni),mi(ei),mi(ti),mi(Zn),(Ii=mi(Mn),{...Ii,dynamicPorts:[{type:"togglePort",parameter:"else",equals:!0,port:{id:"else",label:"graph.node.flow_control.if.ports.output.else.label",direction:"output",schema:{type:"any"}}}]}),(e=>({...e,outputs:[],parameters:[...e.parameters,{type:"collection",id:"cases",label:"graph.node.flow_control.switch.fields.cases.label",required:!0,itemIdPath:"outputPort",itemLabelPath:"label"},{type:"boolean",id:"hasDefault",label:"graph.node.flow_control.switch.fields.hasDefault.label",defaultValue:!1},{type:"object",id:"switch",label:"graph.node.flow_control.switch.fields.switch.label",required:!1}],dynamicPorts:[{type:"repeatFromParameter",parameter:"cases",itemIdPath:"outputPort",itemLabelPath:"label",direction:"output",portIdTemplate:"${id}",defaultPort:{id:"case",label:"graph.node.flow_control.switch.ports.output.case.label",direction:"output",schema:{type:"any"}}},{type:"togglePort",parameter:"hasDefault",equals:!0,port:{id:"default",label:"graph.node.flow_control.switch.ports.output.default.label",direction:"output",schema:{type:"any"}}}]}))(mi(Un)),mi(Yn),mi(Jn),mi(Tn),mi(Ln),mi(zn),mi(Xn),mi(Qn),mi(Rn),mi(ri),yi,wi,bi];var Ii;const Ei=Object.fromEntries(vi.map(e=>[e.kind,e])),Ni=[oi,ii,ni,ei,ti,Zn],Oi=[Mn,Un,Jn,Tn,Ln,Xn,Rn],Ai=[zn,Yn,Qn],xi=[li,pi,ui],ki=[hi,fi],_i={value:hi,result:fi,"core.trigger.manual":oi,"core.trigger.webhook":ii,"core.trigger.schedule":ni,"core.trigger.event":ei,"core.trigger.form":ti,"core.trigger.chat":Zn,"core.flow.if":Mn,"core.flow.switch":Un,"core.utility.map":Yn,"core.flow.delay":Jn,"core.flow.errorBoundary":Tn,"core.flow.humanApproval":Ln,"core.utility.code":zn,"core.flow.log":Xn,"core.utility.log":Qn,"core.flow.break":Rn,"core.agent":ri,"core.loop.foreach":li,"core.loop.while":pi,"core.loop.until":ui};function Di(e){return{execute:(t,o)=>e.instantiate({...$n(o.node),...t.parameters,...o.node.state??{}}).execute(t,o)}}function Pi(){const e=[];for(const[t,o]of Object.entries(Ei)){const n=_i[t];n&&e.push(Dn({manifest:o,executor:Di(n)}))}return e}function $i(e,...t){for(const o of Pi())e.register(o,{},...t);return e}class Si{resolve(e){const t=this.createValidator(e);return{name:e.name,required:e.required,validate:t}}resolveAll(e){const t={};for(const o of e)t[o.name]=this.resolve(o);return t}createValidator(e){switch((e.type??e.designType??"").toLowerCase()){case"string":return e=>"string"==typeof e;case"number":return e=>"number"==typeof e;case"boolean":return e=>"boolean"==typeof e;case"date":return e=>e instanceof Date||"string"==typeof e&&!isNaN(Date.parse(e));case"array":return e=>Array.isArray(e);case"bigint":return e=>"bigint"==typeof e;default:return()=>!0}}}class Ri{constructor(e){this.resolver=e}validateWorkflowInputs(e,t){this.validatePorts(e.inputs,t,"workflow input")}validateWorkflowOutputs(e,t){this.validatePorts(e.outputs,t,"workflow output")}validateNodeInputs(e,t){const o=(e.ports??[]).filter(e=>"input"===e.direction);this.validatePorts(o,t,`node '${e.name}' input`)}validateNodeOutputs(e,t){const o=(e.ports??[]).filter(e=>"output"===e.direction);this.validatePorts(o,t,`node '${e.name}' output`)}validatePorts(e,t,o){if(e)for(const n of e){const e=Object.prototype.hasOwnProperty.call(t,n.name);if(n.required&&!e)throw new Zt(`Missing required ${o} port '${n.name}'`);if(e&&!this.resolver.resolve(n).validate(t[n.name]))throw new Zt(`Invalid value for ${o} port '${n.name}'`)}}}const Ci=["node","definition","executor","execute","ports","component"];function Ti(e,t,o,n){return{code:e,path:t,message:o,...void 0!==n?.nodeId?{nodeId:n.nodeId}:{},...void 0!==n?.edgeId?{edgeId:n.edgeId}:{},...n?.details?{details:n.details}:{}}}function Li(e,t){const o=[];for(const n of Object.keys(e))Ci.includes(n)&&o.push(Ti("document.forbidden-field",`${t}.${n}`,`Field '${n}' is not accepted in a canonical workflow document: node, definition, executor, execute, ports and component fields are rejected at the boundary`,{details:{field:n}}));return o}function ji(e,t){t.push(...Li(e,"$")),e.inputs.forEach((e,o)=>t.push(...Li(e,`inputs[${o}]`))),e.outputs.forEach((e,o)=>t.push(...Li(e,`outputs[${o}]`)));for(const o of e.nodes)t.push(...Li(o,`nodes[${o.id}]`)),o.loop&&(t.push(...Li(o.loop,`nodes[${o.id}].loop`)),ji(o.loop.body,t));for(const o of e.edges)t.push(...Li(o,`edges[${o.id}]`))}function Mi(e,t){const o=[];e.nodes.length>t.maxNodes&&o.push(Ti("document.limit.nodes","$.nodes",`Document declares ${e.nodes.length} nodes; at most ${t.maxNodes} are allowed`,{details:{count:e.nodes.length,limit:t.maxNodes}})),e.edges.length>t.maxEdges&&o.push(Ti("document.limit.edges","$.edges",`Document declares ${e.edges.length} edges; at most ${t.maxEdges} are allowed`,{details:{count:e.edges.length,limit:t.maxEdges}}));const n=Gi(e);n>t.maxNestingDepth&&o.push(Ti("document.limit.depth","$.nodes",`Document nests loop bodies ${n} levels deep; at most ${t.maxNestingDepth} levels are allowed`,{details:{depth:n,limit:t.maxNestingDepth}}));const i=Buffer.byteLength(JSON.stringify(e),"utf8");return i>t.maxDocumentBytes&&o.push(Ti("document.limit.size","$",`Document serializes to ${i} bytes; at most ${t.maxDocumentBytes} bytes are allowed`,{details:{bytes:i,limit:t.maxDocumentBytes}})),o}function Gi(e,t=0){let o=t;for(const n of e.nodes)n.loop?.body&&(o=Math.max(o,Gi(n.loop.body,t+1)));return o}async function Ui(e,t,...o){const n=[];for(const i of e.nodes)t.has(i.kind,...o)||n.push(Ti("node.unknown-kind",`nodes[${i.id}].kind`,`Node '${i.id}' references kind '${i.kind}' which is not registered in the backend catalogue`,{nodeId:i.id,details:{kind:i.kind}})),i.loop?.body&&n.push(...await Ui(i.loop.body,t,...o));return n}async function Fi(e,t={},...o){const n={...Fn,...t.limits},i=[];if(!ut(e))return i.push(Ti("document.shape","$","Payload is not a canonical GraphWorkflowDocument: id and name must be strings and inputs, outputs, nodes and edges must be arrays")),{valid:!1,issues:i};if(!Ge(e))return i.push(Ti("document.json-unsafe","$","Document contains JSON-unsafe values: functions, class instances, undefined, NaN/Infinity, symbol keys and unsafe prototype keys (__proto__/prototype/constructor) are rejected")),{valid:!1,issues:i};ji(e,i),i.push(...(e=>{const t=[],o=new Set;for(const n of[...e.inputs,...e.outputs])o.has(n.id)?t.push(Ti("document.duplicate-port-id",`ports[${n.id}]`,`Workflow port '${n.id}' is declared more than once; workflow port ids must be unique`)):o.add(n.id);const n=new Set;for(const o of e.nodes)n.has(o.id)?t.push(Ti("document.duplicate-node-id",`nodes[${o.id}]`,`Node '${o.id}' is declared more than once; node ids must be unique`,{nodeId:o.id})):n.add(o.id);const i=new Set;for(const o of e.edges)i.has(o.id)?t.push(Ti("document.duplicate-edge-id",`edges[${o.id}]`,`Edge '${o.id}' is declared more than once; edge ids must be unique`,{edgeId:o.id})):i.add(o.id);return t})(e)),i.push(...Mi(e,n)),So(e,i);try{tt(e)}catch(e){const t=e instanceof x?e.message:e+"";i.push(Ti("document.structure","$",t))}return t.catalogue&&i.push(...await Ui(e,t.catalogue,...o)),{valid:0===i.length,issues:i}}class Bi{constructor(e,t){this.iteration=e,this.metadata=t}}function qi(e,t,o){const n=e?.owner??null;if(n&&n!==t&&(null!=t&&""!==t||!0!==o.allowAnonymousAccess))throw new L(`${o.resourceKind} '${o.resourceId}' is owned by another user`)}function Vi(e){if(null===e||"object"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(e=>Vi(e)).join(",")}]`;const t=e;return`{${Object.keys(t).filter(e=>void 0!==t[e]).sort().map(e=>`${JSON.stringify(e)}:${Vi(t[e])}`).join(",")}}`}function Wi(e){return X("sha256").update(Vi(e)).digest("hex")}class Hi{constructor(e={}){this.events=new Map,this.listeners=new Map,this.limits={...ce,...e}}async append(e){let t=this.events.get(e.runId);t||(t=[],this.events.set(e.runId,t)),t.push(e),this.enforceRetention(t);for(const t of this.listeners.get(e.runId)??[])try{t(e)}catch{}}async listAfter(e,t){const o=this.events.get(e);return o?o.filter(e=>e.sequence>t):[]}subscribe(e,t){let o=this.listeners.get(e);return o||(o=new Set,this.listeners.set(e,o)),o.add(t),()=>{o.delete(t),0===o.size&&this.listeners.delete(e)}}release(e){this.events.delete(e),this.listeners.delete(e)}enforceRetention(e){const t=this.limits.maxEventsPerRun;for(;e.length>t;){const t=e.findIndex(e=>!pe(e.type));if(-1===t)break;e.splice(t,1)}}}class Ki{constructor(){this.runs=new Map}async saveRun(e){this.runs.set(e.runId,{...e})}async readRun(e){const t=this.runs.get(e);return t?{...t}:null}release(e){this.runs.delete(e)}}class zi{constructor(e,t={}){this.sequences=new Map,this.chains=new Map,this.store=e,this.limits={...ce,...t}}async publish(e){const t=e.runId,o=(this.sequences.get(t)??0)+1;this.sequences.set(t,o);const n={...e,payload:this.limitPayload(e.payload),sequence:o,timestamp:(new Date).toISOString()},i=(this.chains.get(t)??Promise.resolve()).then(()=>this.store.append(n));return this.chains.set(t,i.catch(()=>{})),await i,n}lastSequence(e){return this.sequences.get(e)??0}release(e){this.sequences.delete(e),this.chains.delete(e)}limitPayload(e){if(void 0===e)return;let t;try{t=JSON.stringify(e)}catch{return{nonSerializable:!0}}return t.length>this.limits.maxEventPayloadBytes?{truncated:!0,reason:"event payload exceeds the configured byte limit",bytes:t.length}:e}}class Ji{constructor(e,t,o,n={},i={}){this.controllers=new Map,this.completions=new Map,this.timeouts=new Map,this.engine=e,this.runStore=t,this.publisher=o,this.hooks=n,this.limits={...ce,...i}}begin(e){const t=this.controllers.get(e);if(t)return t;const o=new AbortController;return this.controllers.set(e,o),o}abort(e,t){const o=this.controllers.get(e);return!!o&&(o.signal.aborted||o.abort(t),!0)}isAborted(e){return!0===this.controllers.get(e)?.signal.aborted}abortReason(e){const t=this.controllers.get(e)?.signal;if(t?.aborted)return"timeout"===t.reason?"timeout":"user"}waitFor(e){return this.completions.get(e)}schedule(e,t,o,...n){const i=this.completions.get(e.runId);if(i)return i;const r=this.runExecution({...e},t,o,...n).catch(async t=>{const o=Xi(t);try{await this.emitTerminal({...e},le.WORKFLOW_FAILED,o)}catch{}return await this.finalize({...e},"failed",void 0,o,...n)});return this.completions.set(e.runId,r),r}release(e){this.controllers.delete(e),this.completions.delete(e);const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.publisher.release(e)}armTimeout(e){const t=setTimeout(()=>{this.timeouts.delete(e),this.abort(e,"timeout")},this.limits.executionTimeoutMs);this.timeouts.set(e,t)}async runExecution(e,t,o,...n){const i=e.runId;let r,a,s=!1;const d=this.engine.observe({refresh:async t=>{t.runId===i&&(t.error&&(r=t.error),pe((await this.publisher.publish(this.envelopeOf(e,t))).type)?s=!0:t.type===le.WORKFLOW_STARTED&&"validating"===e.status&&(e.status="running",await this.persist(e,...n)))}});this.armTimeout(i);try{if(this.isAborted(i)){const t={name:"GraphRunCancelledError",message:`Graph run '${i}' was cancelled before execution started`,code:"GRAPH_RUN_CANCELLED"};return r=t,await this.emitTerminal(e,le.WORKFLOW_CANCELLED,t),s=!0,await this.finalize(e,"cancelled",void 0,t,...n)}let d,l;e.status="validating",e.startedAt=(new Date).toISOString(),await this.persist(e,...n);try{({document:d,fingerprint:l}=await t(...n)),e.documentFingerprint=l,await this.persist(e,...n)}catch(t){const o=Xi(t);return r=o,s||(await this.emitTerminal(e,le.WORKFLOW_FAILED,o),s=!0),await this.finalize(e,"failed",void 0,o,...n)}if(this.isAborted(i)){const t={name:"GraphRunCancelledError",message:`Graph run '${i}' was cancelled before execution started`,code:"GRAPH_RUN_CANCELLED"};return r=t,s||(await this.emitTerminal(e,le.WORKFLOW_CANCELLED,t),s=!0),await this.finalize(e,"cancelled",void 0,t,...n)}try{a=await this.engine.execute(d,o,{runId:i,abortSignal:this.controllers.get(i)?.signal,metadata:{documentFingerprint:l}},...n)}catch(e){r=Xi(e)}const c=this.abortReason(i);let u,p;return"timeout"===c?(u="failed",p=r??{name:"GraphRunTimeoutError",message:`Graph run '${i}' exceeded the configured execution timeout of ${this.limits.executionTimeoutMs}ms`,code:"GRAPH_RUN_TIMEOUT"}):"user"===c?(u="cancelled",p=r):a?.status===ae.SUCCEEDED?u="succeeded":a?.status===ae.CANCELLED?(u="cancelled",p=r):(u="failed",p=r??Xi(new Yt(a?`Graph run '${i}' failed`:`Graph run '${i}' failed without a result`,"GRAPH_RUN_FAILED",{runId:i}))),s||await this.emitTerminal(e,"succeeded"===u?le.WORKFLOW_COMPLETED:"cancelled"===u?le.WORKFLOW_CANCELLED:le.WORKFLOW_FAILED,p),await this.finalize(e,u,a,p,...n)}finally{d();const e=this.timeouts.get(i);e&&(clearTimeout(e),this.timeouts.delete(i))}}async emitTerminal(e,t,o){await this.publisher.publish({runId:e.runId,workflowId:e.workflowId,type:t,error:o})}async finalize(e,t,o,n,...i){e.status=t,o&&(e.result=o),n&&(e.error=n),e.startedAt||(e.startedAt=(new Date).toISOString()),e.finishedAt=(new Date).toISOString(),await this.persist(e,...i);try{await(this.hooks.onRunCompleted?.(e,o))}catch{}return e}async persist(e,...t){await this.runStore.saveRun({...e},...t)}envelopeOf(e,t){return{runId:e.runId,workflowId:t.workflowId??e.workflowId,type:t.type,nodeId:t.nodeId,edgeId:t.edgeId,payload:void 0===t.payload?void 0:Me(t.payload)?t.payload:{nonSerializable:!0},error:t.error,parentRunId:t.parentRunId,path:t.path}}}function Xi(e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack,code:e.graphCode??("number"==typeof e.code?e.code+"":e.code)}:{name:"UnknownError",message:e+""}}class Yi{constructor(e,t,o,n={}){this.activeByCaller=new Map,this.callerKeysByRun=new Map,this.releaseTimers=new Map,this.engine=e,this.runStore=t,this.eventStore=o,this.publisher=new zi(o,n.limits),this.executor=new Ji(e,t,this.publisher,{onRunCompleted:n.onRunCompleted},n.limits),this.options={...n,limits:{...ce,...n.limits}}}get limits(){return this.options.limits}async createRun(e,t,o,...n){this.validateCreateRequest(e);const i=e.workflowId??e.workflow?.id??"";if(!i)throw new x("Graph run request must carry a workflow document with an id or a saved workflowId");if(e.workflowId&&!this.options.documentResolver)throw new x("Graph run requests by workflowId require a document resolver");const r=o??t??"anonymous",a=this.activeByCaller.get(r)??new Set;if(a.size>=this.options.limits.maxConcurrentRuns)throw new x(`Graph run rejected: the configured limit of ${this.options.limits.maxConcurrentRuns} concurrent runs per caller is exhausted`);const s=this.generateRunId(),d={runId:s,workflowId:i,ownerUser:t,status:"queued",createdAt:(new Date).toISOString()};this.executor.begin(s),await this.runStore.saveRun({...d},...n);const l=this.documentProviderFor(e,t);return a.add(s),this.activeByCaller.set(r,a),this.callerKeysByRun.set(s,r),this.executor.schedule(d,l,e.inputs??{},...n).catch(()=>{}).finally(()=>this.finishActiveRun(s)),d}async getRun(e,t,...o){const n=await this.runStore.readRun(e,...o);if(!n)throw new _(`No graph run found for runId '${e}'`);return this.assertOwnership(n,t),n}async cancelRun(e,t,...o){const n=await this.runStore.readRun(e,...o);if(!n)throw new _(`No graph run found for runId '${e}'`);return this.assertOwnership(n,t),"succeeded"===(i=n.status)||"failed"===i||"cancelled"===i||(this.executor.abort(e,"user"),n.status="cancelled",n.finishedAt=(new Date).toISOString(),await this.runStore.saveRun({...n},...o)),n;var i}async listEvents(e,t,o,...n){return await this.getRun(e,o,...n),this.eventStore.listAfter(e,t)}async subscribeEvents(e,t,o,...n){return await this.getRun(e,t,...n),this.eventStore.subscribe(e,o)}subscribeRunEvents(e,t){return this.eventStore.subscribe(e.runId,t)}async waitForRun(e,t,...o){const n=this.executor.waitFor(e);return n&&await n,this.getRun(e,t,...o)}async executeAndWait(e,t,o,...n){const i=await this.createRun(e,t,o,...n);return this.waitForRun(i.runId,t,...n)}release(e){this.finishActiveRun(e);const t=this.releaseTimers.get(e);t&&(clearTimeout(t),this.releaseTimers.delete(e)),this.executor.release(e),this.eventStore.release?.(e)}finishActiveRun(e){const t=this.callerKeysByRun.get(e);if(void 0!==t){this.callerKeysByRun.delete(e);const o=this.activeByCaller.get(t);o&&(o.delete(e),0===o.size&&this.activeByCaller.delete(t))}if(this.releaseTimers.has(e))return;const o=setTimeout(()=>{this.releaseTimers.delete(e),this.release(e)},this.options.limits.eventReplayWindowMs);o.unref?.(),this.releaseTimers.set(e,o)}validateCreateRequest(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new x("Graph run request must be an object carrying either a workflow document or a workflowId plus inputs");const t=void 0!==e.workflow,o=void 0!==e.workflowId;if(t&&o)throw new x("Graph run request is ambiguous: supply either an unsaved workflow document or a saved workflowId, not both");if(!t&&!o)throw new x("Graph run request must supply either an unsaved workflow document or a saved workflowId");if(t&&!ut(e.workflow))throw new x("Graph run request carries a payload that is not a canonical GraphWorkflowDocument");if(void 0!==e.inputs&&!Ge(e.inputs))throw new x("Graph run inputs must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys and unsafe prototype keys (__proto__/prototype/constructor) are rejected");const n=(e=>{try{return JSON.stringify(e)?.length??0}catch{return Number.MAX_SAFE_INTEGER}})(e);if(n>this.options.limits.maxRequestBytes)throw new x(`Graph run request of ${n} bytes exceeds the configured limit of ${this.options.limits.maxRequestBytes} bytes`)}documentProviderFor(e,t){if(e.workflow){const t=e.workflow;return async()=>({document:t,fingerprint:Wi(t)})}const o=e.workflowId;return async(...e)=>{const n=this.options.documentResolver;if(!n)throw new x("Graph run requests by workflowId require a document resolver");const i=await n.resolve(o,t,...e);return{document:i,fingerprint:Wi(i)}}}assertOwnership(e,t){qi({owner:e.ownerUser},t,{allowAnonymousAccess:!0===this.options.allowAnonymousAccess,resourceKind:"Graph run",resourceId:e.runId})}generateRunId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new no("Cannot generate a graph run id: crypto.randomUUID is unavailable in this runtime",{runtime:typeof globalThis.crypto});return e.randomUUID()}}function Qi(e){if(!e)return;let t;try{t=e.cache?.user}catch{t=void 0}if(null==t)try{t=e.get("user")}catch{t=void 0}return"string"==typeof t&&t.length>0?t:void 0}function Zi(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&ut(e.document)&&!ut(e)}function er(e){return JSON.parse(JSON.stringify(e))}let tr=class extends W{constructor(e){super(Lt),this.catalogue=e}get limits(){return{...Fn,...Bn.graph.workflows.limits??{}}}get allowAnonymousAccess(){return!0===Bn.graph.workflows.allowAnonymousAccess}async saveDocument(e,t,...o){const{ctx:n,ctxArgs:i}=(await this.logCtx(o,"saveDocument",!0)).for(this.saveDocument);if(!ut(t))throw new x("Payload is not a canonical GraphWorkflowDocument: id and name must be strings and inputs, outputs, nodes and edges must be arrays");if(t.id!==e)throw new x(`Document id '${t.id}' does not match the workflow id '${e}' from the request path`);const r=await this.validateDocument(t,n);if(!r.valid)throw new so(r.issues);const a=Qi(n);let s;try{s=await this.read(e,...i)}catch{s=null}this.assertOwnership(e,s,a);const d=new Date;if(s)return s.name=t.name,s.document=er(t),s.updatedAt=d,this.update(s,...i);const l=new Lt({workflowId:e,name:t.name,document:er(t),...a?{owner:a}:{},updatedAt:d});return this.create(l,...i)}async getDocument(e,...t){const{ctx:o,ctxArgs:n}=(await this.logCtx(t,"getDocument",!0)).for(this.getDocument);let i;try{i=await this.read(e,...n)}catch{i=null}if(!i)throw new _(`No graph workflow found for workflowId '${e}'`);if(this.assertOwnership(e,i,Qi(o)),i.document)return er(i.document);throw new _(`Graph workflow '${e}' has no canonical document; legacy definition/state snapshots are no longer supported (DECAF-50 \xa74.26 R2-2)`)}async validateDocument(e,...t){const{ctx:o}=(await this.logCtx(t,"validateDocument",!0)).for(this.validateDocument);return await Fi(e,{limits:this.limits,...this.catalogue?{catalogue:this.catalogue}:{}},o)}async saveSnapshot(e,t,...o){const{ctx:n,ctxArgs:i}=(await this.logCtx(o,"saveSnapshot",!0)).for(this.saveSnapshot);if(!Ge(t))throw new x("Workflow snapshot payload must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys and unsafe prototype keys (__proto__/prototype/constructor) are rejected");if(!Zi(t))throw new x("Workflow snapshots must wrap a canonical GraphWorkflowDocument ({ document, editor?, metadata? }): legacy definition/state snapshots are no longer accepted; save canonical documents via PUT /graph/workflows/{workflowId}");const r=Qi(n);let a;try{a=await this.read(e,...i)}catch{a=null}this.assertOwnership(e,a,r);const s=new Date;if(a)return a.snapshot=t,await this.applyCanonicalWrapper(a,t,n),a.updatedAt=s,this.update(a,...i);const d=new Lt({workflowId:e,snapshot:t,...r?{owner:r}:{},updatedAt:s});return await this.applyCanonicalWrapper(d,t,n),this.create(d,...i)}async loadSnapshot(e,...t){const{ctx:o,ctxArgs:n}=(await this.logCtx(t,"loadSnapshot",!0)).for(this.loadSnapshot);try{const t=await this.read(e,...n);return this.assertOwnership(e,t,Qi(o)),t}catch{return null}}assertOwnership(e,t,o){qi(t??null,o??null,{allowAnonymousAccess:this.allowAnonymousAccess,resourceKind:"Graph workflow",resourceId:e})}async applyCanonicalWrapper(e,t,o){if(!Zi(t))return;if(t.document.id!==e.workflowId)throw new x(`Document id '${t.document.id}' does not match the workflow id '${e.workflowId}' from the request path`);const n=await Fi(t.document,{limits:this.limits,...this.catalogue?{catalogue:this.catalogue}:{}},o);if(!n.valid)throw new so(n.issues);e.document=er(t.document),e.name=t.document.name}};function or(e){if(null!=e)return JSON.parse(JSON.stringify(e))}tr=D([G(Lt),P("design:paramtypes",[Function])],tr);let nr=class extends W{constructor(){super(Tt)}async saveRun(e,...t){const{ctxArgs:o}=(await this.logCtx(t,"saveRun",!0)).for(this.saveRun),n=(e=>new Tt({runId:e.runId,workflowId:e.workflowId,...e.ownerUser?{owner:e.ownerUser}:{},status:e.status,...e.documentFingerprint?{documentFingerprint:e.documentFingerprint}:{},...void 0!==e.result?{result:or(e.result)}:{},...e.error?{error:or(e.error)}:{},createdAt:new Date(e.createdAt),...e.startedAt?{startedAt:new Date(e.startedAt)}:{},...e.finishedAt?{finishedAt:new Date(e.finishedAt)}:{}}))(e);let i;try{i=await super.read(e.runId,...o)}catch{i=null}if(i)return i.workflowId=n.workflowId,i.owner=n.owner,i.status=n.status,i.documentFingerprint=n.documentFingerprint,i.result=n.result,i.error=n.error,i.startedAt=n.startedAt,i.finishedAt=n.finishedAt,void await this.update(i,...o);await this.create(n,...o)}async readRun(e,...t){const{ctxArgs:o}=(await this.logCtx(t,"readRun",!0)).for(this.readRun);try{return(e=>{const t=e.result;return{runId:e.runId,workflowId:e.workflowId,ownerUser:e.owner??null,status:(o=e.status,"string"==typeof o&&["queued","validating","running","succeeded","failed","cancelled"].includes(o)?e.status:"failed"),createdAt:e.createdAt.toISOString(),...e.startedAt?{startedAt:e.startedAt.toISOString()}:{},...e.finishedAt?{finishedAt:e.finishedAt.toISOString()}:{},...t?{result:t}:{},...e.error?{error:e.error}:{},...e.documentFingerprint?{documentFingerprint:e.documentFingerprint}:{}};var o})(await super.read(e,...o))}catch{return null}}};nr=D([G(Tt),P("design:paramtypes",[])],nr);class ir{map(e){const t={};for(const[o,n]of Object.entries(e.nodeResults))t[o]={status:n.status,startedAt:n.startedAt?.toISOString(),finishedAt:n.finishedAt?.toISOString(),error:n.error,outputs:n.outputs,fromCache:n.fromCache,pinned:n.pinned};const o={};for(const t of e.events)t.edgeId&&"edge.valueRouted"===t.type&&(o[t.edgeId]={status:ae.SUCCEEDED,lastValue:t.payload?.value,updatedAt:t.timestamp.toISOString()});const n=[...e.events];return{runId:e.runId,status:e.status,nodes:t,edges:o,outputs:e.outputs,events:n}}}export{ri as AgentNode,Rn as BreakFlowNode,Zn as ChatTriggerNode,Kn as CodeInputSchema,zn as CodeNode,jn as ConditionExpressionEvaluator,Fn as DEFAULT_GRAPH_WORKFLOW_DOCUMENT_LIMITS,Wo as DEFAULT_GRAPH_WORKFLOW_VALIDATION_LIMITS,an as DEFAULT_PINNING_METADATA,Jn as DelayFlowNode,Tn as ErrorBoundaryFlowNode,ei as EventTriggerNode,ti as FormTriggerNode,ai as GRAPH_AGENT_NODES,ki as GRAPH_BOUNDARY_NODES,_i as GRAPH_BUILT_IN_NODE_CLASSES_BY_KIND,vi as GRAPH_BUILT_IN_NODE_MANIFESTS,Ei as GRAPH_BUILT_IN_NODE_MANIFESTS_BY_KIND,Hn as GRAPH_CODE_DEFAULT_LANGUAGE,qn as GRAPH_CODE_DEFAULT_TIMEOUT_MS,Wn as GRAPH_CODE_LANGUAGES,Ht as GRAPH_CODE_MAX_TIMEOUT_MS,Ft as GRAPH_DEFAULT_CONCURRENCY,qt as GRAPH_DEFAULT_MAX_FOREACH_ITERATIONS,Bt as GRAPH_DEFAULT_MAX_LOOP_ITERATIONS,Ho as GRAPH_DOCUMENT_FORBIDDEN_FIELD_KEYS,Oi as GRAPH_FLOW_CONTROL_NODES,Xt as GRAPH_LOOP_KIND,xi as GRAPH_LOOP_NODES,Wt as GRAPH_MAX_FOREACH_ITERATIONS,Vt as GRAPH_MAX_LOOP_ITERATIONS,Kt as GRAPH_PINNING_METADATA_KEY,jo as GRAPH_PLAIN_SECRET_KEYS,Ni as GRAPH_TRIGGER_NODES,Ai as GRAPH_UTILITY_NODES,Ut as GRAPH_WORKFLOW_BOUNDARY,Ci as GRAPH_WORKFLOW_FORBIDDEN_FIELD_KEYS,Ao as GraphAuthValidator,ro as GraphBreakSignal,ci as GraphConditionEvaluator,Jt as GraphConditionType,Uo as GraphConnectionPolicyValidator,qo as GraphConnectionValidationError,Vo as GraphCredentialAuthorizationError,Fo as GraphCredentialReferenceValidator,Qt as GraphCycleError,Bo as GraphDocumentValidationError,Go as GraphEdgeInstanceValidator,Bn as GraphEnvironment,_o as GraphExecutionContext,cn as GraphExecutionEngine,Yt as GraphExecutionError,lo as GraphExecutionEventEmitter,co as GraphExecutionEventFactory,Do as GraphExecutionFrame,Xo as GraphExecutionPlanner,ir as GraphExecutionSnapshotMapper,li as GraphForeachLoopNode,Zt as GraphInputError,hi as GraphInputValueNode,Bi as GraphLoopExecutionContext,eo as GraphLoopLimitError,Sn as GraphNode,xn as GraphNodeCatalogue,kn as GraphNodeExecutorRegistry,_n as GraphNodeExecutorResolver,$o as GraphNodeInstanceValidator,En as GraphNodeManifestResolver,gn as GraphNodeMethodNotFoundError,mn as GraphNodeMethodRegistry,fn as GraphNodeNotFoundError,hn as GraphNodeRegistrationError,fi as GraphOutputValueNode,Mo as GraphParameterValidator,ln as GraphPinningDependencyResolver,to as GraphPinningError,dn as GraphPinningPolicy,rn as GraphPinningService,zt as GraphPinningStrategy,oo as GraphPortError,Si as GraphPortSchemaResolver,ao as GraphRunCancelledError,zi as GraphRunEventPublisher,Ji as GraphRunExecutor,nr as GraphRunModelService,Yi as GraphRunService,no as GraphStoreError,nn as GraphTopology,io as GraphTopologyError,ui as GraphUntilLoopNode,Yo as GraphValueModel,tn as GraphValueRepository,Ri as GraphValueValidator,pi as GraphWhileLoopNode,so as GraphWorkflowDocumentRejectedError,Jo as GraphWorkflowDocumentValidator,tr as GraphWorkflowService,Ln as HumanApprovalFlowNode,Mn as IfFlowNode,Hi as InMemoryGraphRunEventStore,Ki as InMemoryGraphRunStore,pn as IsolatedVmCodeSandboxEvaluator,Xn as LogFlowNode,oi as ManualTriggerNode,Yn as MapNode,ni as ScheduleTriggerNode,Un as SwitchFlowNode,Qn as UtilityLogNode,ii as WebhookTriggerNode,qi as assertGraphResourceOwnership,Po as buildGraphExecutionResult,Pi as builtInGraphNodeRegistrations,Ro as checkGraphValueAgainstSchema,Vn as clampGraphCodeTimeoutMs,So as collectLooseNodeIssues,po as composeGraphNamespace,on as createGraphValueRepository,Pn as declaredGraphNodeMethods,uo as decomposeGraphNamespace,No as decomposeGraphNamespaces,Dn as defineGraphNode,yo as findMalformedGraphNamespaces,mo as findUngrantedGraphNamespaces,Io as graphAuthDataFromRecord,Eo as graphAuthDataOf,go as graphNamespaceCovers,fo as graphNamespacePartsOf,$n as graphNodeConfig,wo as graphRolesFromNamespaces,Wi as graphRunDocumentFingerprint,Qi as graphWorkflowOwnerOf,To as isGraphCredentialReferenceLike,ho as isGraphNamespaceCacheEntryValid,Ko as isGraphResolvedWorkflow,sn as isPinnable,Oo as mergeGraphAuthData,$i as registerBuiltInGraphNodes,vn as resolveGraphDynamicPorts,In as resolveGraphNodeManifest,Qo as serializeGraphValueKey,Fi as validateGraphWorkflowDocumentAtBoundary};
|
|
1
|
+
import{logParameterRegistry as e,Logging as t,LoggedEnvironment as o}from"@decaf-ts/logging";import{RenderingEngine as n,uimodel as r,uielement as i,uilistprop as a,uilistmodel as s,hidden as d}from"@decaf-ts/ui-decorators";import{Metadata as l,Decoration as c,apply as u,metadata as p,propMetadata as h,description as f,prop as g,DefaultFlavour as m}from"@decaf-ts/decoration";import{ValidationKeys as y,Model as w,required as b,type as v,date as I,model as E,option as N,min as O,max as k}from"@decaf-ts/decorator-validation";import{ValidationError as A,InternalError as x,NotFoundError as _}from"@decaf-ts/db-decorators";import{__decorate as S,__metadata as D}from"tslib";import{pk as P,column as R,index as $,table as C,BaseModel as T,ForbiddenError as L,Context as M,repository as j,Repository as G,AuthorizationError as U,service as F,Service as B,ClientBasedService as W,Adapter as q,ModelService as H,OrderDirection as K}from"@decaf-ts/core";import V from"isolated-vm";import*as z from"acorn";import*as J from"acorn-walk";import*as X from"typescript";import{createHash as Y}from"node:crypto";var Q,Z;y.REQUIRED,y.MIN,y.MIN_LENGTH,y.MAX,y.MAX_LENGTH,y.PATTERN,y.URL,y.STEP,y.DATE,y.EMAIL,y.PASSWORD,y.EQUALS,y.DIFF,y.LESS_THAN,y.LESS_THAN_OR_EQUAL,y.GREATER_THAN,y.GREATER_THAN_OR_EQUAL,(e=>{e.GRAPH="graph",e.NODE="graph.node",e.EDGE="graph.edge",e.PORT="graph.port",e.STATE="graph.state"})(Q||(Q={})),(e=>{e.INPUT="input",e.OUTPUT="output",e.CONNECTION="connection"})(Z||(Z={}));const ee={};function te(e,t={}){let o=e.width??96,n=e.height??96;for(const r of e.sizeRules??[]){if("parameterCount"!==r.type)continue;const e=t[r.parameter]??0;e>0&&("width"===r.dimension?o+=e*r.perItem:n+=e*r.perItem)}return{width:o,height:n}}function oe(e,t){ee[e]=t}function ne(e,t,o){const n=t?ee[t]:void 0;return n?.color?n.color:e||"#64748b"}function re(e,t,o){const n=t?ee[t]:void 0;return n?.icon?n.icon:e||"ti-pointer"}const ie=["skip","passThroughFirstInput","emitDefaults"];function ae(e){return ie.includes(e)}var se,de,le,ce;(e=>{e.PENDING="pending",e.PLANNING="planning",e.RUNNING="running",e.SUCCEEDED="succeeded",e.FAILED="failed",e.SKIPPED="skipped",e.CANCELLED="cancelled",e.CACHED="cached"})(se||(se={})),(e=>{e.IDLE="idle",e.RUNNING="running",e.BLOCKED="blocked",e.SUCCEEDED="succeeded",e.FAILED="failed",e.SKIPPED="skipped"})(de||(de={})),(e=>{e.NODE_ID="nodeId",e.WORKFLOW_ID="workflowId",e.RUN_ID="runId",e.USER="user",e.ROLES="roles",e.NAMESPACES="namespaces",e.ORGANIZATION="organization",e.IP="ip"})(le||(le={})),(e=>{e.WORKFLOW_STARTED="workflow.started",e.WORKFLOW_PLANNED="workflow.planned",e.WORKFLOW_COMPLETED="workflow.completed",e.WORKFLOW_FAILED="workflow.failed",e.WORKFLOW_CANCELLED="workflow.cancelled",e.WORKFLOW_SUSPENDED="workflow.suspended",e.WORKFLOW_RESUMED="workflow.resumed",e.NODE_QUEUED="node.queued",e.NODE_STARTED="node.started",e.NODE_OUTPUT="node.output",e.NODE_COMPLETED="node.completed",e.NODE_FAILED="node.failed",e.NODE_SKIPPED="node.skipped",e.NODE_CACHE_HIT="node.cacheHit",e.NODE_PINNED="node.pinned",e.NODE_UNPINNED="node.unpinned",e.NODE_STATE_CHANGED="node.stateChanged",e.EDGE_VALUE_ROUTED="edge.valueRouted",e.EDGE_STATE_CHANGED="edge.stateChanged",e.GRAPH_RUN_LOG="graph.run.log",e.LOOP_STARTED="loop.started",e.LOOP_ITERATION_STARTED="loop.iteration.started",e.LOOP_ITERATION_COMPLETED="loop.iteration.completed",e.LOOP_CONDITION_EVALUATED="loop.condition.evaluated",e.LOOP_COMPLETED="loop.completed",e.LOOP_LIMIT_REACHED="loop.limitReached",e.VALIDATION_STARTED="validation.started",e.VALIDATION_FAILED="validation.failed",e.VALIDATION_COMPLETED="validation.completed",e.STORE_READ="store.read",e.STORE_WRITE="store.write",e.STORE_DELETE="store.delete"})(ce||(ce={}));const ue={maxRequestBytes:4e6,maxConcurrentRuns:32,maxEventsPerRun:1e4,maxEventPayloadBytes:256e3,executionTimeoutMs:6e5,eventReplayWindowMs:3e5},pe=[ce.WORKFLOW_COMPLETED,ce.WORKFLOW_FAILED,ce.WORKFLOW_CANCELLED];function he(e){return pe.includes(e)}function fe(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}function ge(e){const t=l.constr(e);if("function"==typeof t)return t;const o=e.constructor;return"function"==typeof o?o:e}function me(e){if(null!=e)return"string"==typeof e?e:e+""}function ye(e,t,o){return me(e?.props?.label??e?.props?.name)??me(t?.name)??o??""}function we(e,t,o){const n=Ie(e,t);if(n?.model&&"function"==typeof n.model&&w.isModel(n.model))return n.model;const r=l.type(e,t);if("function"==typeof r&&w.isModel(r))return r;const i=l.getPropDesignTypes?.(e,t)?.designTypes||[];for(const e of i)if("function"==typeof e&&w.isModel(e))return e;const a=o?.[y.TYPE]?.customTypes||[];for(const e of a)if("function"==typeof e&&w.isModel(e))return e}function be(e,t){const o=[t,e.path??e.property].filter(Boolean).join(".");return{...e,path:o,children:e.children?.map(e=>be(e,o))}}function ve(e){const t=ge(e);return l.get(t,Q.NODE)}function Ie(e,t){const o=ge(e);return l.get(o,l.key(Q.PORT,t+""))}function Ee(e,t,o,n=new Set){const r=Ie(e,t);if(!r?.schema)return;const i=we(e,t,l.validationFor(e,t));if(!i)return;if(n.has(i))return[];const a=new Set(n);return a.add(e),a.add(i),ke(i,a).filter(e=>e.direction===o)}function Ne(e,t,o=new Set){const n=Ie(e,t);if(!n)return;const r=l.validationFor(e,t),i=we(e,t,r);if(n.schema&&i)return;const a=w.uiElementOf(e,t)||void 0,s=w.uiDecorationOf(e,t,"uiprop"),d=l.type(e,t),c=me(n.type??r?.[y.TYPE]?.customTypes?.[0]?.name??a?.props?.type??s?.type??d?.name),u=(n.expand||i&&!o.has(i))&&i?(()=>{const n=new Set(o);return n.add(e),n.add(i),ke(i,n).map(e=>be(e,t))})():void 0;return{property:t,path:t,direction:n.direction,name:t,label:ye(a,s,t),type:c?.toLowerCase(),required:!!r?.[y.REQUIRED],hidden:!!w.uiIsHidden(e,t),designType:d?.name,element:a,prop:s,validation:r,graph:n,connectionRules:n.connectionRules,composite:!!u?.length,children:u,model:i?.name}}function Oe(e){return ke(ge(e))}function ke(e,t=new Set){const o=l.properties(e)||[],n=[];for(const r of o){const o=r+"",i=Ie(e,o);if(i?.schema){const r=Ee(e,o,i.direction,t);if(r){n.push(...r);continue}}const a=Ne(e,o,t);a&&n.push(a)}return n}function Ae(e){return e.flatMap(e=>e.children&&e.children.length?Ae(e.children):[e])}function xe(e){const t=ge(e),o=w.uiModelOf(t),n=ve(t)||{},r=o?.tag||t.name,i=Oe(t),a=((e,t)=>{const o=t.portGroups||[],n=new Map(o.map(e=>[e.property,e])),r=[],i=l.properties(e)||[];for(const t of i){const o=t+"",i=Ie(e,o);if(!i?.schema)continue;if(!we(e,o,l.validationFor(e,o)))continue;const a=n.get(o);r.push(a?{...a,toggle:a.toggle??"all"}:{property:o,toggle:"all"})}for(const e of o)r.some(t=>t.property===e.property)||r.push(e);return r.length?r:void 0})(t,n),s=n.namespaces?.length?n.namespaces:(e=>{if(null==e)return[];let t,o=e;try{o=l.constr(e)}catch{o=e}try{t=l.get(o,"auth-namespace")}catch{t=void 0}return fe(t)??[]})(t),d=s.length?s:void 0;return{name:t.name,tag:r,kind:n.kind||r,category:n.category,color:n.color,effectiveColor:ne(n.color,n.category),group:n.group,height:n.height,icon:n.icon,effectiveIcon:re(n.icon,n.category),labels:n.labels||[],maxChildren:n.maxChildren,minWidth:n.minWidth,width:n.width,shape:n.shape,cornerRadius:n.cornerRadius,sizeRules:n.sizeRules,props:o?.props,ui:o,graph:n,ports:i,portGroups:a,namespaces:d}}const _e=new Set,Se=new Set;function De(e,t,o){return c.for(Q.NODE).define({decorator:(e,t,o)=>{const n={kind:t?.kind||e,...t};return t=>{const i=u(r(e,o),p(Q.NODE,n))(t);var a;return a=t,_e.add(a),i}},args:[e,t,o]}).apply()}function Pe(e,t){return c.for(Q.PORT).define({decorator:(e,t)=>(o,n)=>{const r={direction:e,...t};return u(h(l.key(Q.PORT,n),r))(o,n)},args:[e,t]}).apply()}function Re(e){return Pe(Z.INPUT,{...e,schema:!0})}function $e(e){return Pe(Z.OUTPUT,{...e,schema:!0})}function Ce(e){return Pe(Z.CONNECTION,e)}n.prototype.renderAsNode=(e,t,...o)=>xe(e),l.nodes=(()=>[..._e]).bind(l),l.workflows=(()=>[...Se]).bind(l);const Te=["__proto__","prototype","constructor"];function Le(e){return Te.includes(e)}function Me(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function je(e){return null===e||"string"==typeof e||"number"==typeof e&&Number.isFinite(e)||"boolean"==typeof e}function Ge(e){return!!je(e)||(Array.isArray(e)?e.every(e=>Ge(e)):!!Me(e)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&!Le(t)&&Ge(e[t])))}function Ue(e){if(void 0===e)return!1;if("number"==typeof e)return Number.isFinite(e);if("function"==typeof e)return!1;if(Ge(e))return!0;if(Array.isArray(e))return e.every(e=>Ue(e));if(Me(e)){const t=Reflect.ownKeys(e);for(const o of t){if("string"!=typeof o)return!1;if(Le(o))return!1;if(!Ue(e[o]))return!1}return!0}return!1}function Fe(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>Fe(e));const t={};for(const[o,n]of Object.entries(e))t[o]=Fe(n);return t}const Be={string:"string",char:"string",text:"string",textarea:"string",radio:"string",select:"string",number:"number",integer:"number",float:"number",double:"number",decimal:"number",boolean:"boolean",bool:"boolean",checkbox:"boolean",array:"array",list:"array",set:"array",object:"object",model:"model",any:"any",unknown:"any",enum:"enum"},We={date:"date",datetime:"date-time","date-time":"date-time",duration:"duration"};function qe(e){return e?Be[e.toLowerCase()]??"any":"any"}function He(e,t){const o=e[t];if(o&&"object"==typeof o)return o.value}function Ke(e,t){const o=He(e,t);return"number"==typeof o&&Number.isFinite(o)?o:void 0}function Ve(e,t,o){const n=e??{},r=(e=>{const t=He(e,y.ENUM);if(Array.isArray(t)&&t.every(je))return t})(n);if(r)return{type:"enum",values:r};const i=(e=>{const t=e[y.TYPE],o=t?.customTypes?.[0],n="function"==typeof o?o.name:o?.name;if(n)return n})(n)??o;return i?{type:"model",name:i}:((e,t)=>{switch(qe(e)){case"string":{const t=(e=>{if(e)return We[e.toLowerCase()]})(e);return void 0!==t?{type:"string",format:t}:{type:"string"}}case"number":{const o={type:"number"};e&&"integer"===e.toLowerCase()&&(o.integer=!0);const n=Ke(t,y.MIN),r=Ke(t,y.MAX);return void 0!==n&&(o.min=n),void 0!==r&&(o.max=r),o}case"boolean":return{type:"boolean"};case"array":return((e,t)=>{const o={type:"array",items:ze(e,t)},n=Ke(e,y.MIN),r=Ke(e,y.MAX);return void 0!==n&&(o.minItems=n),void 0!==r&&(o.maxItems=r),o})(t,e);case"object":return{type:"object",properties:{}};case"enum":return{type:"enum",values:[]};case"model":return{type:"model",name:e??"any"};default:return{type:"any"}}})(t,n)}function ze(e,t){if((e=>{const t=e[y.LIST];return!!t?.clazz?.length})(e))return{type:"model",name:Je(e)};const o=He(e,y.TYPE);if("string"==typeof o){const e=qe(o);return"model"===e?{type:"model",name:o}:{type:e}}if(t&&"array"!==t){const e=qe(t);return"model"===e?{type:"model",name:t}:{type:e}}return{type:"any"}}function Je(e){const t=e[y.LIST],o=t?.clazz?.[0];if("function"!=typeof o)return"any";if(o.name)return o.name;try{const e=o();if("function"==typeof e&&e.name)return e.name}catch{return"any"}return"any"}function Xe(e){return"workflow"===e.scope}function Ye(e){return"node"===e.scope}function Qe(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"workflow"===t.scope?"string"==typeof t.port&&2===Reflect.ownKeys(t).length:"node"===t.scope&&"string"==typeof t.nodeId&&"string"==typeof t.port&&3===Reflect.ownKeys(t).length}function Ze(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e.mode;if("edge"===t)return 1===Reflect.ownKeys(e).length;if("literal"===t){const t=e.value;return 2===Object.keys(e).length&&Ge(t)}return"expression"===t&&2===Object.keys(e).length&&"string"==typeof e.expression}const et=["any","string","number","boolean","array","object","enum","model"];function tt(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&(e=>et.includes(e))(e.type)}function ot(e,t={seen:[]}){if(t.seen.includes(e))throw new A(`Document '${(e=>{const t=e?.id;return"string"==typeof t?t:"<unnamed document>"})(e)}' contains a loop body that references itself (cyclic document)`);if("string"!=typeof e.id||!e.id)throw new A("Document 'id' is required and must be a non-empty string");if("string"!=typeof e.name||!e.name)throw new A("Document 'name' is required and must be a non-empty string");const o=new Set;for(const t of[...e.inputs,...e.outputs]){if("string"!=typeof t.id||!t.id)throw new A("Workflow port 'id' is required and must be a non-empty string");if(o.has(t.id))throw new A(`Workflow port '${t.id}' is declared more than once; workflow port ids must be unique`);if(void 0!==t.schema&&!tt(t.schema))throw new A(`Workflow port '${t.id}' schema must be a valid GraphValueSchema`);o.add(t.id)}const n={seen:[...t.seen,e]},r=new Set;for(const t of e.nodes)nt(t,r);for(const t of e.nodes)t.loop&&rt(t,t.loop,n),t.errorBoundary&&it(t,t.errorBoundary,n);const i=new Set;for(const t of e.edges)st(t,i);for(const t of e.edges)dt(t.source,0,o,r,`Edge '${t.id}' source`),dt(t.target,0,o,r,`Edge '${t.id}' target`);if(void 0!==e.settings&&!Ue(e.settings))throw new A("Document settings must be JSON-safe (a map of JSON-safe values)");if(void 0!==e.metadata&&!Ue(e.metadata))throw new A("Document metadata must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed");if(void 0!==e.ui&&!Ue(e.ui))throw new A("Document ui must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed")}function nt(e,t){if("string"!=typeof e.id||!e.id)throw new A("Node 'id' is required and must be a non-empty string");if(t.has(e.id))throw new A(`Node id '${e.id}' is declared more than once; node ids must be unique`);if("string"!=typeof e.kind||!e.kind)throw new A(`Node '${e.id}' must declare a non-empty string 'kind'`);if(void 0===e.parameters||null===e.parameters)throw new A(`Node '${e.id}' parameters must be present (an empty object when there are none)`);if(t.add(e.id),e.inputBindings)for(const[t,o]of Object.entries(e.inputBindings)){if(Le(t))throw new A(`Node '${e.id}' input binding key '${t}' is not allowed (unsafe prototype-pollutant key)`);if(!Ze(o))throw new A(`Node '${e.id}' input binding for '${t}' must be a valid GraphInputBinding (edge, literal, or expression)`);if("literal"===o.mode&&!Ue(o.value))throw new A(`Node '${e.id}' literal binding for '${t}' must contain JSON-safe values`);if("expression"===o.mode&&!o.expression)throw new A(`Node '${e.id}' expression binding for '${t}' must contain a non-empty expression`)}if(e.outputBindings)for(const[t,o]of Object.entries(e.outputBindings)){if(Le(t))throw new A(`Node '${e.id}' output binding key '${t}' is not allowed (unsafe prototype-pollutant key)`);if(!o||"object"!=typeof o||Array.isArray(o))throw new A(`Node '${e.id}' output binding for '${t}' must be an object with enabled and alias settings`)}if(!Ue(e.parameters))throw new A(`Node '${e.id}' parameters must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed`);if(void 0!==e.state){if(!e.state||"object"!=typeof e.state||Array.isArray(e.state))throw new A(`Node '${e.id}' state must be an object when present`);if(!Ue(e.state))throw new A(`Node '${e.id}' state must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed`)}}function rt(e,t,o){if(!t.body||"object"!=typeof t.body)throw new A(`Node '${e.id}' loop configuration requires a body document`);if(ot(t.body,o),!(void 0===t.maxIterations||Number.isFinite(t.maxIterations)&&t.maxIterations>0))throw new A(`Node '${e.id}' loop maxIterations must be a positive number`);if(void 0!==t.timeoutMs&&("number"!=typeof t.timeoutMs||0>=t.timeoutMs))throw new A(`Node '${e.id}' loop timeoutMs must be a positive number in milliseconds`);if(void 0!==t.concurrency&&("number"!=typeof t.concurrency||0>=t.concurrency))throw new A(`Node '${e.id}' loop concurrency must be a positive number`);for(const o of[t.inputMappings,t.outputMappings])if(o)for(const[t,n]of Object.entries(o)){if(Le(t))throw new A(`Node '${e.id}' loop mapping key '${t}' is not allowed (unsafe prototype-pollutant key)`);at(n,e.id,t)}}function it(e,t,o){if(!t.try||"object"!=typeof t.try)throw new A(`Node '${e.id}' error-boundary configuration requires a try body document`);ot(t.try,o);for(const[n,r]of[["catch",t.catch],["finally",t.finally]])if(void 0!==r){if(!r||"object"!=typeof r)throw new A(`Node '${e.id}' error-boundary ${n} body must be a document`);ot(r,o)}}function at(e,t,o){if(!e||"object"!=typeof e)throw new A(`Node '${t}' loop mapping '${o}' must reference a workflow port, node port, literal, or expression`);switch(e.source){case"workflow":if("string"!=typeof e.port||!e.port)throw new A(`Node '${t}' loop mapping '${o}' referencing a workflow must reference a port identifier`);break;case"node":if("string"!=typeof e.nodeId||!e.nodeId||"string"!=typeof e.port||!e.port)throw new A(`Node '${t}' loop mapping '${o}' referencing a node must reference a node id and a port`);break;case"literal":if(!Ue(e.value))throw new A(`Node '${t}' loop mapping '${o}' literal references must be JSON-safe values`);break;case"expression":if("string"!=typeof e.expression||!e.expression)throw new A(`Node '${t}' loop mapping '${o}' expression references must be non-empty expressions`);break;default:throw new A(`Node '${t}' loop mapping '${o}' must use a workflow, node, literal, or expression reference source`)}}function st(e,t){if("string"!=typeof e.id||!e.id)throw new A("Edge 'id' is required and must be a non-empty string");if(t.has(e.id))throw new A(`Edge id '${e.id}' is declared more than once; edge ids must be unique`);if(!Qe(e.source))throw new A(`Edge '${e.id}' source endpoint is not a valid GraphEndpoint`);if(!Qe(e.target))throw new A(`Edge '${e.id}' target endpoint is not a valid GraphEndpoint`);if("data"!==e.type&&"connection"!==e.type)throw new A(`Edge '${e.id}' type '${e.type+""}' is not a valid edge type (data or connection are allowed)`);if(t.add(e.id),!Ue(e))throw new A(`Edge '${e.id}' contains values that are not JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed`)}function dt(e,t,o,n,r){if(Xe(e)){if(!o.has(e.port))throw new A(`${r} references workflow port '${e.port}' which is not declared on the document`)}else if(Ye(e)){if(!n.has(e.nodeId))throw new A(`${r} references node '${e.nodeId}' which is not part of the document`);if("string"!=typeof e.port||!e.port)throw new A(r+" node endpoints must reference a non-empty port identifier")}}const lt=["expression","template"],ct=["javascript","typescript","json","text"];function ut(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return!(!(e=>lt.includes(e))(t.mode)||"string"!=typeof t.expression||!t.expression||void 0!==t.language&&!(e=>ct.includes(e))(t.language)||void 0!==t.metadata&&!Ge(t.metadata))}function pt(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.name&&Array.isArray(t.inputs)&&Array.isArray(t.outputs)&&Array.isArray(t.nodes)&&Array.isArray(t.edges)}function ht(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.type&&(void 0===t.required||"boolean"==typeof t.required)&&(void 0===t.displayName||"string"==typeof t.displayName)&&(void 0===t.allowedOperations||Array.isArray(t.allowedOperations)&&t.allowedOperations.every(e=>"string"==typeof e))}const ft=["trigger","loop","branching","stateful","retryable","cancellable","parallel","resource"];function gt(e){return ft.includes(e)}function mt(e){if(!(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.kind&&"object"==typeof t.display&&Array.isArray(t.inputs)&&Array.isArray(t.outputs)&&Array.isArray(t.parameters)})(e))throw new A("Graph node manifest does not conform to the required shape");if(!Ue(e))throw new A("Graph node manifest contains values that are not JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys or unsafe prototype keys are not allowed on manifests")}const yt=["loadOptions","listSearch","resourceLocator","resourceMapping","validateParameter","action"];function wt(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.name&&(e=>yt.includes(e))(t.type)&&(void 0===t.parameter||"string"==typeof t.parameter)&&(void 0===t.dependencies||Array.isArray(t.dependencies)&&t.dependencies.every(e=>"string"==typeof e))}function bt(e){const t=e.element?.props?.value,o=t??e.prop?.value??e.validation?.defaultValue;if(void 0!==o&&"function"!=typeof o&&Ue(o))try{return JSON.parse(JSON.stringify(o))}catch{return}}function vt(e){if(e.type&&e.type in We)return{type:"string",format:We[e.type]};const t=(e=>{for(const t of[e.graph?.type,e.element?.props?.type,e.prop?.type])if("string"==typeof t&&"any"!==qe(t))return t})(e);return t?Ve((e=>{if(!e)return;const t=Object.entries(e).filter(([e])=>e!==y.TYPE);return Object.fromEntries(t)})(e.validation),t):Ve(e.validation,e.type,e.model)}function It(e){const t={};for(const[o,n]of Object.entries(e.graph?.metadata??{}))Ue(n)&&(t[o]=JSON.parse(JSON.stringify(n)));return Object.keys(t).length?t:void 0}function Et(e){switch(e){case"output":return"output";case"connection":return"connection";default:return"input"}}function Nt(e){const t=e.graph?.handle;return"connection"!==e.direction&&"string"==typeof t&&t?t:e.path??e.property}function Ot(e,t){const o={id:Nt(e),label:e.label,direction:Et(e.direction),schema:vt(e)};e.required&&(o.required=!0),e.hidden&&(o.hidden=!0);const n=e.graph?.category;"string"==typeof n&&(o.category=n),!0===e.graph?.userControlled&&(o.configurable=!0);const r=e.graph?.handle;"string"==typeof r&&(o.handle=r);const i=Ct(e.graph?.connectionRules)??t;i&&(o.connectionPolicy=i);const a=(e=>{const t=e.element;if(!t||!Ue(t))return;const o=t.tag;if("string"!=typeof o)return;const n=t.props;return{tag:o,serialize:!0===t.serialize,props:n&&"object"==typeof n&&!Array.isArray(n)?Fe(n):{}}})(e);a&&(o.element=a);const s=It(e);return s&&(o.metadata=s),o}function kt(e){const t={type:"string",id:Nt(e),label:e.label,required:e.required};if(e.hidden)return((e,t)=>{const o={...t,type:"hidden"},n=bt(e);return void 0!==n&&(o.defaultValue=n),At(o)})(e,t);const o=bt(e);void 0!==o&&(t.defaultValue=o);const n=(e=>{const t=e.element?.props?.placeholder??e.prop?.placeholder;return"string"==typeof t?t:void 0})(e);n&&(t.placeholder=n);const r=It(e);if(r&&(t.metadata=r),(e=>{const t=St(e);return"code"===t||"code-editor"===t})(e))return At({...t,type:"code",language:Rt(e)});const i=vt(e);switch(i.type){case"number":{const o={...t,type:"number",integer:i.integer,min:i.min,max:i.max},n=_t(e.validation?.step);return void 0!==n&&(o.step=n),At(o)}case"boolean":return At({...t,type:"boolean"});case"enum":return At({...t,type:"options",options:i.values.map(e=>({value:e,label:e+""}))});case"array":{const e={...t,type:"collection"};return void 0!==i.maxItems&&(e.maxItems=i.maxItems),At(e)}case"object":case"model":return At({...t,type:"object"});default:return At({...t,type:"string",multiline:!!Dt(e)||void 0,pattern:xt(e.validation?.pattern),minLength:_t(e.validation?.minlength),maxLength:_t(e.validation?.maxlength)})}}function At(e){const t=e;for(const e of Object.keys(t))void 0===t[e]&&delete t[e];return e}function xt(e){const t=e?.value;return"string"==typeof t?t:void 0}function _t(e){const t=e?.value;return"number"==typeof t&&Number.isFinite(t)?t:void 0}function St(e){const t=e.element?.tag;return"string"==typeof t&&t?t:void 0}function Dt(e){return"textarea"===St(e)||"textarea"===(e=>{const t=e.element?.props?.type;return"string"==typeof t?t:void 0})(e)}const Pt=["javascript","typescript","json","text"];function Rt(e){const t=e.element?.props?.language;return"string"==typeof t&&Pt.includes(t)?t:"javascript"}function $t(e,t){const o={name:t.name??e.name},n=e.graph?.metadata?.description??void 0;"string"==typeof n&&n&&(o.description=n);const r=t.category??e.category;"string"==typeof r&&r&&(o.category=r),"string"==typeof e.group&&e.group&&(o.group=e.group),Array.isArray(e.labels)&&(o.labels=e.labels.slice());const i=((e,t)=>{if(t.icon)return t.icon;const o=e.effectiveIcon??e.icon;return"string"==typeof o?{type:"catalogue",name:o}:{type:"catalogue",name:"ph:circuitry"}})(e,t);return i&&(o.icon=i),"string"==typeof e.color&&e.color&&(o.color=e.color),"number"==typeof e.width&&Number.isFinite(e.width)&&(o.width=e.width),"number"==typeof e.minWidth&&Number.isFinite(e.minWidth)&&(o.minWidth=e.minWidth),"number"==typeof e.height&&Number.isFinite(e.height)&&(o.height=e.height),"string"==typeof e.shape&&(o.shape=e.shape),"number"==typeof e.cornerRadius&&Number.isFinite(e.cornerRadius)&&(o.cornerRadius=e.cornerRadius),Array.isArray(e.sizeRules)&&(o.sizeRules=e.sizeRules),o}function Ct(e){if(!e)return;const t=e,o={};"boolean"==typeof t.allowSelf&&(o.allowSelf=t.allowSelf),"boolean"==typeof t.allowMultiple&&(o.allowMultiple=t.allowMultiple);const n=t.allowedKinds;Array.isArray(n)&&n.every(e=>"string"==typeof e)&&(o.allowedNodeKinds=n);const r=t.blockedKinds;Array.isArray(r)&&r.every(e=>"string"==typeof e)&&(o.blockedNodeKinds=r);const i=t.maxConnections;return"number"==typeof i&&Number.isFinite(i)&&(o.maxConnections=i),Object.keys(o).length?o:void 0}function Tt(e,t={}){const o="function"==typeof e?e:e.constructor;if(!ve(o))throw new A(`Node '${o?.name??e+""}' is not decorated with @node and cannot produce a manifest`);const n=xe(o),r=Ae(Oe(o)),i=[],a=[],s=[],d=[],l=Ct(n.graph?.connectionRules);for(const e of r)("connection"===e.direction?s:"output"===e.direction?a:i).push(Ot(e,l)),"input"===e.direction&&d.push(kt(e));const c={kind:t.kind??n.kind??n.name,display:$t(n,t),inputs:i,outputs:a,parameters:d};return s.length&&(c.connections=s),n.namespaces?.length&&(c.namespaces=n.namespaces.slice()),mt(c),c}var Lt,Mt;(e=>{e.READABILITY="readability",e.COMPACTNESS="compactness",e.BALANCED="balanced"})(Lt||(Lt={})),(e=>{e.TIGHT="tight",e.NORMAL="normal",e.COMFORTABLE="comfortable"})(Mt||(Mt={})),Mt.TIGHT,Mt.NORMAL,Mt.COMFORTABLE,Lt.READABILITY,Mt.COMFORTABLE,Lt.COMPACTNESS,Mt.TIGHT,Lt.BALANCED,Mt.NORMAL;let jt=class extends T{constructor(e){super(e)}};S([P({type:String,generated:!1}),f("Unique graph run id"),i("ngx-decaf-crud-field",{label:"graph.run.id.label",readonly:!0}),D("design:type",String)],jt.prototype,"runId",void 0),S([R(),b(),$(),f("Workflow document id the run executes"),a("workflowId"),i("ngx-decaf-crud-field",{label:"graph.run.workflowId.label"}),D("design:type",String)],jt.prototype,"workflowId",void 0),S([R(),f("Owning user; absent for anonymous callers"),i("ngx-decaf-crud-field",{label:"graph.run.owner.label"}),D("design:type",String)],jt.prototype,"owner",void 0),S([R(),b(),v(String),$(),f("Current run lifecycle status"),a("status"),i("ngx-decaf-crud-field",{label:"graph.run.status.label",readonly:!0}),D("design:type",String)],jt.prototype,"status",void 0),S([R(),f("Fingerprint of the executed document"),i("ngx-decaf-crud-field",{label:"graph.run.fingerprint.label",readonly:!0}),D("design:type",String)],jt.prototype,"documentFingerprint",void 0),S([R(),g(),f("Workflow input values keyed by input port id"),D("design:type",Object)],jt.prototype,"inputs",void 0),S([R(),g(),f("Execution result, present on successful completion"),D("design:type",Object)],jt.prototype,"result",void 0),S([R(),g(),f("Structured error payload, present on failure"),D("design:type",Object)],jt.prototype,"error",void 0),S([I(),R(),f("Run creation timestamp"),D("design:type",Date)],jt.prototype,"createdAt",void 0),S([I(),R(),f("Execution start timestamp, once it has started"),D("design:type",Date)],jt.prototype,"startedAt",void 0),S([I(),R(),f("Terminal-state timestamp, once the run has finished"),D("design:type",Date)],jt.prototype,"finishedAt",void 0),jt=S([s("ngx-decaf-list-item",{icon:"ti-player-play"}),r("ngx-decaf-crud-form"),f("Persistable graph run lifecycle record"),C("graph_run"),E(),D("design:paramtypes",[Object])],jt);let Gt=class extends T{constructor(e){super(e)}};S([P({type:String,generated:!1}),D("design:type",String)],Gt.prototype,"workflowId",void 0),S([R(),D("design:type",String)],Gt.prototype,"name",void 0),S([R(),D("design:type",Object)],Gt.prototype,"document",void 0),S([R(),D("design:type",String)],Gt.prototype,"owner",void 0),S([R(),D("design:type",Object)],Gt.prototype,"snapshot",void 0),Gt=S([C("graph_workflow"),E(),D("design:paramtypes",[Object])],Gt),oe("Trigger",{color:"#3b82f6",icon:"ti-bolt"}),oe("Flow Control",{color:"#f59e0b",icon:"ti-arrows-split-2"}),oe("Utility",{color:"#0d9488",icon:"ti-tool"}),oe("Loop",{color:"#eab308",icon:"ti-repeat"}),oe("Workflow",{color:"#f97316",icon:"ti-sitemap"}),oe("Pipeline",{color:"#0ea5e9",icon:"ti-git-merge"}),oe("Node",{color:"#8b5cf6",icon:"ti-point-filled"}),oe("Agent",{color:"#7c3aed",icon:"ti-robot"}),oe("model",{color:"#3b82f6",icon:"ti-cpu"}),oe("memory",{color:"#10b981",icon:"ti-database"}),oe("workspace",{color:"#f59e0b",icon:"ti-folder"});const Ut=new Set;function Ft(e,t){return e.config[t]}function Bt(e){return Array.isArray(e)?e.map(e=>e+"").join(", "):e+""}(()=>{const t=[{key:le.NODE_ID,shouldInclude:e=>null!=Ft(e,le.NODE_ID),render:e=>Ft(e,le.NODE_ID)+""},{key:le.WORKFLOW_ID,shouldInclude:e=>null!=Ft(e,le.WORKFLOW_ID),render:e=>Ft(e,le.WORKFLOW_ID)+""},{key:le.RUN_ID,shouldInclude:e=>null!=Ft(e,le.RUN_ID),render:e=>Ft(e,le.RUN_ID)+""},{key:le.USER,shouldInclude:e=>null!=Ft(e,le.USER),render:e=>Ft(e,le.USER)+""},{key:le.ROLES,shouldInclude(e){const t=Ft(e,le.ROLES);return Array.isArray(t)&&t.length>0},render:e=>Bt(Ft(e,le.ROLES))},{key:le.NAMESPACES,shouldInclude(e){const t=Ft(e,le.NAMESPACES);return Array.isArray(t)&&t.length>0},render:e=>Bt(Ft(e,le.NAMESPACES))},{key:le.ORGANIZATION,shouldInclude:e=>null!=Ft(e,le.ORGANIZATION),render:e=>Ft(e,le.ORGANIZATION)+""},{key:le.IP,shouldInclude:e=>null!=Ft(e,le.IP),render:e=>Ft(e,le.IP)+""}];for(const o of t)Ut.has(o.key)||(e.register(o),Ut.add(o.key))})();const Wt="$workflow",qt="local",Ht=4,Kt=100,Vt=1e3,zt=1e3,Jt=1e4,Xt=3e4,Yt="graph.pinnable";var Qt,Zt;(e=>{e.MANUAL="manual",e.AUTOMATIC="automatic",e.DISABLED="disabled"})(Qt||(Qt={})),(e=>{e.TRUTHY="truthy",e.FALSY="falsy",e.EQUALS="equals",e.NOT_EQUALS="notEquals",e.GREATER_THAN="greaterThan",e.GREATER_THAN_OR_EQUAL="greaterThanOrEqual",e.LESS_THAN="lessThan",e.LESS_THAN_OR_EQUAL="lessThanOrEqual",e.EXISTS="exists",e.CUSTOM="custom"})(Zt||(Zt={}));const eo={FOREACH:"core.loop.foreach",WHILE:"core.loop.while",UNTIL:"core.loop.until"};class to extends x{constructor(e,t="GRAPH_EXECUTION_ERROR",o){super(e,to.name,500),this.graphCode=t,this.details=o,this.name=this.constructor.name}}class oo extends to{constructor(e){super("Graph workflow contains an unsupported cycle","GRAPH_CYCLE_ERROR",e)}}class no extends to{constructor(e,t){super(e,"GRAPH_INPUT_ERROR",t)}}class ro extends to{constructor(e,t){super(e,"GRAPH_LOOP_LIMIT_ERROR",t)}}class io extends to{constructor(e,t){super(e,"GRAPH_PINNING_ERROR",t)}}class ao extends to{constructor(e,t){super(e,"GRAPH_PORT_ERROR",t)}}class so extends to{constructor(e,t){super(e,"GRAPH_STORE_ERROR",t)}}class lo extends to{constructor(e,t){super(e,"GRAPH_TOPOLOGY_ERROR",t)}}class co extends to{constructor(e){super("Break signal","GRAPH_BREAK_SIGNAL",{value:e}),this.isBreakSignal=!0,this.name="GraphBreakSignal"}}class uo extends to{constructor(e){super(`Graph run '${e}' was cancelled`,"GRAPH_RUN_CANCELLED",{runId:e}),this.name=uo.name}}class po extends A{constructor(e){super(`Graph workflow document rejected with ${e.length} issue(s): ${e.map(e=>`${e.code} at ${e.path} (${e.message})`).join("; ")}`),this.name=po.name,this.issues=e}}class ho{constructor(){this.observers=new Set}observe(e){return this.observers.add(e),()=>this.unObserve(e)}unObserve(e){this.observers.delete(e)}async updateObservers(e){await Promise.all(Array.from(this.observers).map(async t=>{try{await Promise.resolve(t.refresh(e))}catch{}}))}}class fo{constructor(){this.sequence=0}create(e){return{...e,id:this.createEventId(),sequence:++this.sequence,timestamp:new Date}}createEventId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new to("Cannot generate a graph event id: crypto.randomUUID is unavailable in this runtime","GRAPH_EVENT_ID_ERROR",{runtime:typeof globalThis.crypto});return e.randomUUID()}}function go(e){if("string"!=typeof e)return;const t=e.trim();if(!t)return;const o=t.split(".");if(3!==o.length)return;const n=o[0].trim(),r=o[2].trim(),i=o[1].split(",").map(e=>e.trim()).filter(e=>e.length>0);return n&&r&&0!==i.length?{organization:n,departments:i,role:r}:void 0}function mo(e){return`${e.organization}.${e.departments.join(",")}.${e.role}`}function yo(e){if(!e||"string"!=typeof e.namespace||!e.parts)return!1;const t=go(e.namespace);return!!t&&mo(t)===mo(e.parts)}function wo(e,t){const o="string"==typeof e?e.trim():"";if(o){if(t)for(const e of t)if(e&&e.namespace===o&&yo(e))return e.parts;return go(o)}}function bo(e,t,o={},n){const r=wo(e,n),i=wo(t,n);return!(!r||!i)&&r.organization===i.organization&&r.role===i.role&&("exact"===(o.mode??"inherit")?r.departments.length===i.departments.length&&r.departments.every((e,t)=>e===i.departments[t]):r.departments.length<=i.departments.length&&r.departments.every((e,t)=>e===i.departments[t]))}function vo(e,t,o={},n){return e.filter(e=>!t.some(t=>bo(t,e,o,n)))}function Io(e){return e.filter(e=>void 0===go(e))}function Eo(e,t){const o=new Set;for(const n of e){const e=wo(n,t);e&&o.add(e.role)}return[...o]}function No(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}function Oo(e,t){try{const o=e.cache;if(o&&void 0!==o[t]&&null!==o[t])return o[t]}catch{}try{return e.get(t)}catch{return}}function ko(e){if(!e)return{};const t={},o=e.user;"string"==typeof o&&o&&(t.user=o);const n=e.organization;"string"==typeof n&&n&&(t.organization=n);const r=e.ip;"string"==typeof r&&r&&(t.ip=r);const i=No(e.roles);i&&(t.roles=i);const a=No(e.namespaces);return a&&(t.namespaces=a,t.namespaceCache=xo(a)),t}function Ao(e){return e?ko({user:Oo(e,"user"),organization:Oo(e,"organization"),ip:Oo(e,"ip"),roles:Oo(e,"roles"),namespaces:Oo(e,"namespaces")}):{}}function xo(e){const t=[];for(const o of e){const e=go(o);e&&t.push({namespace:o,parts:e})}return t}function _o(...e){const t={};for(const o of e)o&&(void 0!==o.user&&(t.user=o.user),void 0!==o.organization&&(t.organization=o.organization),void 0!==o.ip&&(t.ip=o.ip),void 0!==o.roles&&(t.roles=o.roles),void 0!==o.namespaces&&(t.namespaces=o.namespaces),void 0!==o.namespaces?t.namespaceCache=o.namespaceCache??xo(o.namespaces):void 0!==o.namespaceCache&&(t.namespaceCache=o.namespaceCache));return t}class So{constructor(e={}){this.options=e}get enabled(){return!0===this.options.enabled}validate(e,o,n,r){if(!this.enabled)return;const i=r??this.options.logger??t.for("GraphAuth"),a=e.id||e.name||o.workflowId,s=(e=>{if(!e||"object"!=typeof e)return;const t=e.auth;return t&&"object"==typeof t&&!Array.isArray(t)?(e=>{if(!e)return;const t=fe(e.namespaces),o=fe(e.roles);if(!t&&!o)return;const n={};return t&&(n.namespaces=t),o&&(n.roles=o),n})(t):void 0})(e.metadata);this.assertGranted(`workflow '${a}'`,s?.namespaces??[],n,s?.roles??[],i);for(const e of o.nodes)this.assertGranted(`node '${e.id}'`,e.manifest.namespaces??[],n,[],i)}assertGranted(e,t,o,n,r){const i=o.namespaces??[],a=vo(t,i,this.options.match,o.namespaceCache),s=Eo(i,o.namespaceCache),d=n.filter(e=>!s.includes(e));if(0===a.length&&0===d.length)return;const l=[...new Set([...Io(t),...Io(i)])],c=[];throw a.length&&c.push("namespace(s) "+a.join(", ")),d.length&&c.push("role(s) "+d.join(", ")),r.warn(`Graph access denied for ${e} for user ${o.user??"anonymous"}: missing ${c.join(" and ")}${l.length?`; malformed namespace(s) ${l.join(", ")} failed closed`:""}`),new L(`Access to ${e} requires ${c.join(" and ")}`)}}class Do{constructor(e){this.baseOptions=e,this.inner=t.for("GraphRun").for(this.attributeConfig(e))}attributeConfig(e){return{[le.NODE_ID]:e.nodeId,[le.WORKFLOW_ID]:e.workflowId,[le.RUN_ID]:e.runId,[le.USER]:e.user??null,[le.ROLES]:e.roles,[le.NAMESPACES]:e.namespaces,[le.ORGANIZATION]:e.organization,[le.IP]:e.ip}}emit(e,t,o){const n="string"==typeof t?t:t instanceof Error?t.message:t+"",r={level:e,message:n,timestamp:(new Date).toISOString(),runId:this.baseOptions.runId,workflowId:this.baseOptions.workflowId,nodeId:this.baseOptions.nodeId,user:this.baseOptions.user??null};void 0!==this.baseOptions.roles&&(r.roles=this.baseOptions.roles),void 0!==this.baseOptions.namespaces&&(r.namespaces=this.baseOptions.namespaces),void 0!==this.baseOptions.organization&&(r.organization=this.baseOptions.organization),void 0!==this.baseOptions.ip&&(r.ip=this.baseOptions.ip),void 0!==o&&(r.payload=o),this.baseOptions.forward({type:ce.GRAPH_RUN_LOG,payload:r}).catch(()=>{}),{benchmark:(e,t)=>this.inner.benchmark(e,t),fatal:(e,t)=>this.inner.fatal(e,t),critical:(e,t)=>this.inner.critical(e,t),silly:(e,t)=>this.inner.silly(e,t),trace:(e,t)=>this.inner.trace(e,t),verbose:(e,t)=>this.inner.verbose(e,t),info:(e,t)=>this.inner.info(e,t),warn:(e,t)=>this.inner.warn(e,t),error:(e,t)=>this.inner.error(e,t),debug:(e,t)=>this.inner.debug(e,t)}[e](n,o)}benchmark(e,t){this.emit("benchmark",e,t)}fatal(e,t,o){this.emit("fatal",e,t??o)}critical(e,t,o){this.emit("critical",e,t??o)}silly(e,t,o){this.emit("silly",e,"object"==typeof t?t:o)}trace(e,t){this.emit("trace",e,t)}verbose(e,t,o){this.emit("verbose",e,"object"==typeof t?t:o)}info(e,t){this.emit("info",e,t)}error(e,t,o){this.emit("error",e,t??o)}warn(e,t){this.emit("warn",e,t)}debug(e,t){this.emit("debug",e,t)}action(e,t,o){this.inner.action(e,t,o)}setConfig(){}for(e,t,...o){return this}clear(){return this}get root(){return this.inner.root}}function Po(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}class Ro extends M{constructor(e,t,o,n,r,i,a,s,d={},l,c,u){super(),this.runId=e,this.parentRunId=t,this.workflowId=o,this.document=n,this.node=r,this.manifest=i,this.path=a,this.emitFn=s,this.metadata=d,this.engine=l,this.abortSignal=c,this.limits=u;const p=ko(d);this.accumulate({...p,operation:"execute"});const h="string"==typeof d?.user?d.user:null;this.runLogger=new Do({runId:e,workflowId:o,nodeId:r.id,user:h,roles:Po(d?.roles),namespaces:Po(d?.namespaces),organization:"string"==typeof d?.organization?d.organization:void 0,ip:"string"==typeof d?.ip?d.ip:void 0,forward:async e=>{await this.emit(e)}})}get logger(){return this.runLogger}get auth(){return Ao(this)}async emit(e){await this.emitFn({...e,runId:this.runId,parentRunId:this.parentRunId,workflowId:this.workflowId,nodeId:this.node.id,path:e.path??this.path})}async progress(e){await this.emit({type:ce.NODE_OUTPUT,payload:e})}async log(e,t){await this.emit({type:ce.NODE_OUTPUT,payload:{message:e,payload:t}})}}class $o{constructor(e,t,o,n){this.nodeResults=new Map,this.events=[],this.activeDataEdges=new Set,this.runId=e,this.plan=t,this.valueStore=o,this.eventFactory=n,this.startedAt=new Date}recordNodeResult(e){this.nodeResults.set(e.nodeId,e)}activateDataEdge(e){this.activeDataEdges.add(e)}isDataEdgeActive(e){return this.activeDataEdges.has(e)}appendEvent(e){this.events.push(e)}finish(){this.finishedAt=new Date}}function Co(e,t,o,n,r){const i=e.valueStore.getWorkflowValues(),a={};for(const[t,o]of e.nodeResults)a[t]=o;const s=[...e.events];return{runId:e.runId,workflowId:t.id||t.name,status:n,document:t,inputs:{...o},outputs:i,nodeResults:a,events:s,startedAt:e.startedAt,finishedAt:e.finishedAt,metadata:r}}class To{constructor(e,t,o){this.emitter=e,this.eventFactory=t,this.options=o}get engine(){return this.options.engine}get codeSandboxEvaluator(){return this.options.codeSandboxEvaluator}get frame(){return this._frame}bindFrame(e){this._frame=e}async emit(e){const t=this.eventFactory.create({id:"",sequence:0,timestamp:new Date,runId:this.options.runId,parentRunId:this.options.parentRunId,workflowId:this.options.workflowId,type:ce.NODE_OUTPUT,path:this.options.path??[],...e});this._frame?.appendEvent(t),await this.emitter.updateObservers(t)}async updateObservers(e){await this.emitter.updateObservers(e)}}function Lo(e){const t=e.capabilities;return{codeMode:t?.codeMode??e.codeMode,workflows:{list:t?.workflows?.list??("function"==typeof e.listWorkflows?"supported":"not_supported"),get:t?.workflows?.get??("function"==typeof e.getWorkflow?"supported":"not_supported")}}}class Mo{static{this._cache={}}static register(e,t){return Mo._cache[e]=t,t}static get(e){const t=e??Mo._currentFlavour;if(t)return Mo._cache[t]}static getOrFail(e){const t=Mo.get(e);if(!t)throw new to(`No graph execution backend registered under '${e}'`,"GRAPH_EXECUTION_BACKEND_NOT_REGISTERED");return t}static get current(){return Mo.get()}static get currentFlavour(){return Mo._currentFlavour??qt}static setCurrent(e){Mo._currentFlavour=e}static list(){return Object.entries(Mo._cache).map(([e,t])=>({flavour:e,backend:t}))}static unregister(e){e&&(delete Mo._cache[e],Mo._currentFlavour===e&&(Mo._currentFlavour=void 0))}static clear(){for(const e of Object.keys(Mo._cache))delete Mo._cache[e];Mo._currentFlavour=void 0}}class jo{evaluate(e,t){switch(e.op){case"eq":return this.resolveValue(e.left,t)===this.resolveValue(e.right,t);case"neq":return this.resolveValue(e.left,t)!==this.resolveValue(e.right,t);case"gt":return Number(this.resolveValue(e.left,t))>Number(this.resolveValue(e.right,t));case"gte":return Number(this.resolveValue(e.left,t))>=Number(this.resolveValue(e.right,t));case"lt":return Number(this.resolveValue(e.left,t))<Number(this.resolveValue(e.right,t));case"lte":return Number(this.resolveValue(e.left,t))<=Number(this.resolveValue(e.right,t));case"and":return e.conditions.every(e=>this.evaluate(e,t));case"or":return e.conditions.some(e=>this.evaluate(e,t));case"not":return!this.evaluate(e.condition,t);case"exists":return void 0!==this.resolveValue(e.value,t)&&null!==this.resolveValue(e.value,t);default:throw new to(`Unknown ConditionExpression op '${e.op}'`,"GRAPH_UNKNOWN_CONDITION_OP",{expr:e})}}resolveValue(e,t){if("const"in e)return e.const;if("path"in e&&!("step"in e))return this.resolvePath(e.path,t);if("step"in e&&"path"in e){const o=t?.nodes;if(o&&"object"==typeof o){const t=o[e.step];return this.resolvePath(e.path,t)}return this.resolvePath(e.path,t)}throw new to("Invalid ExprValue: must have `const`, `path`, or `step`+`path`","GRAPH_INVALID_EXPR_VALUE",{ref:e})}resolvePath(e,t){if(!e)return t;const o=e.split(".");let n=t;for(const e of o){if(null==n)return;n=n[e]}return n}}function Go(e){return"object"==typeof e&&null!==e&&"type"in e&&"code"===e.type}function Uo(e){return"object"==typeof e&&null!==e&&"op"in e&&"string"==typeof e.op}async function Fo(e,t,o){const n=o.engine?.codeSandboxEvaluator;if(!n)throw new to("Code conditions require a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator","GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{code:e.code});await o.log("Evaluating code condition",{language:e.language??"javascript"});const r=o.metadata;return!!await n.evaluate({code:e.code,language:e.language,input:t,vars:r?.vars??void 0,item:r?.item,index:r?.index,nodes:r?.nodes??void 0,logger:o.logger,abortSignal:o.abortSignal})}function Bo(e,t,o){if(Uo(e))return(new jo).evaluate(e,t);throw((e,t)=>new to(`Unknown ${t??"flow"} condition type \u2014 must be ConditionExpression (op) or CodeCondition (type: 'code')`,"GRAPH_UNKNOWN_CONDITION_TYPE",{condition:e}))(e,o)}async function Wo(e,t,o){return Go(e)?Fo(e,t.input,o):Bo(e,t.state,t.label)}function qo(e,t,o,n){if(e&&"object"==typeof e&&!n.has(e))if(n.add(e),Go(e))o.push({nodeId:t,kind:"code-condition"});else if(ut(e))o.push({nodeId:t,kind:"value-template"});else if((e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"expression"===t.source&&"string"==typeof t.expression})(e))o.push({nodeId:t,kind:"expression-binding"});else if((e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.name&&Array.isArray(t.nodes)&&Array.isArray(t.edges)})(e))Ko(e,o,n);else if(Array.isArray(e))for(const r of e)qo(r,t,o,n);else for(const r of Object.keys(e))qo(e[r],t,o,n)}function Ho(e,t,o){const n=e.id;"core.utility.code"===e.kind&&t.push({nodeId:n,kind:"code-node",detail:e.kind});const r=e.inputBindings??{};for(const[e,o]of Object.entries(r))o&&"expression"===o.mode&&t.push({nodeId:n,kind:"expression-binding",detail:e});qo(e.parameters,n,t,o),qo(e.metadata,n,t,o),qo(e.state,n,t,o),qo(e.loop,n,t,o)}function Ko(e,t,o){for(const n of e.nodes??[])Ho(n,t,o)}function Vo(e){const t=[];return Ko(e,t,new Set),t}function zo(e){return Vo(e).length>0}function Jo(e,t){if(!t)return{valid:!0};switch(t.type){case"any":default:return{valid:!0};case"string":return"string"!=typeof e?Xo("string"):{valid:!0};case"number":return"number"==typeof e&&Number.isFinite(e)?t.integer&&!Number.isInteger(e)?{valid:!1,message:"expected an integer number"}:void 0!==t.min&&e<t.min?{valid:!1,message:"expected a number >= "+t.min}:void 0!==t.max&&e>t.max?{valid:!1,message:"expected a number <= "+t.max}:{valid:!0}:Xo("number");case"boolean":return"boolean"!=typeof e?Xo("boolean"):{valid:!0};case"array":if(!Array.isArray(e))return Xo("array");if(void 0!==t.minItems&&e.length<t.minItems)return{valid:!1,message:`expected at least ${t.minItems} items`};if(void 0!==t.maxItems&&e.length>t.maxItems)return{valid:!1,message:`expected at most ${t.maxItems} items`};for(const o of e){const e=Jo(o,t.items);if(!e.valid)return e}return{valid:!0};case"object":case"model":{if(null===e||"object"!=typeof e||Array.isArray(e))return Xo(t.type);const o=t,n=o.properties;if(!n)return{valid:!0};for(const[t,o]of Object.entries(n))if(t in e){const n=Jo(e[t],o);if(!n.valid)return{valid:!1,message:`property '${t}': ${n.message}`}}if(o.required)for(const t of o.required)if(!(t in e))return{valid:!1,message:`missing required property '${t}'`};if(!1===o.additionalProperties)for(const t of Object.keys(e))if(!(t in n))return{valid:!1,message:`unexpected property '${t}'`};return{valid:!0}}case"enum":return t.values.some(t=>t===e)?{valid:!0}:{valid:!1,message:"value is not one of the enum values"}}}function Xo(e){return{valid:!1,message:`expected a ${e} value`}}function Yo(e){if("string"==typeof e)return e.length>0;if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.credentialId&&t.credentialId.length>0&&(void 0===t.credentialType||"string"==typeof t.credentialType)}const Qo=new Set(["loop"]),Zo=["secret","secrets","password","passwd","token","accessToken","refreshToken","apiKey","api_key","privateKey","credentials"];class en{validate(e,t,o,n,r){this.validateParameters(e,t,o,n,r),this.validateMetadataKeys(e,t,o,n),this.validateDisabledBehavior(e,o,n),this.validateBindingShapes(e,t,o,n)}validateParameters(e,t,o,n,r){const i=!0===t.policies?.allowUndeclaredParameters,a=new Map(t.parameters.map(e=>[e.id,e]));for(const[r,s]of Object.entries(e.parameters??{})){const d=a.get(r);if(!d){i||o.push({code:"parameter.undeclared",path:`${n}.parameters.${r}`,message:`Node '${e.id}' sets parameter '${r}' which is not declared by kind '${t.kind}'`,nodeId:e.id,details:{kind:t.kind}});continue}if(void 0===s){o.push({code:"parameter.invalid",path:`${n}.parameters.${r}`,message:`Node '${e.id}' parameter '${r}' must not be undefined`,nodeId:e.id});continue}const l=this.checkParameterValue(s,d);l.valid||o.push({code:"parameter.type-mismatch",path:`${n}.parameters.${r}`,message:`Node '${e.id}' parameter '${r}' is invalid: ${l.message}`,nodeId:e.id,details:{expectedType:d.type}})}for(const i of t.parameters)void 0===(e.parameters??{})[i.id]&&(this.isParameterSatisfiedByInput(e,i.id,r)||(!0===i.required||(i.validation??[]).some(e=>"required"===e.kind))&&void 0===i.defaultValue&&o.push({code:"parameter.required-missing",path:`${n}.parameters.${i.id}`,message:`Node '${e.id}' is missing required parameter '${i.id}' declared by kind '${t.kind}'`,nodeId:e.id}))}isParameterSatisfiedByInput(e,t,o){return void 0!==(e.inputBindings??{})[t]||!0===o?.has(t)}checkParameterValue(e,t){if(ut(e))return{valid:!0};switch(t.type){case"string":case"code":case"expression":return"string"!=typeof e?Xo("string"):{valid:!0};case"number":return"number"==typeof e&&Number.isFinite(e)?{valid:!0}:Xo("number");case"boolean":return"boolean"!=typeof e?Xo("boolean"):{valid:!0};case"options":{const o=t.options;return o&&o.length&&!o.some(t=>t.value===e)?{valid:!1,message:"value is not one of the declared options"}:{valid:!0}}case"collection":return Array.isArray(e)?{valid:!0}:Xo("array");case"object":case"resourceLocator":return null===e||"object"!=typeof e||Array.isArray(e)?Xo("object"):{valid:!0};case"credential":return Yo(e)?t.credentialType&&"object"==typeof e&&void 0!==e.credentialType&&e.credentialType!==t.credentialType?{valid:!1,message:`credential type '${e.credentialType}' does not match the declared type '${t.credentialType}'`}:{valid:!0}:{valid:!1,message:"credential parameters must hold a credential reference (credentialId), never a secret"};default:return{valid:!0}}}validateMetadataKeys(e,t,o,n){const r=t.metadata?.allowedInstanceMetadataKeys;for(const i of Object.keys(e.metadata??{}))Qo.has(i)?o.push({code:"metadata.key-not-allowed",path:`${n}.metadata.${i}`,message:`Node '${e.id}' metadata key '${i}' is reserved and must not be set directly`,nodeId:e.id}):Array.isArray(r)&&!r.includes(i)&&o.push({code:"metadata.key-not-allowed",path:`${n}.metadata.${i}`,message:`Node '${e.id}' metadata key '${i}' is not in the allowed metadata keys of kind '${t.kind}'`,nodeId:e.id})}validateDisabledBehavior(e,t,o){!0!==e.disabled&&!1!==e.disabled&&void 0!==e.disabled&&t.push({code:"disabled.invalid",path:o+".disabled",message:`Node '${e.id}' disabled flag must be a boolean`,nodeId:e.id});const n=(e.metadata??{}).disabledBehavior;void 0===n||ae(n)||t.push({code:"disabled.invalid-behavior",path:o+".metadata.disabledBehavior",message:`Node '${e.id}' disabled behavior '${n+""}' is not one of: ${ie.join(", ")}`,nodeId:e.id})}validateBindingShapes(e,t,o,n){for(const[r,i]of Object.entries(e.inputBindings??{})){if("literal"===i.mode){const a=t.inputs.find(e=>e.id===r);if(a?.schema){const t=Jo(i.value,a.schema);t.valid||o.push({code:"binding.literal-invalid",path:`${n}.inputBindings.${r}`,message:`Node '${e.id}' literal binding for '${r}' is schema-invalid: ${t.message}`,nodeId:e.id})}}"expression"!==i.mode||"string"==typeof i.expression&&i.expression.trim()||o.push({code:"binding.expression-invalid",path:`${n}.inputBindings.${r}`,message:`Node '${e.id}' expression binding for '${r}' must contain a non-empty expression`,nodeId:e.id})}}validateBindingSatisfaction(e,t,o,n,r,i={}){const a=new Set(o.filter(e=>"data"===e.type).map(e=>e.targetPort)),s=new Set(Object.entries(e.inputBindings??{}).map(([e])=>e));for(const t of a){const o=(e.inputBindings??{})[t];o&&"literal"===o.mode&&!0!==i.allowLiteralAndEdgeBindings&&n.push({code:"binding.conflict",path:`${r}.inputBindings.${t}`,message:`Node '${e.id}' input '${t}' has both an incoming edge and a literal binding`,nodeId:e.id})}for(const o of t.inputs)!0===o.required&&(a.has(o.id)||s.has(o.id)||void 0===(e.parameters??{})[o.id]&&n.push({code:"topology.required-input-unsatisfiable",path:r+".parameters",message:`Node '${e.id}' required input '${o.id}' has no incoming edge or binding`,nodeId:e.id,details:{port:o.id}}))}static disabledBehaviorOf(e,t){const o=(e.metadata??{}).disabledBehavior;if(ae(o))return o;const n=t?.disabledBehavior;return ae(n)?n:"skip"}}let tn=class extends T{constructor(e){super(e)}};function on(e){return[e.namespace??"default",e.workflowId,e.nodeId,e.version??"default",e.fingerprint].join(":")}function nn(e){return new tn({id:on(e.key),workflowId:e.key.workflowId,nodeId:e.key.nodeId,fingerprint:e.key.fingerprint,...void 0!==e.key.namespace?{namespace:e.key.namespace}:{},...void 0!==e.key.version?{version:e.key.version}:{},pinned:e.pinned,outputs:e.outputs,createdAt:new Date(e.createdAt),updatedAt:new Date(e.updatedAt),...e.expiresAt?{expiresAt:new Date(e.expiresAt)}:{},...e.metadata?{metadata:e.metadata}:{}})}function rn(e){return{key:{workflowId:e.workflowId,nodeId:e.nodeId,fingerprint:e.fingerprint,...void 0!==e.namespace?{namespace:e.namespace}:{},...void 0!==e.version?{version:e.version}:{}},outputs:e.outputs,pinned:e.pinned,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString(),...e.expiresAt?{expiresAt:e.expiresAt.toISOString()}:{},...e.metadata?{metadata:e.metadata}:{}}}S([P({type:String,generated:!1}),D("design:type",String)],tn.prototype,"id",void 0),S([R(),$(),D("design:type",String)],tn.prototype,"workflowId",void 0),S([R(),$(),D("design:type",String)],tn.prototype,"nodeId",void 0),S([R(),D("design:type",String)],tn.prototype,"fingerprint",void 0),S([R(),D("design:type",String)],tn.prototype,"namespace",void 0),S([R(),D("design:type",String)],tn.prototype,"version",void 0),S([R(),D("design:type",Boolean)],tn.prototype,"pinned",void 0),S([R(),D("design:type",Object)],tn.prototype,"outputs",void 0),S([R(),D("design:type",Date)],tn.prototype,"createdAt",void 0),S([R(),D("design:type",Date)],tn.prototype,"updatedAt",void 0),S([R(),D("design:type",Date)],tn.prototype,"expiresAt",void 0),S([R(),D("design:type",Object)],tn.prototype,"metadata",void 0),tn=S([C("graph_value"),E(),D("design:paramtypes",[Object])],tn);let an=class extends G{constructor(e){super(e,tn,!0),this.runtimeValues=new Map}seedWorkflowInputs(e){this.runtimeValues.set(Wt,{...e})}setNodeOutputs(e,t){this.runtimeValues.set(e,{...t})}getPort(e,t){return this.runtimeValues.get(e)?.[t]}hasPort(e,t){return Object.prototype.hasOwnProperty.call(this.runtimeValues.get(e)??{},t)}setWorkflowOutput(e,t){const o=this.runtimeValues.get(Wt)??{};o[e]=t,this.runtimeValues.set(Wt,o)}getWorkflowValues(){return{...this.runtimeValues.get(Wt)??{}}}snapshot(){return Object.fromEntries(this.runtimeValues.entries())}async readCached(e,...t){try{return rn(await this.read(on(e),...t))}catch{return}}async writeCached(e,t,...o){const n=on(e);let r;try{r=await this.read(n,...o)}catch{r=void 0}r?await this.update(Object.assign(r,nn(t)),...o):await this.create(nn(t),...o)}async deleteCached(e,...t){try{await this.delete(on(e),...t)}catch{}}async hasCached(e,...t){return void 0!==await this.readCached(e,...t)}async listCached(e,...t){return(await this.select().execute(...t)).map(e=>rn(e)).filter(t=>((e,t)=>!(void 0!==t.workflowId&&e.workflowId!==t.workflowId||void 0!==t.nodeId&&e.nodeId!==t.nodeId||void 0!==t.namespace&&e.namespace!==t.namespace||void 0!==t.version&&e.version!==t.version||void 0!==t.fingerprint&&e.fingerprint!==t.fingerprint))(t.key,e))}async clearRun(e,...t){const o=await this.select().execute(...t);for(const e of o)await this.delete(e.id,...t)}readRuntimeValues(e){return this.runtimeValues.get(e)}writeRuntimeValues(e,t){this.runtimeValues.set(e,{...t})}getAdapter(){return this.adapter}};function sn(e){return new(0,G.forModel(tn,e.alias).constructor)(e)}an=S([j(tn,m),D("design:paramtypes",[Function])],an);class dn{static upstreamNodes(e,t,o=!1){const n=new Set,r=[e];for(;r.length;){const e=r.pop(),i=t.get(e)??[];for(const e of i)!o&&this.isBoundary(e.sourceNodeId)||n.has(e.sourceNodeId)||(n.add(e.sourceNodeId),r.push(e.sourceNodeId))}return n}static downstreamNodes(e,t,o=!1){const n=new Set,r=[e];for(;r.length;){const e=r.pop(),i=t.get(e)??[];for(const e of i)!o&&this.isBoundary(e.targetNodeId)||n.has(e.targetNodeId)||(n.add(e.targetNodeId),r.push(e.targetNodeId))}return n}static isBoundary(e){return"$workflow"===e}}class ln{constructor(e,t,o){this.store=e,this.policy=t,this.dependencyResolver=o}async pinNode(e){const t=e.plan,o=e.includeDependencies??!0?this.dependencyResolver.getPinSet(t,e.nodeId):new Set([e.nodeId]);for(const e of o){const o=t.nodes.find(t=>t.id===e);if(!o)throw new io(`Node '${e}' not found in plan`);if(!this.policy.canPin(o))throw new io(`Node '${e}' is not pinnable`,{nodeId:e})}const n=this.topologicalOrder(t,o);for(const o of n){const n=t.nodes.find(e=>e.id===o),r=e.result.nodeResults[o];if(!r||!r.outputs)throw new io(`Node '${o}' has no completed output to pin`);const i=r.inputs??{},a=this.dependencyFingerprints(t,o,e.result),s=this.createValueKey(e.document.id,n,i,a),d=(new Date).toISOString(),l={key:s,outputs:r.outputs,pinned:!0,createdAt:d,updatedAt:d,metadata:{...e.result.metadata,nodeId:o}};await this.store.writeCached(s,l)}}async unpinNode(e){const t={workflowId:e.document.id,nodeId:e.nodeId,fingerprint:e.fingerprint,namespace:e.namespace};await this.store.deleteCached(t)}async readPinnedValue(e,t,o,n,r){const i=this.createValueKey(e,t,o,n,r),a=await this.store.readCached(i);if(a&&a.pinned){if(a.expiresAt&&new Date(a.expiresAt)<new Date)return;return a}}createValueKey(e,t,o,n,r){return{workflowId:e,nodeId:t.id,fingerprint:this.computeFingerprint(e,t,o,n),namespace:r}}computeFingerprint(e,t,o,n){const r={workflowId:e,nodeId:t.id,nodeKind:t.kind,parameters:this.stableSerialize(t.instance.parameters??{}),inputBindings:this.stableSerialize(t.instance.inputBindings??{}),metadata:this.stableSerialize(this.relevantMetadata(t)),inputs:this.stableSerialize(o),dependencyFingerprints:this.stableSerialize(n)},i=this.stableSerialize(r);return this.simpleHash(i)}relevantMetadata(e){const t={...e.metadata??{}};return delete t.ui,delete t.position,delete t.visual,t}topologicalOrder(e,t){const o=[],n=new Set,r=i=>{if(n.has(i))return;n.add(i);const a=dn.upstreamNodes(i,e.incomingByNode,!1);for(const e of a)t.has(e)&&r(e);o.push(i)};for(const e of t)r(e);return o}dependencyFingerprints(e,t,o){const n=this.dependencyResolver.getDependencies(e,t),r={};for(const t of n){const n=e.nodes.find(e=>e.id===t);if(n){const i=o.nodeResults[t],a=i?.inputs??{},s=this.dependencyFingerprints(e,t,o);r[t]=this.computeFingerprint(e.workflowId,n,a,s)}}return r}stableSerialize(e){return null===e||"object"!=typeof e?JSON.stringify(e):Array.isArray(e)?`[${e.map(e=>this.stableSerialize(e)).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${this.stableSerialize(e[t])}`).join(",")}}`}simpleHash(e){let t=0;for(let o=0;o<e.length;o++)t=(t<<5)-t+e.charCodeAt(o),t|=0;return`fp_${Math.abs(t).toString(16).padStart(8,"0")}_${e.length}`}}const cn={enabled:!0,strategy:"manual",includeDependencies:!0};function un(e){return!0===e?.enabled&&"disabled"!==e.strategy}class pn{canPin(e){return un(this.getPinningMetadata(e))}shouldUsePinnedValue(e){const t=this.getPinningMetadata(e);return!0===t.enabled&&"disabled"!==t.strategy}shouldAutoPin(e){const t=this.getPinningMetadata(e);return!0===t.enabled&&"automatic"===t.strategy}getPinningMetadata(e){const t=e.manifest.metadata?.pinnable??e.metadata?.pinnable;return t?{...cn,...t}:{...cn,enabled:!1}}}class hn{getDependencies(e,t){return dn.upstreamNodes(t,e.incomingByNode,!1)}getPinSet(e,t){const o=this.getDependencies(e,t);return o.add(t),o}}class fn{constructor(){this.local=!0,this.codeMode="hostSide",Mo.register(qt,this)}async initialize(e){this.valueAdapter=e.valueAdapter,this.codeSandboxEvaluator=e.codeSandboxEvaluator,this.workflowStore=e.workflowStore,this.engine=e.engine}get capabilities(){const e=this.workflowStore?"supported":"not_supported";return{codeMode:this.codeMode,workflows:{list:e,get:e}}}async listWorkflows(...e){const t=this.workflowStore;if(!t)throw new to("LocalGraphExecutionBackend has no workflowStore configured; workflow listing is not supported","GRAPH_BACKEND_WORKFLOWS_NOT_SUPPORTED");return(await t.listWorkflows(...e)).map(e=>({id:e.workflowId,...void 0!==e.name?{name:e.name}:{},...void 0!==e.updatedAt&&null!==e.updatedAt?{updatedAt:e.updatedAt}:{}}))}async getWorkflow(e,...t){const o=this.workflowStore;if(!o)throw new to("LocalGraphExecutionBackend has no workflowStore configured; workflow lookup is not supported","GRAPH_BACKEND_WORKFLOWS_NOT_SUPPORTED");return await o.getDocument(e,...t)}async execute(e){const{document:t,plan:o,inputs:n,options:r,events:i}=e,a=i,s=a.frame;if(!s)throw new to("LocalGraphExecutionBackend requires the frame-bound event sink created by GraphExecutionEngine","GRAPH_EXECUTION_FRAME_MISSING");const d=s.valueStore,l=s.runId,c=r.path??[],u=async e=>{await a.emit(e)};try{for(const e of o.layers)this.assertNotAborted(r),await this.executeLayer(s,o,e.nodes,r,u);this.assertNotAborted(r);const e=[...s.nodeResults.values()].find(e=>e.status===se.FAILED);if(e?.error)throw new to(e.error.message,e.error.code??"GRAPH_EXECUTION_ERROR",e.error.details);return s.finish(),await a.emit({type:ce.WORKFLOW_COMPLETED,runId:l,parentRunId:r.parentRunId,workflowId:o.workflowId,path:c,status:se.SUCCEEDED,payload:{outputs:d.getWorkflowValues()}}),Co(s,t,n,se.SUCCEEDED,r.metadata)}catch(e){if(e instanceof co)throw s.finish(),e;s.finish();const i=this.toErrorPayload(e);return e instanceof uo||!0===r.abortSignal?.aborted?(await a.emit({type:ce.WORKFLOW_CANCELLED,runId:l,parentRunId:r.parentRunId,workflowId:o.workflowId,path:c,status:se.CANCELLED,error:i}),Co(s,t,n,se.CANCELLED,r.metadata)):(await a.emit({type:ce.WORKFLOW_FAILED,runId:l,parentRunId:r.parentRunId,workflowId:o.workflowId,path:c,status:se.FAILED,error:i}),Co(s,t,n,se.FAILED,r.metadata))}}async executeLayer(e,t,o,n,r){const i=Math.max(1,n.concurrency??4),a=[...o];for(;a.length>0;){const o=a.splice(0,i);await Promise.all(o.map(o=>this.executeNode(e,t,o,n,r)))}}async executeNode(e,t,o,n,r){if(this.assertNotAborted(n),!this.isNodeActivated(e,t,o))return void await this.skipInactiveNode(e,t,o,n,r);if(!0===o.instance.disabled)return void await this.executeDisabledNode(e,t,o,n,r);const i=new Date,a=[...n.path??[],o.id];await r({type:ce.NODE_STARTED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.RUNNING}),this.emitNodeStateChanged(e,t,o,a,de.RUNNING,se.RUNNING,r);const s=await this.resolveNodeInputs(e,t,o,n);if(n.usePinnedValues){const n=await this.tryPinnedValue(e,t,o,s);if(n){e.valueStore.setNodeOutputs(o.id,n.outputs),this.routeOutgoingEdges(e,t,o,n.outputs,r);const d=new Date,l={nodeId:o.id,status:se.CACHED,inputs:s,outputs:n.outputs,startedAt:i,finishedAt:d,fromCache:!0,pinned:!0,events:[]};return e.recordNodeResult(l),await r({type:ce.NODE_CACHE_HIT,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.CACHED,payload:{outputs:n.outputs}}),await r({type:ce.NODE_COMPLETED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.SUCCEEDED,payload:{outputs:n.outputs,fromCache:!0}}),void this.emitNodeStateChanged(e,t,o,a,de.SUCCEEDED,se.SUCCEEDED,r)}}try{const d=new Ro(e.runId,n.parentRunId,t.workflowId,t.resolved.document,o.instance,o.manifest,a,r,n.metadata,this.engine,n.abortSignal,this.executionLimits(n)),l=await this.resolveNodeParameters(o,s,n),c={nodeId:o.id,kind:o.kind,inputs:s,parameters:l,credentials:this.collectCredentials(o),metadata:o.instance.metadata},u=await this.invokeExecutor(o,c,d),p=this.validateNodeOutputs(o,u??{});e.valueStore.setNodeOutputs(o.id,p),this.routeOutgoingEdges(e,t,o,p,r);const h=new Date,f={nodeId:o.id,status:se.SUCCEEDED,inputs:s,outputs:p,startedAt:i,finishedAt:h,events:[]};e.recordNodeResult(f),await r({type:ce.NODE_COMPLETED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.SUCCEEDED,payload:{outputs:p}}),this.emitNodeStateChanged(e,t,o,a,de.SUCCEEDED,se.SUCCEEDED,r)}catch(d){if(d instanceof co)throw d;const l=new Date,c=this.toErrorPayload(d),u={nodeId:o.id,status:se.FAILED,inputs:s,error:c,startedAt:i,finishedAt:l,events:[]};if(e.recordNodeResult(u),await r({type:ce.NODE_FAILED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.FAILED,error:c}),this.emitNodeStateChanged(e,t,o,a,de.FAILED,se.FAILED,r),n.failFast??!0)throw d}}isNodeActivated(e,t,o){const n=(t.incomingByNode.get(o.id)??[]).filter(e=>"data"===e.type);return 0===n.length||n.some(t=>t.sourceNodeId===Wt||e.isDataEdgeActive(t.id))}async skipInactiveNode(e,t,o,n,r){const i=new Date,a=[...n.path??[],o.id];await r({type:ce.NODE_SKIPPED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.SKIPPED,payload:{reason:"branchNotSelected"}});const s={nodeId:o.id,status:se.SKIPPED,inputs:{},startedAt:i,finishedAt:new Date,events:[]};e.recordNodeResult(s),this.emitNodeStateChanged(e,t,o,a,de.SKIPPED,se.SKIPPED,r)}async executeDisabledNode(e,t,o,n,r){const i=new Date,a=[...n.path??[],o.id],s=en.disabledBehaviorOf(o.instance,t.resolved.document.settings);if(await r({type:ce.NODE_SKIPPED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.SKIPPED,payload:{disabled:!0,behavior:s}}),"skip"===s){const n={nodeId:o.id,status:se.SKIPPED,inputs:{},startedAt:i,finishedAt:new Date,events:[]};return e.recordNodeResult(n),void this.emitNodeStateChanged(e,t,o,a,de.SKIPPED,se.SKIPPED,r)}const d=await this.resolveNodeInputs(e,t,o,n);let l;if("passThroughFirstInput"===s){const n=(t.incomingByNode.get(o.id)??[]).find(e=>"data"===e.type),r=o.manifest.outputs[0]?.id??"value",i=n?e.valueStore.getPort(n.sourceNodeId,n.sourcePort):Object.values(d)[0];l={[r]:i}}else{l={};for(const e of o.manifest.outputs)l[e.id]=e.metadata?.defaultValue}e.valueStore.setNodeOutputs(o.id,l),this.routeOutgoingEdges(e,t,o,l,r);const c={nodeId:o.id,status:se.SUCCEEDED,inputs:d,outputs:l,startedAt:i,finishedAt:new Date,events:[]};e.recordNodeResult(c),this.emitNodeStateChanged(e,t,o,a,de.SUCCEEDED,se.SUCCEEDED,r)}async invokeExecutor(e,t,o){return await e.executor.execute(t,o)}validateNodeOutputs(e,t){const o=e.manifest;if(!0===o.policies?.allowUnknownOutputs)return t;const n=new Set(o.outputs.map(e=>e.id)),r=Object.keys(t).filter(e=>!n.has(e));if(r.length>0)throw new to(`Node '${e.id}' of kind '${e.kind}' produced unknown output(s): ${r.join(", ")}`,"GRAPH_OUTPUT_VALIDATION_FAILED",{nodeId:e.id,unknownOutputs:r});const i=o.outputs.filter(e=>!0===e.required&&!(e.id in t)).map(e=>e.id);if(i.length>0)throw new to(`Node '${e.id}' of kind '${e.kind}' did not produce required output(s): ${i.join(", ")}`,"GRAPH_OUTPUT_VALIDATION_FAILED",{nodeId:e.id,missingRequired:i});return t}collectCredentials(e){const t={};for(const o of e.manifest.parameters){if("credential"!==o.type)continue;const n=(e.instance.parameters??{})[o.id];"string"==typeof n&&n.length>0?t[o.id]={credentialId:n,credentialType:o.credentialType??""}:Yo(n)&&(t[o.id]={credentialId:n.credentialId,credentialType:n.credentialType})}const o=(e.instance.metadata??{}).credentials;if(o&&"object"==typeof o&&!Array.isArray(o))for(const[e,n]of Object.entries(o)){const o=n;"string"==typeof o&&o.length>0?t[e]={credentialId:o,credentialType:""}:Yo(o)&&(t[e]={credentialId:o.credentialId,credentialType:o.credentialType})}return t}async resolveNodeInputs(e,t,o,n){const r={},i=(t.incomingByNode.get(o.id)??[]).filter(e=>"data"===e.type),a=new Map;for(const e of i){const t=a.get(e.targetPort)??[];t.push(e),a.set(e.targetPort,t)}for(const[t,o]of a)if(1===o.length)r[t]=e.valueStore.getPort(o[0].sourceNodeId,o[0].sourcePort);else{let n,i=!1;for(const t of o){const o=e.valueStore.getPort(t.sourceNodeId,t.sourcePort);r[t.sourcePort]=o,void 0!==o&&(n=o,i=!0)}i&&void 0===r[t]&&(r[t]=n)}const s=o.instance.inputBindings??{};for(const e of o.manifest.inputs){const t=s[e.id];if("literal"===t?.mode)r[e.id]=t.value;else if("expression"===t?.mode)r[e.id]=await this.evaluateExpressionBinding(o,t.expression,r,n);else if(void 0===r[e.id]){const t=e.metadata?.defaultValue;void 0!==t&&(r[e.id]=t)}}return r}async resolveNodeParameters(e,t,o){const n=e.instance.parameters??{},r={};for(const[i,a]of Object.entries(n))r[i]=ut(a)?await this.evaluateValueTemplate(a,e,t,o):a;return r}async evaluateValueTemplate(e,t,o,n){const r=this.codeSandboxEvaluator;if(!r)throw new to(`Value template on node '${t.id}' requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator`,"GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{nodeId:t.id});const i=e.language??("expression"===e.mode?"javascript":"text"),a="template"===e.mode?(e=>`\`${e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\{\{\s*([\s\S]*?)\s*\}\}/g,(e,t)=>`\${${t}}`)}\``)(e.expression):e.expression,s=n.metadata;return await r.evaluate({code:a,language:"typescript"===i?"typescript":"javascript",input:o,vars:s?.vars??void 0,item:s?.item,index:s?.index,abortSignal:n.abortSignal})}async evaluateExpressionBinding(e,t,o,n){const r=this.codeSandboxEvaluator;if(!r)throw new to(`Expression binding on node '${e.id}' requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator`,"GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{nodeId:e.id,expression:t});const i=n.metadata;return await r.evaluate({code:t,language:"javascript",input:o,vars:i?.vars??void 0,item:i?.item,index:i?.index,abortSignal:n.abortSignal})}async tryPinnedValue(e,t,o,n){if(!(new pn).shouldUsePinnedValue(o))return;const r=this.createPinningService(e),i=this.computeDependencyFingerprints(e,t,o.id);return r.readPinnedValue(t.workflowId,o,n,i)}computeDependencyFingerprints(e,t,o){const n=this.createPinningService(e),r=(new hn).getDependencies(t,o),i={};for(const o of r){const r=t.nodes.find(e=>e.id===o);if(r){const a=e.nodeResults.get(o),s=a?.inputs??{},d=this.computeDependencyFingerprints(e,t,o);i[o]=n.computeFingerprint(t.workflowId,r,s,d)}}return i}routeOutgoingEdges(e,t,o,n,r){const i=(t.outgoingByNode.get(o.id)??[]).filter(e=>"data"===e.type);for(const a of i){if(!Object.prototype.hasOwnProperty.call(n,a.sourcePort))continue;const i=n[a.sourcePort];e.activateDataEdge(a.id),a.targetNodeId===Wt&&e.valueStore.setWorkflowOutput(a.targetPort,i),this.emitEdgeStateChanged(e,t,o,a,de.SUCCEEDED,se.SUCCEEDED,r),r({type:ce.EDGE_VALUE_ROUTED,runId:e.runId,workflowId:t.workflowId,edgeId:a.id,nodeId:o.id,path:[],payload:{edge:a,value:i}}).catch(()=>{})}}emitNodeStateChanged(e,t,o,n,r,i,a){a({type:ce.NODE_STATE_CHANGED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:n,status:i,payload:{nodeId:o.id,state:r,runId:e.runId,workflowId:t.workflowId,status:i}}).catch(()=>{})}emitEdgeStateChanged(e,t,o,n,r,i,a){a({type:ce.EDGE_STATE_CHANGED,runId:e.runId,workflowId:t.workflowId,edgeId:n.id,nodeId:o.id,path:[],status:i,payload:{edgeId:n.id,state:r,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,status:i}}).catch(()=>{})}createPinningService(e){const t=sn(e.valueStore.getAdapter()??this.valueAdapter);return new ln(t,new pn,new hn)}executionLimits(e){return{maxLoopIterations:e.maxLoopIterations??zt,maxForeachIterations:e.maxForeachIterations??Jt}}assertNotAborted(e){if(!0===e.abortSignal?.aborted)throw new uo(e.runId??"unknown")}toErrorPayload(e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack,code:e.graphCode??("number"==typeof e.code?e.code+"":e.code)}:{name:"UnknownError",message:e+""}}}class gn{constructor(e){this.catalogue=e}async resolveNodes(e,t,o,...n){const r=new Map;for(const[i,a]of e.entries()){const e=`nodes[${i}]`;if(this.catalogue.has(a.kind,...n))try{const e=await this.catalogue.resolveManifest(a.kind,a,o,...n),t=this.catalogue.getExecutor(a.kind,...n);r.set(a.id,{instance:a,manifest:e,executor:t})}catch(o){t.push({code:"kind.resolution-failed",path:e+".kind",message:`Node '${a.id}' kind '${a.kind}' failed to resolve: ${o.message}`,nodeId:a.id,details:{kind:a.kind}})}else t.push({code:"kind.unknown",path:e+".kind",message:`Node '${a.id}' references kind '${a.kind}' which is not registered in the backend catalogue`,nodeId:a.id,details:{kind:a.kind}})}return r}validateEffectivePorts(e,t,o,n){const r=!0===t.policies?.allowUndeclaredParameters,i=new Set(t.inputs.map(e=>e.id)),a=new Set(t.outputs.map(e=>e.id));for(const a of Object.keys(e.inputBindings??{}))r||i.has(a)||o.push({code:"binding.unknown-port",path:`${n}.inputBindings.${a}`,message:`Node '${e.id}' input binding '${a}' does not refer to an effective input port of kind '${t.kind}'`,nodeId:e.id,details:{effectiveInputs:[...i]}});for(const i of Object.keys(e.outputBindings??{}))r||a.has(i)||o.push({code:"binding.unknown-port",path:`${n}.outputBindings.${i}`,message:`Node '${e.id}' output binding '${i}' does not refer to an effective output port of kind '${t.kind}'`,nodeId:e.id,details:{effectiveOutputs:[...a]}})}}function mn(e,t,o="$"){const n=new Set;for(const t of e.edges)"node"===t.source.scope&&n.add(t.source.nodeId),"node"===t.target.scope&&n.add(t.target.nodeId);for(const r of e.nodes){n.has(r.id)||t.push({code:"topology.loose-node",path:`${o}.nodes[${r.id}]`,message:`Node '${r.id}' is connected to nothing; every node must participate in at least one edge`,nodeId:r.id});const e=r.loop?.body;e&&mn(e,t,`${o}.nodes[${r.id}].loop.body`)}}class yn{resolveEdges(e,t,o){const n=new Set(e.inputs.map(e=>e.id)),r=new Set(e.outputs.map(e=>e.id)),i=[];for(const[a,s]of(e.edges??[]).entries()){const e=`edges[${a}]`,d=this.resolveEndpoint(s,"source",t,n,r,o,e),l=this.resolveEndpoint(s,"target",t,n,r,o,e);if(!d||!l)continue;if(!this.validateDirectionAndType(s,d,l,t,o,e))continue;const c={id:s.id,type:s.type,sourceNodeId:d.nodeId,sourcePort:d.port,targetNodeId:l.nodeId,targetPort:l.port,metadata:s.metadata,edge:s};void 0!==s.label&&(c.label=s.label),i.push(c)}return i}resolveEndpoint(e,t,o,n,r,i,a){const s=e[t];return Xe(s)?("source"===t?n.has(s.port):r.has(s.port))?{nodeId:Wt,port:s.port}:void i.push({code:"edge.unknown-port",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} references workflow port '${s.port}' which is not declared on the document boundary`,edgeId:e.id,details:{scope:"workflow",port:s.port}}):Ye(s)?o.get(s.nodeId)?{nodeId:s.nodeId,port:s.port}:void i.push({code:"edge.unknown-node",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} references node '${s.nodeId}' which is not part of the document or did not resolve`,edgeId:e.id,nodeId:s.nodeId}):void i.push({code:"edge.invalid-endpoint",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} endpoint is not a valid GraphEndpoint`,edgeId:e.id})}validateDirectionAndType(e,t,o,n,r,i){let a=!0;const s=t.nodeId===Wt?void 0:n.get(t.nodeId),d=o.nodeId===Wt?void 0:n.get(o.nodeId),l=e=>!0===e?.manifest.policies?.allowUndeclaredParameters;if("data"===e.type)!s||l(s)||this.hasPortDirection(s,t.port,"output")||(this.pushPortIssue(e,"source",t,s,r,i),a=!1),!d||l(d)||this.hasPortDirection(d,o.port,"input")||(this.pushPortIssue(e,"target",o,d,r,i),a=!1);else{if(!s||!d)return r.push({code:"edge.boundary-routing",path:i,message:`Connection edge '${e.id}' must connect two node connection ports; the workflow boundary only routes data`,edgeId:e.id}),!1;if(!(l(s)||l(d)||this.hasPortDirection(s,t.port,"connection")&&this.hasPortDirection(d,o.port,"connection")))return r.push({code:"edge.type-mismatch",path:i,message:`Connection edge '${e.id}' endpoints must both be connection ports`,edgeId:e.id,details:{sourcePort:t.port,targetPort:o.port}}),!1}return a}hasPortDirection(e,t,o){return("input"===o?e.manifest.inputs:"output"===o?e.manifest.outputs:e.manifest.connections??[]).some(e=>e.id===t)}pushPortIssue(e,t,o,n,r,i){const a="source"===t?"output":"input";r.push({code:"data"===e.type?"edge.invalid-direction":"edge.type-mismatch",path:`${i}.${t}`,message:`Edge '${e.id}' ${t} port '${o.port}' on node '${o.nodeId}' is not an ${a} port of kind '${n.manifest.kind}'`,edgeId:e.id,nodeId:o.nodeId,details:{port:o.port,expected:a}})}}class wn{validate(e,t){this.validateDuplicates(e.edges,t),this.validatePolicies(e,t)}validateDuplicates(e,t){const o=new Map;for(const n of e){const e=`${n.sourceNodeId}:${n.sourcePort}->${n.targetNodeId}:${n.targetPort}`,r=o.get(e);r?t.push({code:"connection.duplicate-edge",path:`edges[${n.id}]`,message:`Edge '${n.id}' duplicates the routing of edge '${r.id}' (${e})`,edgeId:n.id,details:{duplicateOf:r.id,routing:e}}):o.set(e,n)}}validatePolicies(e,t){const o=new Map;for(const t of e.edges){if("connection"!==t.type)continue;const e=`${t.targetNodeId}:${t.targetPort}`,n=o.get(e)??[];n.push(t),o.set(e,n)}for(const o of e.edges){if("connection"!==o.type)continue;const n=e.nodeById.get(o.targetNodeId),r=n?.manifest.connections?.find(e=>e.id===o.targetPort)?.connectionPolicy;this.validateEdgePolicy(o,e.nodeById,r,t)}for(const[n,r]of o){const o=n.lastIndexOf(":"),i=n.slice(0,o),a=n.slice(o+1),s=e.nodeById.get(i),d=s?.manifest.connections?.find(e=>e.id===a)?.connectionPolicy;if(!d)continue;const l=void 0!==d.maxConnections?d.maxConnections:!1===d.allowMultiple?1:1/0;r.length>l&&t.push({code:"connection.max-connections",path:`edges[${r[r.length-1].id}]`,message:`Connection port '${a}' on node '${i}' accepts at most ${l} connection(s) but has ${r.length}`,nodeId:i,edgeId:r[r.length-1].id,details:{port:a,max:l,actual:r.length}})}}validateEdgePolicy(e,t,o,n){if(e.sourceNodeId===e.targetNodeId&&!o?.allowSelf)return void n.push({code:"connection.self-connection",path:`edges[${e.id}]`,message:`Edge '${e.id}' connects node '${e.sourceNodeId}' to itself, which the target port policy does not allow`,edgeId:e.id,nodeId:e.sourceNodeId});if(!o)return;const r=t.get(e.sourceNodeId),i=r?.manifest.kind;if(!o.allowedNodeKinds?.length||i&&o.allowedNodeKinds.includes(i)||n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source kind '${i??"unknown"}' is not in the allowed node kinds of target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{allowedNodeKinds:o.allowedNodeKinds}}),i&&o.blockedNodeKinds?.includes(i)&&n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source kind '${i}' is blocked by target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{blockedNodeKinds:o.blockedNodeKinds}}),o.allowedPortCategories?.length){const t=r?.manifest.connections?.find(t=>t.id===e.sourcePort)?.category;t&&o.allowedPortCategories.includes(t)||n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source port '${e.sourcePort}' category '${t??"unknown"}' is not in the allowed port categories of target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{allowedPortCategories:o.allowedPortCategories}})}}}class bn{constructor(e){this.authorizer=e}async validate(e,t,o,n){const r=this.collectReferences(e,t);for(const i of t.credentials??[]){const a=r.find(e=>void 0===e.credentialType||e.credentialType===i.type);if(a){if(this.checkType(a,i))o.push({code:"credential.type-mismatch",path:n,message:`Node '${e.id}' credential '${a.credentialId}' has type '${a.credentialType}' but kind '${t.kind}' requires '${i.type}'`,nodeId:e.id,details:{credentialType:a.credentialType??"",requiredType:i.type}});else if(this.authorizer){if(!await this.authorizer.hasCredential(a)){o.push({code:"credential.not-found",path:n,message:`Node '${e.id}' references credential '${a.credentialId}' which does not exist`,nodeId:e.id,details:{credentialId:a.credentialId}});continue}await this.authorizer.authorize(a,i)||o.push({code:"credential.unauthorized",path:n,message:`Node '${e.id}' is not authorized to use credential '${a.credentialId}'`,nodeId:e.id,details:{credentialId:a.credentialId}})}}else!1!==i.required&&o.push({code:"credential.missing",path:n,message:`Node '${e.id}' does not provide the required credential of type '${i.type}'`,nodeId:e.id,details:{credentialType:i.type}})}this.scanPlainSecrets(e,o,n)}collectReferences(e,t){const o=[];for(const n of t.parameters){if("credential"!==n.type)continue;const t=(e.parameters??{})[n.id];Yo(t)&&o.push(this.normalize(t,n.credentialType))}const n=(e.metadata??{}).credentials;if(n&&"object"==typeof n&&!Array.isArray(n))for(const e of Object.values(n))Yo(e)&&o.push(this.normalize(e));return o}normalize(e,t){return"string"==typeof e?{credentialId:e,credentialType:t??""}:{credentialId:e.credentialId,credentialType:e.credentialType??t??""}}checkType(e,t){return void 0!==e.credentialType&&e.credentialType!==t.type}scanPlainSecrets(e,t,o){const n=new Set(Zo);for(const[r,i]of Object.entries(e.parameters??{}))this.scanPlainSecretValue(i,[r],e,o+".parameters",n,t);for(const[r,i]of Object.entries(e.metadata??{}))this.scanPlainSecretValue(i,[r],e,o+".metadata",n,t)}scanPlainSecretValue(e,t,o,n,r,i,a=0){const s=t[t.length-1];if(r.has(s))i.push({code:"credential.plain-secret",path:`${n}.${t.join(".")}`,message:`Node '${o.id}' carries plain secret material in '${t.join(".")}'; workflow documents may only hold credential references`,nodeId:o.id});else if(8>a&&null!==e)if(Array.isArray(e))for(const s of e)this.scanPlainSecretValue(s,[...t,"[]"],o,n,r,i,a+1);else if("object"==typeof e)for(const[s,d]of Object.entries(e))this.scanPlainSecretValue(d,[...t,s],o,n,r,i,a+1)}}class vn extends A{constructor(e,t=[]){super(e),this.issues=t,this.name=vn.name}}class In extends A{constructor(e,t){super(e),this.edgeId=t,this.name=In.name}}class En extends U{constructor(e){super(e),this.name=En.name}}const Nn={maxDocumentBytes:2e6,maxNestingDepth:10,maxNodes:500,maxEdges:1e3},On=["node","definition","executor","execute","ports","component"];function kn(e){if(!e||"object"!=typeof e)return!1;const t=e;return pt(t.document)&&Array.isArray(t.nodes)&&Array.isArray(t.edges)&&t.nodeById instanceof Map&&t.incomingByNode instanceof Map&&t.outgoingByNode instanceof Map&&t.nodes.every(e=>null!==e&&"object"==typeof e&&"object"==typeof e.instance&&"object"==typeof e.manifest&&"object"==typeof e.executor)}function An(e,t){const o=[];for(const n of Object.keys(e))On.includes(n)&&o.push({code:"document.forbidden-field",path:`${t}.${n}`,message:`Field '${n}' is not accepted in a canonical workflow document: node, definition, executor, execute, ports and component fields are rejected`,details:{field:n}});return o}class xn{constructor(e){this.options=e,this.parameterValidator=new en,this.edgeValidator=new yn,this.connectionPolicyValidator=new wn,this.nodeValidator=new gn(e.catalogue),this.credentialValidator=new bn(e.credentialAuthorizer)}async validateOrThrow(e,...t){const o=await this.validate(e,0,...t);if(!o.valid||!o.resolved)throw new vn(`Graph workflow document '${e.id}' failed validation with ${o.issues.length} issue(s)`,o.issues);return o.resolved}async validate(e,t=0,...o){const n=[],r={...Nn,...this.options.limits};if(!await this.validateStructure(e,r,t,n,...o))return{valid:!1,issues:n};const i=await this.nodeValidator.resolveNodes(e.nodes,n,this.options.resolutionContext,...o),a=e.nodes.filter(e=>i.has(e.id)).map(e=>i.get(e.id)),s=(e=>{const t=new Map;for(const o of e.edges??[]){if("data"!==o.type)continue;const e=o.target;if("node"!==e.scope)continue;const n=t.get(e.nodeId)??new Set;n.add(e.port),t.set(e.nodeId,n)}return t})(e);for(const e of a)this.parameterValidator.validate(e.instance,e.manifest,n,`nodes[${e.instance.id}]`,s.get(e.instance.id));for(const e of a)this.nodeValidator.validateEffectivePorts(e.instance,e.manifest,n,`nodes[${e.instance.id}]`);const d=this.edgeValidator.resolveEdges(e,i,n),l=new Map,c=new Map;for(const e of d){if(e.targetNodeId!==Wt){const t=l.get(e.targetNodeId)??[];t.push(e),l.set(e.targetNodeId,t)}if(e.sourceNodeId!==Wt){const t=c.get(e.sourceNodeId)??[];t.push(e),c.set(e.sourceNodeId,t)}}this.connectionPolicyValidator.validate({edges:d,nodeById:i},n),this.validateAcyclicity(a,d,e,n),mn(e,n);for(const e of a)this.parameterValidator.validateBindingSatisfaction(e.instance,e.manifest,l.get(e.instance.id)??[],n,`nodes[${e.instance.id}]`,{allowLiteralAndEdgeBindings:this.options.allowLiteralAndEdgeBindings});this.validateRequiredWorkflowOutputs(e,c,n);for(const e of a)await this.credentialValidator.validate(e.instance,e.manifest,n,`nodes[${e.instance.id}]`);return this.validateCapabilities(a,n),n.length>0?{valid:!1,issues:n}:{valid:!0,issues:n,resolved:{document:e,nodes:a,edges:d,nodeById:i,incomingByNode:l,outgoingByNode:c}}}async validateStructure(e,t,o,n,...r){if(!pt(e))return n.push({code:"document.shape",path:"$",message:"Payload is not a canonical GraphWorkflowDocument: id and name must be strings and inputs, outputs, nodes and edges must be arrays"}),!1;if(e.id&&e.id.trim()||n.push({code:"document.empty-id",path:"$.id",message:"Workflow document id must be a non-empty string"}),!Ue(e))return n.push({code:"document.json-unsafe",path:"$",message:"Document contains JSON-unsafe values: functions, class instances, undefined, NaN/Infinity, symbol keys and unsafe prototype keys are rejected"}),!1;n.push(...An(e,"$"));for(const t of[...e.inputs,...e.outputs])n.push(...An(t,"ports"));for(const t of e.nodes)n.push(...An(t,`nodes[${t.id}]`));for(const t of e.edges)n.push(...An(t,`edges[${t.id}]`));this.validateUniqueIds(e,n),this.validateLimits(e,t,o,n);try{ot(e)}catch(e){n.push({code:"document.structure",path:"$",message:e instanceof Error?e.message:e+""})}return await this.validateNestedBodies(e,o,n,...r),!0}validateUniqueIds(e,t){const o=new Set,n=new Set;for(const[r,i]of[["input",e.inputs],["output",e.outputs]]){const e="input"===r?o:n;for(const o of i)e.has(o.id)?t.push({code:"document.duplicate-port-id",path:`${"input"===r?"inputs":"outputs"}[${o.id}]`,message:`Workflow ${r} port '${o.id}' is declared more than once; workflow port ids must be unique`}):e.add(o.id)}const r=new Set;for(const o of e.nodes)r.has(o.id)?t.push({code:"document.duplicate-node-id",path:`nodes[${o.id}]`,message:`Node '${o.id}' is declared more than once; node ids must be unique`,nodeId:o.id}):r.add(o.id);const i=new Set;for(const o of e.edges)i.has(o.id)?t.push({code:"document.duplicate-edge-id",path:`edges[${o.id}]`,message:`Edge '${o.id}' is declared more than once; edge ids must be unique`,edgeId:o.id}):i.add(o.id)}validateLimits(e,t,o,n){e.nodes.length>t.maxNodes&&n.push({code:"document.limit.nodes",path:"$.nodes",message:`Document declares ${e.nodes.length} nodes; at most ${t.maxNodes} are allowed`,details:{count:e.nodes.length,limit:t.maxNodes}}),e.edges.length>t.maxEdges&&n.push({code:"document.limit.edges",path:"$.edges",message:`Document declares ${e.edges.length} edges; at most ${t.maxEdges} are allowed`,details:{count:e.edges.length,limit:t.maxEdges}}),o>t.maxNestingDepth&&n.push({code:"document.limit.depth",path:"$",message:`Document nests loop bodies ${o} levels deep; at most ${t.maxNestingDepth} levels are allowed`,details:{depth:o,limit:t.maxNestingDepth}});const r=Buffer.byteLength(JSON.stringify(e),"utf8");r>t.maxDocumentBytes&&n.push({code:"document.limit.size",path:"$",message:`Document serializes to ${r} bytes; at most ${t.maxDocumentBytes} bytes are allowed`,details:{bytes:r,limit:t.maxDocumentBytes}})}async validateNestedBodies(e,t,o,...n){for(const r of e.nodes){const e=[["loop.body",r.loop?.body],["errorBoundary.try",r.errorBoundary?.try],["errorBoundary.catch",r.errorBoundary?.catch],["errorBoundary.finally",r.errorBoundary?.finally]];for(const[i,a]of e){if(!a)continue;const e=await this.validate(a,t+1,...n);for(const t of e.issues)o.push({...t,path:`nodes[${r.id}].${i}.${t.path}`,nodeId:t.nodeId??r.id})}}}validateAcyclicity(e,t,o,n){const r=new Set(e.map(e=>e.instance.id)),i=new Map(e.map(e=>[e.instance.id,0]));for(const e of t)r.has(e.sourceNodeId)&&i.has(e.targetNodeId)&&i.set(e.targetNodeId,(i.get(e.targetNodeId)??0)+1);const a=[...i.entries()].filter(([,e])=>0===e).map(([e])=>e),s=[];for(;a.length>0;){const e=a.shift();s.push(e);for(const o of t){if(o.sourceNodeId!==e)continue;if(!i.has(o.targetNodeId))continue;const t=(i.get(o.targetNodeId)??1)-1;i.set(o.targetNodeId,t),0===t&&a.push(o.targetNodeId)}}if(s.length!==i.size){const e=[...i.keys()].filter(e=>!s.includes(e));n.push({code:"topology.cycle",path:"$.edges",message:`Workflow '${o.id}' contains an unsupported cycle involving node(s): ${e.join(", ")}`,details:{cyclicNodes:e}})}}validateRequiredWorkflowOutputs(e,t,o){const n=new Set;for(const e of t.values())for(const t of e)t.targetNodeId===Wt&&n.add(t.targetPort);for(const t of e.outputs)!0===t.required&&void 0===t.defaultValue&&(n.has(t.id)||o.push({code:"topology.required-output-unsatisfiable",path:`outputs[${t.id}]`,message:`Required workflow output '${t.id}' has no incoming edge from any node`}))}validateCapabilities(e,t){for(const o of e){const e=o.manifest;for(const n of e.capabilities??[])gt(n)||t.push({code:"capability.invalid",path:`nodes[${o.instance.id}]`,message:`Kind '${e.kind}' declares unknown capability '${n+""}'`,nodeId:o.instance.id,details:{capability:n+""}});!0!==e.policies?.allowUndeclaredParameters&&o.instance.loop&&((e.capabilities??[]).includes("loop")||t.push({code:"capability.loop-not-supported",path:`nodes[${o.instance.id}].loop`,message:`Node '${o.instance.id}' carries loop configuration but kind '${e.kind}' does not declare the 'loop' capability`,nodeId:o.instance.id}))}}}let _n=class extends B{constructor(){super()}async plan(e,...t){const{log:o}=(await this.logCtx(t,"plan",!0)).for(this.plan);if(o.debug(`Planning resolved workflow '${e?.document?.id??"unknown"}'`),!kn(e))throw new lo("GraphExecutionPlanner.plan accepts only a GraphResolvedWorkflow produced by the nine-stage validation gate; raw workflow definitions and inline node definitions are rejected",{received:(n=e,n&&"object"==typeof n?{reason:"input is not a GraphResolvedWorkflow",looksLikeWorkflowDefinition:"nodes"in n&&"relations"in n&&!("nodeById"in n),hasResolvedNodes:Array.isArray(n.nodes)}:{reason:"input is not an object"})});var n;const r=this.buildPlanNodes(e),i=this.buildPlanEdges(e),a=this.buildIncomingMap(i),s=this.buildOutgoingMap(i),d=this.topologicalLayers(r,i);return{resolved:e,workflowId:e.document.id||e.document.name,nodes:r,edges:i,layers:d,incomingByNode:a,outgoingByNode:s}}buildPlanNodes(e){return e.nodes.map(e=>({id:e.instance.id,kind:e.manifest.kind,instance:e.instance,manifest:e.manifest,executor:e.executor,inputPorts:e.manifest.inputs.map(e=>e.id),outputPorts:e.manifest.outputs.map(e=>e.id),connectionPorts:(e.manifest.connections??[]).map(e=>e.id),metadata:e.instance.metadata}))}buildPlanEdges(e){return e.edges.map(e=>({id:e.id,type:e.type,sourceNodeId:e.sourceNodeId,sourcePort:e.sourcePort,targetNodeId:e.targetNodeId,targetPort:e.targetPort,...void 0!==e.label?{label:e.label}:{},metadata:e.metadata}))}buildIncomingMap(e){const t=new Map;for(const o of e){if(o.targetNodeId===Wt)continue;const e=t.get(o.targetNodeId)??[];e.push(o),t.set(o.targetNodeId,e)}return t}buildOutgoingMap(e){const t=new Map;for(const o of e){if(o.sourceNodeId===Wt)continue;const e=t.get(o.sourceNodeId)??[];e.push(o),t.set(o.sourceNodeId,e)}return t}topologicalLayers(e,t){const o=e.filter(e=>e.id!==Wt),n=new Set(o.map(e=>e.id)),r=t.filter(e=>n.has(e.sourceNodeId)&&n.has(e.targetNodeId)),i=new Map;for(const e of o)i.set(e.id,0);for(const e of r)i.set(e.targetNodeId,(i.get(e.targetNodeId)??0)+1);const a=[],s=new Set;let d=o.filter(e=>0===(i.get(e.id)??0)),l=0;for(;d.length>0;){const e={index:l++,nodes:d};a.push(e);const t=[];for(const e of d){s.add(e.id);const n=r.filter(t=>t.sourceNodeId===e.id);for(const e of n){const n=(i.get(e.targetNodeId)??1)-1;if(i.set(e.targetNodeId,n),0===n&&!s.has(e.targetNodeId)){const n=o.find(t=>t.id===e.targetNodeId);n&&t.push(n)}}}d=t}if(s.size!==o.length){const e=o.filter(e=>!s.has(e.id)).map(e=>e.id);throw new oo({unplannedNodes:e,workflowId:o[0]?.manifest.kind})}return a}};_n=S([F(),D("design:paramtypes",[])],_n);const Sn=new Set(["engine","valueAdapter","codeSandboxEvaluator","workflowStore"]);function Dn(e,t){const o={};for(const[n,r]of Object.entries(e??{}))Sn.has(n)&&!t.has(n)||(o[n]=r);return o}class Pn extends W{constructor(){super()}async initialize(...e){const t=e[0];if(!t||"object"!=typeof t||!t.registry)return this._config=void 0,this._client=void 0,{config:void 0,client:void 0};const o=t.catalogue??t.registry.catalog,n=t.valueAdapter??q.current;if(!n)throw new to("GraphExecutionEngine requires a Decaf adapter for cached/pinned values: pass `valueAdapter` or configure one via `Adapter.setCurrent(...)`","GRAPH_VALUE_ADAPTER_MISSING");const r=t.backend??Mo.current??new fn,i={registry:t.registry,catalogue:o,planner:t.planner??new _n,backend:r,valueAdapter:n,eventEmitter:t.eventEmitter??new ho,documentValidator:t.documentValidator??new xn({catalogue:o,limits:t.documentLimits,credentialAuthorizer:t.credentialAuthorizer}),authValidator:new So({enabled:!0===t.authEnabled,...t.authMatch?{match:t.authMatch}:{}}),...t.codeSandboxEvaluator?{codeSandboxEvaluator:t.codeSandboxEvaluator}:{}};this._config=t,this._client=i;const a=new Set(["engine","valueAdapter"]);t.codeSandboxEvaluator&&a.add("codeSandboxEvaluator"),t.workflowStore&&a.add("workflowStore");const s=Dn(r.config,a);return await r.initialize({...s,valueAdapter:n,...t.codeSandboxEvaluator?{codeSandboxEvaluator:t.codeSandboxEvaluator}:{},...t.workflowStore?{workflowStore:t.workflowStore}:{},engine:this}),await(t.onEngineCreated?.(this)),{config:t,client:i}}get codeSandboxEvaluator(){return this.client.codeSandboxEvaluator}get emitter(){return this.client.eventEmitter}get planner(){return this.client.planner}get valueAdapter(){return this.client.valueAdapter}get defaultOptions(){return this.config.defaultOptions??{}}get documentValidator(){return this.client.documentValidator}observe(e){return this.emitter.observe(e)}unObserve(e){this.emitter.unObserve(e)}async dispatchEvent(e){await this.emitter.updateObservers(e)}async execute(e,t={},o={},...n){const{log:r,ctx:i}=(await this.logCtx(n,"execute",!0)).for(this.execute);r.debug(`Executing workflow '${e.id||e.name}'`);const a=this.mergeOptions(o);this.assertNotAborted(a);const s=_o(Ao(i),a.auth);a.auth=s,a.metadata={...a.metadata??{},...s};const d=a.runId??this.generateRunId();a.runId=d;const l=a.path??[],c=new fo,u=sn(this.valueAdapter);u.seedWorkflowInputs(this.withWorkflowInputDefaults(e,t));const p=new To(this.emitter,c,{runId:d,parentRunId:a.parentRunId,workflowId:e.id||e.name,path:l,engine:this,...this.codeSandboxEvaluator?{codeSandboxEvaluator:this.codeSandboxEvaluator}:{}});await p.emit({type:ce.VALIDATION_STARTED,status:se.PLANNING});const h=await this.documentValidator.validate(e,0,i);if(!h.valid||!h.resolved)throw await p.emit({type:ce.VALIDATION_FAILED,status:se.FAILED,payload:{issues:h.issues}}),new vn(`Graph workflow document '${e.id}' failed validation with ${h.issues.length} issue(s)`,h.issues);await p.emit({type:ce.VALIDATION_COMPLETED,status:se.PLANNING,payload:{issues:h.issues.length}}),this.assertNotAborted(a);const f=await this.planner.plan(h.resolved);this.client.authValidator.validate(e,f,s,r),r.debug(`Authorized workflow '${e.id||e.name}' for user ${s.user??"anonymous"}`),this.assertCodeModeSupported(e);const g=new $o(d,f,u,c);return p.bindFrame(g),await p.emit({type:ce.WORKFLOW_STARTED,runId:d,parentRunId:a.parentRunId,workflowId:f.workflowId,path:l,status:se.RUNNING,payload:{inputs:t}}),await p.emit({type:ce.WORKFLOW_PLANNED,runId:d,parentRunId:a.parentRunId,workflowId:f.workflowId,path:l,status:se.PLANNING,payload:{layers:f.layers.length,nodes:f.nodes.length}}),await this.client.backend.execute({document:e,plan:f,inputs:t,options:a,events:p},...n)}get backend(){return this.client.backend}get backendCapabilities(){return Lo(this.client.backend)}async listWorkflows(...e){const t=this.client.backend;if("supported"!==Lo(t).workflows.list||"function"!=typeof t.listWorkflows)throw new to(`Graph execution backend '${this.backendName}' does not support workflow listing`,"GRAPH_BACKEND_WORKFLOWS_NOT_SUPPORTED",{backend:this.backendName});return await t.listWorkflows(...e)}async getWorkflow(e,...t){const o=this.client.backend;if("supported"!==Lo(o).workflows.get||"function"!=typeof o.getWorkflow)throw new to(`Graph execution backend '${this.backendName}' does not support workflow lookup`,"GRAPH_BACKEND_WORKFLOWS_NOT_SUPPORTED",{backend:this.backendName,workflowId:e});return await o.getWorkflow(e,...t)}async listEngineWorkflows(e,...t){const o=Mo.getOrFail(e);if("supported"!==Lo(o).workflows.list||"function"!=typeof o.listWorkflows)throw new to(`Graph execution backend '${e}' does not support workflow listing`,"GRAPH_BACKEND_WORKFLOWS_NOT_SUPPORTED",{backend:e});return await o.listWorkflows(...t)}async getEngineWorkflow(e,t,...o){const n=Mo.getOrFail(e);if("supported"!==Lo(n).workflows.get||"function"!=typeof n.getWorkflow)throw new to(`Graph execution backend '${e}' does not support workflow lookup`,"GRAPH_BACKEND_WORKFLOWS_NOT_SUPPORTED",{backend:e,workflowId:t});return await n.getWorkflow(t,...o)}get backendName(){return this.client.backend.constructor?.name??"GraphExecutionBackend"}assertCodeModeSupported(e){const t=this.client.backend;if(t.local)return;const o=Vo(e);if(0!==o.length){if("unsupported"===t.codeMode)throw new to(`Graph execution backend '${this.backendName}' does not support code-mode workflows`,"GRAPH_CODE_MODE_UNSUPPORTED_BACKEND",{backend:this.backendName,surfaces:o});if(!this.codeSandboxEvaluator)throw new to("Code-mode workflows require a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator","GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{backend:this.backendName,surfaces:o})}}async pinNode(e){const t=this.createPinningService();await t.pinNode(e),await this.emitPinningEvent(e.nodeId,ce.NODE_PINNED)}async unpinNode(e){const t=this.createPinningService();await t.unpinNode(e),await this.emitPinningEvent(e.nodeId,ce.NODE_UNPINNED)}createPinningService(){const e=sn(this.valueAdapter);return new ln(e,new pn,new hn)}async emitPinningEvent(e,t){const o=(new fo).create({id:"",sequence:0,timestamp:new Date,runId:"pinning",workflowId:"",type:t,nodeId:e,path:[]});await this.emitter.updateObservers(o)}withWorkflowInputDefaults(e,t){const o={...t};for(const t of e.inputs)void 0===o[t.id]&&void 0!==t.defaultValue&&(o[t.id]=t.defaultValue);return o}mergeOptions(e){return{concurrency:4,failFast:!0,validateInputs:!0,validateOutputs:!0,maxLoopIterations:zt,maxForeachIterations:Jt,usePinnedValues:!0,writeThroughCache:!1,path:[],metadata:{},...this.defaultOptions,...e}}assertNotAborted(e){if(!0===e.abortSignal?.aborted)throw new uo(e.runId??"unknown")}generateRunId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new to("Cannot generate a graph run id: crypto.randomUUID is unavailable in this runtime","GRAPH_RUN_ID_ERROR",{runtime:typeof globalThis.crypto});return e.randomUUID()}}const Rn=new Set(["process","require","module","exports","global","globalThis","Function","eval","fetch","XMLHttpRequest","WebSocket","Worker","Deno","Bun","__dispatch"]);class $n extends W{constructor(){super()}async initialize(...e){const t=e[0]??{},o=t&&"object"==typeof t?t:{};return this._config=o,this._client=V,{config:o,client:V}}get defaultTimeoutMs(){return this.config.timeoutMs??1e3}get defaultMemoryMb(){return this.config.memoryMb??32}async evaluate(e,...t){(await this.logCtx(t,"evaluate",!0)).for(this.evaluate);const o=e.code;if(!o||"string"!=typeof o||0===o.trim().length)throw new to("Code sandbox received empty code","GRAPH_CODE_SANDBOX_EMPTY_CODE");const n=((e,t)=>"javascript"===t?e:X.transpileModule(e,{compilerOptions:{target:X.ScriptTarget.ES2022,module:X.ModuleKind.None,strict:!0,noEmitHelpers:!0,importHelpers:!1}}).outputText.replace(/^"use strict";\s*/,""))(o,e.language??"javascript");(e=>{if(e.length>1e5)throw new to("Code exceeds the maximum length of 100000 characters","GRAPH_CODE_SANDBOX_CODE_TOO_LONG",{length:e.length});let t;try{t=z.parse(`async function __validate() {\n${e}\n}`,{ecmaVersion:"latest",sourceType:"script"})}catch{try{t=z.parse(e,{ecmaVersion:"latest",sourceType:"module"})}catch(t){throw new to("Code failed to parse: "+t.message,"GRAPH_CODE_SANDBOX_PARSE_ERROR",{code:e,error:t.message})}}J.full(t,e=>{const t=e;if("ImportDeclaration"===t.type)throw new to("Imports are not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"import"});if("ExportNamedDeclaration"===t.type||"ExportDefaultDeclaration"===t.type)throw new to("Exports are not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"export"});if("Identifier"===t.type&&"string"==typeof t.name&&Rn.has(t.name))throw new to(`Identifier "${t.name}" is not allowed in Code nodes.`,"GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:t.name});if("NewExpression"===t.type&&"Function"===t.callee?.name)throw new to("new Function() is not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"Function"});if("CallExpression"===t.type&&"eval"===t.callee?.name)throw new to("eval() is not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"eval"})})})(n);const r=!(e=>/\breturn\b[\s;]/.test(e))(n),i=r?n.replace(/[\s;]+$/,""):n,a={$input:e.input??{},$vars:e.vars??{},$item:e.item,$index:e.index,$node:e.nodes??{},$output:void 0},s=Object.keys(a),d=r?`return (${i});`:i,l=`"use strict";\nasync function __userFunction(${s.join(", ")}) {\n${d}\n}\n__userFunction(${s.join(", ")}).then(function(__r) { return JSON.stringify({ v: __r }); });`,c=new V.Isolate({memoryLimit:this.defaultMemoryMb}),u=await c.createContext();try{const t=u.global;e.logger&&await this.injectConsole(u,e.logger);for(const[e,o]of Object.entries(a))await t.set(e,new V.ExternalCopy(void 0===o?null:o).copyInto());let o;try{o=await c.compileScript(l,{filename:"graph-code-node.js"})}catch(e){if(!r)throw new to("Code failed to compile: "+e.message,"GRAPH_CODE_SANDBOX_COMPILE_ERROR",{code:n,error:e.message});{const e=i,t=`"use strict";\nasync function __userFunction(${s.join(", ")}) {\n${e}\n}\n__userFunction(${s.join(", ")}).then(function(__r) { return JSON.stringify({ v: __r }); });`;try{o=await c.compileScript(t,{filename:"graph-code-node.js"})}catch(e){throw new to("Code failed to compile: "+e.message,"GRAPH_CODE_SANDBOX_COMPILE_ERROR",{code:n,error:e.message})}}}const d=e.timeoutMs??this.defaultTimeoutMs;let p;try{p=await this.runBounded(o,u,d,e.abortSignal)}catch(e){if(e instanceof to)throw e;const t=e.message;if(t.includes("timed out")||t.includes("timeout"))throw new to(`Code execution timed out after ${d} ms`,"GRAPH_CODE_SANDBOX_TIMEOUT",{timeoutMs:d});if(t.includes("memory")||t.includes("heap"))throw new to(`Code exceeded the memory limit of ${this.defaultMemoryMb} MB`,"GRAPH_CODE_SANDBOX_MEMORY_LIMIT",{memoryMb:this.defaultMemoryMb});throw new to("Code execution failed: "+t,"GRAPH_CODE_SANDBOX_RUNTIME_ERROR",{code:n,error:t})}if("string"!=typeof p)throw new to("Code sandbox returned an unexpected non-string result","GRAPH_CODE_SANDBOX_UNEXPECTED_RESULT",{result:p});return JSON.parse(p).v}finally{u.release(),c.dispose()}}async runBounded(e,t,o,n){const r=e.run(t,{timeout:o,promise:!0});r.catch(()=>{});const i=[r];let a,s;try{return i.push(new Promise((e,t)=>{a=setTimeout(()=>{t(new to(`Code execution timed out after ${o} ms`,"GRAPH_CODE_SANDBOX_TIMEOUT",{timeoutMs:o}))},o+100)})),n&&i.push(new Promise((e,t)=>{const r=()=>{const e="timeout"===n.reason;t(new to(e?`Code execution timed out after ${o} ms`:"Code execution aborted",e?"GRAPH_CODE_SANDBOX_TIMEOUT":"GRAPH_CODE_SANDBOX_ABORTED",{timeoutMs:o,reason:n.reason}))};n.aborted?r():(n.addEventListener("abort",r,{once:!0}),s=()=>n.removeEventListener("abort",r))})),await Promise.race(i)}finally{a&&clearTimeout(a),s?.()}}async injectConsole(e,t){const o=new V.Reference((e,o)=>{let n;try{n=JSON.parse(o)}catch{n=[o]}const r=n.map(e=>"string"==typeof e?e:JSON.stringify(e)).join(" "),i=1===n.length?n[0]:n;switch(e){case"log":case"info":default:t.info(r,i);break;case"warn":t.warn(r,i);break;case"error":t.error(r,i);break;case"debug":case"dir":case"dirxml":case"table":t.debug(r,i);break;case"trace":t.trace(r,i);break;case"group":case"groupCollapsed":t.debug("[group] "+r,i);break;case"groupEnd":t.debug("[groupEnd]",void 0);break;case"time":case"timeEnd":case"timeLog":case"count":case"countReset":t.debug(`[${e}] ${r}`,i);break;case"assert":n[0]||t.error("Assertion failed: "+r,i);case"clear":}});await e.evalClosure("\n function __ser() {\n var out = [];\n for (var i = 0; i < arguments.length; i++) {\n var a = arguments[i];\n try { out.push(typeof a === 'object' ? JSON.parse(JSON.stringify(a)) : a); }\n catch (e) { out.push(String(a)); }\n }\n return JSON.stringify(out);\n }\n function __call(level) {\n return function() {\n $0.applySync(undefined, [level, __ser.apply(null, arguments)]);\n };\n }\n globalThis.console = {\n log: __call('log'),\n info: __call('info'),\n warn: __call('warn'),\n error: __call('error'),\n debug: __call('debug'),\n trace: __call('trace'),\n dir: __call('dir'),\n dirxml: __call('dirxml'),\n table: __call('table'),\n group: __call('group'),\n groupCollapsed: __call('groupCollapsed'),\n groupEnd: __call('groupEnd'),\n time: __call('time'),\n timeEnd: __call('timeEnd'),\n timeLog: __call('timeLog'),\n assert: __call('assert'),\n count: __call('count'),\n countReset: __call('countReset'),\n clear: __call('clear')\n };\n ",[o]),o.release()}}class Cn extends x{constructor(e){super(e,Cn.name,500)}}class Tn extends _{constructor(e){super(e),this.name=Tn.name}}class Ln extends _{constructor(e){super(e),this.name=Ln.name}}class Mn{constructor(e,t,o={}){this.kind=e,this.declarations=new Map,this.implementations=new Map;for(const e of t){if("string"!=typeof e?.name||!e.name)throw new Cn(`Method declaration for kind '${this.kind}' is missing a name`);if(this.declarations.has(e.name))throw new Cn(`Kind '${this.kind}' declares duplicate method '${e.name}'`);this.declarations.set(e.name,e)}for(const[e,t]of Object.entries(o)){if("function"!=typeof t)throw new Cn(`Method implementation '${e}' for kind '${this.kind}' is not a function`);if(!this.declarations.has(e))throw new Cn(`Kind '${this.kind}' implements method '${e}' which is not declared by its manifest`);this.implementations.set(e,t)}for(const e of this.declarations.keys())if(!this.implementations.has(e))throw new Cn(`Kind '${this.kind}' declares method '${e}' with no implementation`)}has(e){return this.declarations.has(e)}getDeclaration(e){const t=this.declarations.get(e);if(!t)throw new Ln(`Kind '${this.kind}' does not declare method '${e}'`);return t}get(e){return this.getDeclaration(e),this.implementations.get(e)}list(){return[...this.declarations.values()].sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}}function jn(e,t){if(!t)return;let o=e;for(const e of t.split(".")){if(!o||"object"!=typeof o)return;o=o[e]}return o}function Gn(e,t,o){const n=jn(t,e.itemIdPath),r=e.itemLabelPath?jn(t,e.itemLabelPath):void 0;return{id:"string"==typeof n&&n||"number"==typeof n&&Number.isFinite(n)&&n+""||o+"",label:"string"==typeof r?r:void 0}}function Un(e,t){switch(t){case"input":return e.inputs;case"output":return e.outputs;default:return e.connections}}function Fn(e,t){const o={inputs:[],outputs:[],connections:[]},n={input:new Set((e.inputs??[]).map(e=>e.id)),output:new Set((e.outputs??[]).map(e=>e.id)),connection:new Set((e.connections??[]).map(e=>e.id))},r=(e,t)=>{const o=n[e];return!o.has(t)&&(o.add(t),!0)};for(const n of e.dynamicPorts??[])if("repeatFromParameter"===n.type){const e=t[n.parameter];if(!Array.isArray(e))continue;const i=Un(o,n.direction);e.forEach((e,t)=>{const{id:o,label:a}=Gn(n,e,t),s=(d={id:o,index:t,label:a??o},n.portIdTemplate.replaceAll("${id}",d.id).replaceAll("${index}",d.index+"").replaceAll("${label}",d.label));var d;if(!r(n.direction,s))return;const l=n.defaultPort?Fe(n.defaultPort):{id:s,label:a??s,direction:n.direction};l.id=s,l.direction=n.direction,a&&(l.label=a),i.push(l)})}else if("togglePort"===n.type){if(t[n.parameter]!==n.equals)continue;const e=Fe(n.port);if(!r(e.direction,e.id))continue;Un(o,e.direction).push(e)}return o}function Bn(e,t){const o=Fn(e,t),n={kind:e.kind,display:e.display,inputs:[...e.inputs,...o.inputs],outputs:[...e.outputs,...o.outputs],parameters:e.parameters},r=[...e.connections??[],...o.connections];return r.length&&(n.connections=r),e.dynamicPorts?.length&&(n.dynamicPorts=e.dynamicPorts),e.credentials?.length&&(n.credentials=e.credentials),e.capabilities?.length&&(n.capabilities=e.capabilities),e.policies&&(n.policies=e.policies),e.metadata&&(n.metadata=e.metadata),e.namespaces?.length&&(n.namespaces=e.namespaces),Fe(n)}class Wn{async resolve(e,t,o,n,r){if(o){const i=await o(n,r);if(!(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.kind&&"object"==typeof t.display&&null!==t.display&&Array.isArray(t.inputs)&&Array.isArray(t.outputs)&&Array.isArray(t.parameters)})(i))throw new Cn(`resolveManifest provider for kind '${e}' returned a value that does not conform to GraphResolvedNodeManifest`);if(!Ue(i))throw new Cn(`resolveManifest provider for kind '${e}' returned a non-JSON-safe resolved manifest`);const a=Fe(i);return!a.namespaces?.length&&t.namespaces?.length&&(a.namespaces=t.namespaces.slice()),a}return Bn(t,n.parameters??{})}}const qn=["edge","literal","expression"];function Hn(e){return qn.includes(e)}function Kn(e,t,o){if("string"!=typeof o||!o)throw new Cn(`Manifest for kind '${e}' has a ${t} with an empty port id`);if(Le(o))throw new Cn(`Manifest for kind '${e}' has a ${t} with unsafe port id '${o}'`)}let Vn=class extends B{constructor(){super(),this.entries=new Map,this.resolver=new Wn,this.fallbackContext=new M}withContext(e){return e[e.length-1]instanceof M?e:[this.fallbackContext]}register(e,t={},...o){const{log:n}=this.logCtx(this.withContext(o),"register").for(this.register);n.debug(`Registering graph node kind '${e?.manifest?.kind??"unknown"}'`),(e=>{if(!e||"object"!=typeof e)throw new Cn("Graph node registration is required");if(!e.manifest||"object"!=typeof e.manifest)throw new Cn("Graph node registration is missing a manifest");if(!e.executor||"function"!=typeof e.executor.execute)throw new Cn(`Graph node registration for kind '${e.manifest?.kind+""}' is missing an executor`)})(e);const r=e.manifest;if("string"!=typeof r.kind||!r.kind.trim())throw new Cn("Graph node manifest kind is required and must be a non-empty string");const i=r.kind;if(this.entries.has(i)&&!t.replace)throw new Cn(`Graph node kind '${i}' is already registered; pass { replace: true } to replace it`);try{mt(r)}catch(e){throw new Cn(`Manifest for kind '${i}' is not JSON-serializable: ${e.message}`)}((e,t)=>{const o=[["input",t.inputs],["output",t.outputs],["connection",t.connections??[]]];for(const[t,n]of o){const o=new Set;for(const r of n){if(Kn(e,t+" port",r?.id),o.has(r.id))throw new Cn(`Manifest for kind '${e}' declares duplicate static ${t} port id '${r.id}'`);if(o.add(r.id),void 0!==r.defaultMode&&!Hn(r.defaultMode))throw new Cn(`Manifest for kind '${e}' declares invalid default binding mode '${r.defaultMode+""}' on ${t} port '${r.id}'`)}}})(i,r);const a=((e,t)=>{const o=new Set;for(const n of t.parameters){const t=n?.id;if("string"!=typeof t||!t)throw new Cn(`Manifest for kind '${e}' has a parameter with an empty id`);if(Le(t))throw new Cn(`Manifest for kind '${e}' has a parameter with unsafe id '${t}'`);if(o.has(t))throw new Cn(`Manifest for kind '${e}' declares duplicate parameter id '${t}'`);o.add(t)}return o})(i,r);((e,t,o)=>{for(const n of t.dynamicPorts??[]){if(!n||"string"!=typeof n.parameter||!n.parameter)throw new Cn(`Manifest for kind '${e}' has a dynamic-port rule without a parameter reference`);if(!o.has(n.parameter))throw new Cn(`Manifest for kind '${e}' has a dynamic-port rule referencing missing parameter '${n.parameter}'`);if("togglePort"===n.type){if(!n.port)throw new Cn(`Manifest for kind '${e}' has a togglePort rule without a port`);Kn(e,"togglePort rule port",n.port.id)}if("repeatFromParameter"===n.type&&"string"!=typeof n.portIdTemplate)throw new Cn(`Manifest for kind '${e}' has a repeatFromParameter rule without a portIdTemplate`)}})(i,r,a),((e,t)=>{for(const o of t.credentials??[]){if(!ht(o))throw new Cn(`Manifest for kind '${e}' has a malformed credential requirement`);if(!o.type)throw new Cn(`Manifest for kind '${e}' has a credential requirement with an empty type`)}})(i,r),((e,t)=>{for(const o of t.methods??[])if(!wt(o))throw new Cn(`Manifest for kind '${e}' has a malformed method declaration`)})(i,r);const s=new Mn(i,r.methods??[],e.methods??{});return this.entries.set(i,{registration:e,methods:s,placeholderManifest:!1}),this}registerExecutor(e,t,...o){const{log:n}=this.logCtx(this.withContext(o),"registerExecutor").for(this.registerExecutor);if(n.debug(`Registering graph executor for kind '${e}'`),"string"!=typeof e||!e.trim())throw new Cn("Graph executor kind is required");if(!t||"function"!=typeof t.execute)throw new Cn(`Executor registered for kind '${e}' is missing an execute method`);const r=this.entries.get(e);if(r)return r.registration={...r.registration,executor:t},this;const i={kind:e,display:{name:e},inputs:[],outputs:[],parameters:[],policies:{allowUndeclaredParameters:!0,allowUnknownOutputs:!0}};return this.entries.set(e,{registration:{manifest:i,executor:t},methods:new Mn(e,[],{}),placeholderManifest:!0}),this}unregister(e,...t){const{log:o}=this.logCtx(this.withContext(t),"unregister").for(this.unregister);return o.debug(`Unregistering graph node kind '${e}'`),this.entries.delete(e),this}has(e,...t){return this.logCtx(this.withContext(t),"has").for(this.has),this.entries.has(e)}entry(e){const t=this.entries.get(e);if(!t)throw new Tn(`No graph node kind '${e}' is registered in the catalogue`);return t}getManifest(e,...t){return this.logCtx(this.withContext(t),"getManifest").for(this.getManifest),Fe(this.entry(e).registration.manifest)}getExecutor(e,...t){return this.logCtx(this.withContext(t),"getExecutor").for(this.getExecutor),this.entry(e).registration.executor}getMethodDeclaration(e,t,...o){return this.logCtx(this.withContext(o),"getMethodDeclaration").for(this.getMethodDeclaration),this.entry(e).methods.getDeclaration(t)}getMethod(e,t,...o){return this.logCtx(this.withContext(o),"getMethod").for(this.getMethod),this.entry(e).methods.getDeclaration(t),this.entry(e).methods.get(t)}listMethodDeclarations(e,...t){return this.logCtx(this.withContext(t),"listMethodDeclarations").for(this.listMethodDeclarations),this.entry(e).methods.list()}listManifests(e,...t){this.logCtx(this.withContext(t),"listManifests").for(this.listManifests);const o=[...this.entries.keys()].sort(),n=e?.categories?.length?new Set(e.categories):void 0,r=e?.kinds?.length?new Set(e.kinds):void 0,i=[];for(const e of o){if(r&&!r.has(e))continue;const o=this.getManifest(e,...t);n&&!n.has(o.display.category??"")||i.push(o)}return i}listKinds(...e){return this.logCtx(this.withContext(e),"listKinds").for(this.listKinds),[...this.entries.keys()].sort()}get size(){return this.entries.size}async resolveManifest(e,t,o,...n){this.logCtx(this.withContext(n),"resolveManifest").for(this.resolveManifest);const r=this.entry(e);return this.resolver.resolve(e,r.registration.manifest,r.registration.resolveManifest,t,o)}};Vn=S([F(),D("design:paramtypes",[])],Vn);let zn=class extends B{constructor(e=new Vn){super(),this.catalogue=e}get catalog(){return this.catalogue}register(e,t,...o){const{log:n}=this.logCtx(o,"register").for(this.register);if(n.debug(`Registering graph executor for kind '${e}'`),!e)throw new to("Graph executor kind is required");return this.catalogue.registerExecutor(e,t,...o),this}unregister(e,...t){const{log:o}=this.logCtx(t,"unregister").for(this.unregister);return o.debug(`Unregistering graph executor for kind '${e}'`),this.catalogue.unregister(e,...t),this}has(e,...t){return this.logCtx(t,"has").for(this.has),this.catalogue.has(e,...t)}resolve(e,...t){this.logCtx(t,"resolve").for(this.resolve);try{return this.catalogue.getExecutor(e,...t)}catch(t){if(t instanceof Tn)throw new to(`No graph executor registered for kind '${e}'`,"GRAPH_EXECUTOR_NOT_FOUND",{kind:e});throw t}}};zn=S([F(),D("design:paramtypes",[Vn])],zn);let Jn=class extends B{constructor(e,t){super(),this.registry=e,this.defaultExecutor=t}resolve(e,...t){const{log:o}=this.logCtx(t,"resolve").for(this.resolve);return o.debug(`Resolving graph executor for kind '${e}'`),this.registry.has(e,...t)?this.registry.resolve(e,...t):this.defaultExecutor?this.defaultExecutor:this.registry.resolve(e,...t)}};function Xn(e){return e}function Yn(e){return e.methods??[]}function Qn(e){if(!e)return;const t={...e.metadata??{},...e.parameters??{},...e.state??{}};return e.loop&&(t.loop=e.loop),t}Jn=S([F(),D("design:paramtypes",[Function,Object])],Jn);class Zn extends w{constructor(e){super(),w.fromModel(this,e)}execute(e,t){throw new to(`Graph node kind '${this.constructor.name}' does not implement execute`,"GRAPH_NODE_EXECUTE_NOT_IMPLEMENTED",{kind:this.constructor.name})}static applyMetadata(e){return null}static instantiate(e){return new this(e)}}let er=class extends Zn{execute(e,t){throw new co(e.inputs.value)}};function tr(e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack,code:e.graphCode??("number"==typeof e.code?e.code+"":e.code)}:{name:"UnknownError",message:e+""}}S([b(),i("ngx-decaf-crud-field",{label:"graph.node.flow_control.break.fields.value.label",placeholder:"graph.node.flow_control.break.fields.value.placeholder",type:"textarea"}),Re({handle:"value"}),D("design:type",Object)],er.prototype,"value",void 0),er=S([De("core.flow.break",{kind:"core.flow.break",category:"Flow Control",color:"#f59e0b",icon:"ti-square-arrow-right",width:96,height:96,labels:["flow","break","loop","control"],metadata:{title:"graph.node.flow_control.break.name",description:"graph.node.flow_control.break.description"}}),E()],er);let or=class extends Zn{async execute(e,t){const o=t.node.errorBoundary;if(!o?.try)return{result:e.inputs.value??e.inputs};const n=t.engine;if(!n)throw new to("errorBoundary node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");try{const r=await n.execute(o.try,e.inputs,{parentRunId:t.runId,path:[...t.path,"try"]}),i=Object.values(r.nodeResults).find(e=>e.status===se.FAILED);if(i)throw new to(i.error?.message??"error boundary try body failed",i.error?.code??"GRAPH_ERROR_BOUNDARY",i.error?.details);return{result:r.outputs.result??r.outputs}}catch(r){let i=r;if(o.catch){const a=await n.execute(o.catch,{...e.inputs,error:tr(r)},{parentRunId:t.runId,path:[...t.path,"catch"]});i=a.outputs.error??a.outputs}return{error:i}}finally{o.finally&&await n.execute(o.finally,e.inputs,{parentRunId:t.runId,path:[...t.path,"finally"]})}}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.flow_control.error_boundary.fields.value.label",placeholder:"graph.node.flow_control.error_boundary.fields.value.placeholder",type:"textarea"}),Re({handle:"value"}),D("design:type",Object)],or.prototype,"value",void 0),S([$e({handle:"result"}),D("design:type",Object)],or.prototype,"result",void 0),S([$e({handle:"error"}),D("design:type",Object)],or.prototype,"error",void 0),or=S([De("core.flow.errorBoundary",{kind:"core.flow.errorBoundary",category:"Flow Control",color:"#f59e0b",icon:"ti-shield-check",width:96,height:96,labels:["flow","error","try-catch"],metadata:{title:"graph.node.flow_control.error_boundary.name",description:"graph.node.flow_control.error_boundary.description",finally:!1}}),E()],or);let nr=class extends Zn{execute(e){const t=e.inputs.value??e.inputs;return!1===this.approved?{rejected:t}:{approved:t}}};S([b(),Re({handle:"value"}),D("design:type",Object)],nr.prototype,"value",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.human_approval.fields.message.label",placeholder:"graph.node.flow_control.human_approval.fields.message.placeholder",type:"textarea"}),Re({handle:"message",userControlled:!0}),D("design:type",String)],nr.prototype,"message",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.human_approval.fields.approved.label",type:"checkbox"}),Re({handle:"approved",userControlled:!0}),D("design:type",Boolean)],nr.prototype,"approved",void 0),S([$e({handle:"approved"}),D("design:type",Object)],nr.prototype,"approvedOut",void 0),S([$e({handle:"rejected"}),D("design:type",Object)],nr.prototype,"rejectedOut",void 0),nr=S([De("core.flow.humanApproval",{kind:"core.flow.humanApproval",category:"Flow Control",color:"#f59e0b",icon:"ti-user-check",width:96,height:96,labels:["flow","approval","suspend"],metadata:{title:"graph.node.flow_control.human_approval.name",description:"graph.node.flow_control.human_approval.description",approvers:[],timeoutMs:864e5}}),E()],nr);let rr=class extends Zn{execute(e,t){const o=e.inputs,n=o.value??o;if(!this.condition)throw new to("If node has no condition configured","GRAPH_IF_NO_CONDITION",{input:o});if(Go(this.condition))return Fo(this.condition,o,t).then(e=>this.route(e,n));const r=Bo(this.condition,((e,t)=>t===e||"object"!=typeof t||null===t||Array.isArray(t)?e:{...t,...e})(o,n),"if");return this.route(r,n)}route(e,t){if(e)return{then:t};if(!0===this.else)return{else:t};throw new to("If node condition evaluated to false and the else branch is disabled","GRAPH_IF_ELSE_DISABLED",{condition:this.condition})}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.value.label",placeholder:"graph.node.flow_control.if.fields.value.placeholder",type:"textarea"}),Re({handle:"value"}),D("design:type",Object)],rr.prototype,"value",void 0),S([b(),$e({handle:"then"}),D("design:type",Object)],rr.prototype,"then",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.condition.label",placeholder:"graph.node.flow_control.if.fields.condition.placeholder",type:"code"}),Re({handle:"condition",userControlled:!0,type:"object"}),D("design:type",Object)],rr.prototype,"condition",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.else.label",type:"checkbox"}),Re({handle:"else",userControlled:!0}),D("design:type",Boolean)],rr.prototype,"else",void 0),rr=S([De("core.flow.if",{kind:"core.flow.if",category:"Flow Control",color:"#f59e0b",icon:"ti-arrows-split-2",width:96,height:96,labels:["flow","conditional","branch"],metadata:{title:"graph.node.flow_control.if.name",description:"graph.node.flow_control.if.description"}}),E()],rr);let ir=class extends Zn{async execute(e,t){const o=((e,t)=>{const o={cases:t.cases??[],defaultPort:t.defaultPort??"default",hasDefault:!0===t.hasDefault},n=e.node.metadata?.switch;return n&&Array.isArray(n.cases)?{cases:n.cases,defaultPort:n.defaultPort??o.defaultPort,hasDefault:!0===n.hasDefault||o.hasDefault}:o})(t,this),n=o.cases,r=e.inputs,i=r.value??r,a=((e,t)=>t===e||"object"!=typeof t||null===t||Array.isArray(t)?e:{...t,...e})(r,i);for(const e of n)if(await Wo(e.condition,{input:r,state:a,label:"switch case"},t))return{[e.outputPort]:i};if(!0!==o.hasDefault)throw new to("No switch case matched and default port is not enabled","GRAPH_SWITCH_NO_MATCH",{cases:n.map(e=>e.id)});const s=o.defaultPort??"default";return{[s]:i}}static applyMetadata(e){const t=xe(this),o=e.defaultPort??"default",n=!0===e.hasDefault,r=t.ports.filter(t=>!e.cases.some(e=>e.outputPort===t.property)),i=r.filter(e=>e.property!==o),a=r.find(e=>e.property===o),s=[...i,...e.cases.map(e=>({property:e.outputPort,name:e.label,direction:Z.OUTPUT,label:e.label,required:!1,hidden:!1,path:e.outputPort}))];return n&&a&&s.push(a),{ports:s,size:te(t,{cases:e.cases.length}),dataPatch:{switchMetadata:e}}}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.value.label",placeholder:"graph.node.flow_control.switch.fields.value.placeholder",type:"textarea"}),Re({handle:"value"}),D("design:type",Object)],ir.prototype,"value",void 0),S([b(),$e({handle:"default"}),D("design:type",Object)],ir.prototype,"default",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.cases.label",type:"collection"}),D("design:type",Object)],ir.prototype,"cases",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.hasDefault.label",type:"checkbox"}),D("design:type",Boolean)],ir.prototype,"hasDefault",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.defaultPort.label",type:"text"}),D("design:type",String)],ir.prototype,"defaultPort",void 0),ir=S([De("core.flow.switch",{kind:"core.flow.switch",category:"Flow Control",color:"#f59e0b",icon:"ti-arrows-shuffle",width:120,height:140,sizeRules:[{type:"parameterCount",parameter:"cases",dimension:"height",perItem:24}],labels:["flow","switch","multi-branch"],metadata:{title:"graph.node.flow_control.switch.name",description:"graph.node.flow_control.switch.description"}}),E()],ir);const ar={maxDocumentBytes:2e6,maxNestingDepth:10,maxNodes:500,maxEdges:1e3},sr=o.accumulate({graph:{workflows:{limits:{...ar},allowAnonymousAccess:!1},execution:{maxCodeTimeoutMs:Xt}}}),dr=1e3;function lr(e,t){const o="number"==typeof t?t:Number(t),n=Number.isFinite(o)&&o>0?o:Xt,r="number"==typeof e?e:Number(e);return Number.isFinite(r)&&r>0?Math.min(Math.floor(r),n):1e3}const cr=["javascript","typescript"],ur="javascript";let pr=class extends w{constructor(){super(...arguments),this.language=ur}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.utility.code.fields.language.label",type:"select"}),N([...cr]),v(String),D("design:type",String)],pr.prototype,"language",void 0),S([b(),i("code-editor",{label:"graph.node.utility.code.fields.code.label",placeholder:"graph.node.utility.code.fields.code.placeholder"}),Re({handle:"code"}),D("design:type",String)],pr.prototype,"code",void 0),S([d(),Re({handle:"data"}),D("design:type",Object)],pr.prototype,"data",void 0),pr=S([E()],pr);let hr=class extends Zn{async execute(e,t){const o=e.inputs,n=this.input,r=o.code??e.parameters?.code??n?.code??this.defaultCode,i=n?.language??ur;if(!r||"string"!=typeof r||0===r.trim().length)throw new no("Code node has no code to execute (input.code is empty)",{input:o});const a=t.engine?.codeSandboxEvaluator;if(!a)throw new to("Code node execution requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator","GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{code:r});const s=sr.graph.execution?.maxCodeTimeoutMs,d="number"==typeof s&&Number.isFinite(s)&&s>0?s:Xt,l=lr(this.timeoutMs,d),c=t.metadata,u={code:r,language:i,input:o,vars:c?.vars??void 0,item:c?.item,index:c?.index,nodes:c?.nodes??void 0,logger:t.logger,timeoutMs:l,abortSignal:t.abortSignal};await t.log("Executing code node",{language:i,length:r.length,timeoutMs:l});const p=await a.evaluate(u);return await t.log("Code node executed",{hasResult:void 0!==p}),{result:p}}};S([b(),Re({handle:"input",model:pr}),D("design:type",pr)],hr.prototype,"input",void 0),S([O(1),k(Xt),i("ngx-decaf-crud-field",{label:"graph.node.utility.code.fields.timeoutMs.label",type:"number"}),Re({handle:"timeoutMs"}),D("design:type",Number)],hr.prototype,"timeoutMs",void 0),S([i("code-editor",{label:"graph.node.utility.code.fields.defaultCode.label",placeholder:"graph.node.utility.code.fields.defaultCode.placeholder"}),Re({handle:"defaultCode",userControlled:!0}),D("design:type",String)],hr.prototype,"defaultCode",void 0),S([b(),$e({handle:"result"}),D("design:type",Object)],hr.prototype,"result",void 0),hr=S([De("core.utility.code",{kind:"core.utility.code",category:"Utility",color:"#0d9488",icon:"ti-code",width:96,height:96,labels:["utility","code","sandbox","transform"],metadata:{title:"graph.node.utility.code.name",description:"graph.node.utility.code.description"}}),E()],hr);let fr=class extends Zn{execute(e){return{value:e.inputs.value??e.inputs}}};S([b(),Re({handle:"value"}),D("design:type",Object)],fr.prototype,"value",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.utility.delay.fields.timeoutMs.label",type:"number"}),Re({handle:"timeoutMs"}),D("design:type",Number)],fr.prototype,"timeoutMs",void 0),S([b(),$e({handle:"value"}),D("design:type",Object)],fr.prototype,"valueOut",void 0),fr=S([De("core.flow.delay",{kind:"core.flow.delay",category:"Utility",color:"#0d9488",icon:"ti-clock-hour-4",width:96,height:96,labels:["flow","delay","wait"],metadata:{title:"graph.node.utility.delay.name",description:"graph.node.utility.delay.description"}}),E()],fr);let gr=class extends Zn{execute(e,t){const o=e.inputs.value,n=this.level??"info";return t.logger[n](this.message??"Log node",{value:o}),{value:o}}};S([b(),Re({handle:"value"}),D("design:type",Object)],gr.prototype,"value",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.utility.log.fields.message.label",placeholder:"graph.node.utility.log.fields.message.placeholder",type:"textarea"}),Re({handle:"message"}),D("design:type",String)],gr.prototype,"message",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.utility.log.fields.level.label",placeholder:"graph.node.utility.log.fields.level.placeholder",type:"text"}),Re({handle:"level",userControlled:!0}),D("design:type",String)],gr.prototype,"level",void 0),S([b(),$e({handle:"value"}),D("design:type",Object)],gr.prototype,"valueOut",void 0),gr=S([De("core.flow.log",{kind:"core.flow.log",category:"Utility",color:"#0d9488",icon:"ti-terminal",width:96,height:96,labels:["flow","log","debug","utility"],metadata:{title:"graph.node.utility.log.name",description:"graph.node.utility.log.description"}}),E()],gr);let mr=class extends Zn{execute(e){return{result:{mapped:e.inputs.value??e.inputs}}}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.utility.map.fields.value.label",placeholder:"graph.node.utility.map.fields.value.placeholder",type:"textarea"}),Re({handle:"value"}),D("design:type",Object)],mr.prototype,"value",void 0),S([b(),$e({handle:"result"}),D("design:type",Object)],mr.prototype,"result",void 0),mr=S([De("core.utility.map",{kind:"core.utility.map",category:"Utility",color:"#0d9488",icon:"ti-arrows-right-left",width:96,height:96,labels:["utility","map","transform"],metadata:{title:"graph.node.utility.map.name",description:"graph.node.utility.map.description",mapper:{}}}),E()],mr);let yr=class extends Zn{execute(e,t){const o=e.inputs.value,n=this.level??"info";return t.logger[n](this.message??"Log node",{value:o}),{value:o}}};S([b(),Re({handle:"value"}),D("design:type",Object)],yr.prototype,"value",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.utility.utility_log.fields.message.label",placeholder:"graph.node.utility.utility_log.fields.message.placeholder",type:"textarea"}),Re({handle:"message"}),D("design:type",String)],yr.prototype,"message",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.utility.utility_log.fields.level.label",placeholder:"graph.node.utility.utility_log.fields.level.placeholder"}),Re({handle:"level",userControlled:!0,type:"string"}),D("design:type",String)],yr.prototype,"level",void 0),S([b(),$e({handle:"value"}),D("design:type",Object)],yr.prototype,"valueOut",void 0),yr=S([De("core.utility.log",{kind:"core.utility.log",category:"Utility",color:"#0d9488",icon:"ti-terminal",width:96,height:96,labels:["utility","log","debug","observability"],metadata:{title:"graph.node.utility.utility_log.name",description:"graph.node.utility.utility_log.description"}}),E()],yr);let wr=class extends Zn{execute(e){return{message:e.inputs.message??null,sessionId:e.inputs.sessionId??null,userId:e.inputs.userId??null}}};S([b(),$e({handle:"message"}),D("design:type",String)],wr.prototype,"message",void 0),S([b(),$e({handle:"sessionId"}),D("design:type",String)],wr.prototype,"sessionId",void 0),S([b(),$e({handle:"userId"}),D("design:type",String)],wr.prototype,"userId",void 0),wr=S([De("core.trigger.chat",{kind:"core.trigger.chat",category:"Trigger",color:"#3b82f6",icon:"ti-message-circle",width:96,height:96,labels:["trigger","chat","entrypoint"],metadata:{title:"graph.node.trigger.chat.name",description:"graph.node.trigger.chat.description",trigger:{type:"chat"}}}),E()],wr);let br=class extends Zn{execute(e){return{payload:e.inputs.payload??null}}};S([b(),$e({handle:"payload"}),D("design:type",Object)],br.prototype,"payload",void 0),br=S([De("core.trigger.event",{kind:"core.trigger.event",category:"Trigger",color:"#3b82f6",icon:"ti-broadcast",width:96,height:96,labels:["trigger","event","bus"],metadata:{title:"graph.node.trigger.event.name",description:"graph.node.trigger.event.description",trigger:{type:"event",topic:"default"}}}),E()],br);let vr=class extends Zn{execute(e){return{payload:e.inputs.payload??null}}};S([b(),Re({handle:"schema"}),i("ngx-decaf-model-builder",{label:"graph.node.trigger.form.fields.schema.label",placeholder:"graph.node.trigger.form.fields.schema.placeholder"}),D("design:type",Object)],vr.prototype,"schema",void 0),S([b(),$e({handle:"payload"}),D("design:type",Object)],vr.prototype,"payload",void 0),vr=S([De("core.trigger.form",{kind:"core.trigger.form",category:"Trigger",color:"#3b82f6",icon:"ti-forms",width:96,height:96,labels:["trigger","form","public"],metadata:{title:"graph.node.trigger.form.name",description:"graph.node.trigger.form.description",trigger:{type:"form",fields:[]}}}),E()],vr);let Ir=class extends Zn{execute(e){return{payload:e.inputs.payload??null}}};S([b(),$e({handle:"payload"}),D("design:type",Object)],Ir.prototype,"payload",void 0),Ir=S([De("core.trigger.manual",{kind:"core.trigger.manual",category:"Trigger",color:"#3b82f6",icon:"ti-hand-click",width:96,height:96,labels:["trigger","manual","entrypoint"],metadata:{title:"graph.node.trigger.manual.name",description:"graph.node.trigger.manual.description",trigger:{type:"manual",inputSchema:{}}}}),E()],Ir);let Er=class extends Zn{execute(e){return{payload:e.inputs.payload??null}}};S([b(),Re({handle:"cron"}),i("app-cron-selector-field",{label:"graph.node.trigger.schedule.fields.cron.label",placeholder:"graph.node.trigger.schedule.fields.cron.placeholder"}),D("design:type",String)],Er.prototype,"cron",void 0),S([b(),$e({handle:"payload"}),D("design:type",Object)],Er.prototype,"payload",void 0),Er=S([De("core.trigger.schedule",{kind:"core.trigger.schedule",category:"Trigger",color:"#3b82f6",icon:"ti-calendar-time",width:96,height:96,labels:["trigger","schedule","cron"],metadata:{title:"graph.node.trigger.schedule.name",description:"graph.node.trigger.schedule.description",trigger:{type:"schedule",schedule:"0 * * * *",timezone:"UTC"}}}),E()],Er);let Nr=class extends Zn{execute(e){return{payload:e.inputs.payload??null}}};S([b(),Re({handle:"schema"}),i("ngx-decaf-model-builder",{label:"graph.node.trigger.webhook.fields.schema.label",placeholder:"graph.node.trigger.webhook.fields.schema.placeholder"}),D("design:type",Object)],Nr.prototype,"schema",void 0),S([b(),$e({handle:"payload"}),D("design:type",Object)],Nr.prototype,"payload",void 0),Nr=S([De("core.trigger.webhook",{kind:"core.trigger.webhook",category:"Trigger",color:"#3b82f6",icon:"ti-webhook",width:96,height:96,labels:["trigger","webhook","http"],metadata:{title:"graph.node.trigger.webhook.name",description:"graph.node.trigger.webhook.description",trigger:{type:"webhook",path:"/webhook",method:"POST",auth:"none",responseMode:"onReceived"}}}),E()],Nr);let Or=class extends Zn{execute(e){return{response:"[Agent response] "+(e.inputs.prompt??""),actions:[]}}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.agent.agent.fields.prompt.label",placeholder:"graph.node.agent.agent.fields.prompt.placeholder",type:"textarea"}),Re({handle:"prompt"}),D("design:type",String)],Or.prototype,"prompt",void 0),S([b(),$e({handle:"response"}),D("design:type",String)],Or.prototype,"response",void 0),S([b(),$e({handle:"actions"}),D("design:type",Array)],Or.prototype,"actions",void 0),S([Ce({category:"model",handle:"model"}),D("design:type",Object)],Or.prototype,"model",void 0),S([Ce({category:"memory",handle:"memory"}),D("design:type",Object)],Or.prototype,"memory",void 0),S([Ce({category:"workspace",handle:"workspace"}),D("design:type",Object)],Or.prototype,"workspace",void 0),Or=S([De("core.agent",{kind:"core.agent",category:"Agent",width:140,height:120,labels:["agent","ai","orchestrator"],metadata:{title:"graph.node.agent.agent.name",description:"graph.node.agent.agent.description",shape:"rectangle"}}),E()],Or);const kr=[Or];function Ar(e,t,o,n){const r=t??o;if(null==e)return Math.min(o,r);const i=Number(e);if(!Number.isFinite(i)||0>=i)throw new no(n+" loop maxIterations must be a positive finite number");return Math.min(Math.floor(i),r)}function xr(e,t,o){const n=t.node.loop,r=t.metadata?.loop;if(!n?.body&&!r?.body)throw new no(o+" node is missing loop configuration (instance.loop.body)");const i=t=>{const o=e[t]??n?.[t]??r?.[t],i=Number(o);return void 0!==o&&Number.isFinite(i)?i:void 0},a=t=>{const o=e[t]??r?.[t];return"string"==typeof o?o:void 0};return{body:n?.body??r?.body,maxIterations:i("maxIterations"),timeoutMs:i("timeoutMs"),concurrency:i("concurrency"),condition:e.condition??r?.condition,inputPort:a("inputPort"),outputPort:a("outputPort"),itemPort:a("itemPort"),resultPort:a("resultPort"),statePort:a("statePort"),slice:i("slice")}}let _r=class extends Zn{async execute(e,t){const o=xr(this,t,"foreach"),n=e.inputs,r=n.items,i=Ar(o.maxIterations,t.limits?.maxForeachIterations,1e3,"foreach");if(!Array.isArray(r))throw new no("foreach input 'items' must be an array");const a=t.engine;if(!a)throw new to("foreach node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");const s=Number(n.slice??o.slice??1),d=Number.isFinite(s)&&s>0?Math.floor(s):1,l=d>1?Math.ceil(r.length/d):r.length;if(l>i)throw new ro(`foreach exceeded max iterations (${l} > ${i})`);const c=o.itemPort??"item",u=o.resultPort??"result",p=o.statePort??"state",h=o.body,f=[];let g=n.state,m=!1;await t.emit({type:ce.LOOP_STARTED});for(let e=0;l>e;e++){await t.emit({type:ce.LOOP_ITERATION_STARTED,iteration:e});const o=d>1?r.slice(e*d,e*d+d):r[e],n={[c]:o,index:e};d>1&&(n.slice=o),void 0!==g&&(n[p]=g);try{const r=await a.execute(h,n,{parentRunId:t.runId,path:[...t.path,"iteration:"+e],metadata:{item:o,index:e,slice:d},auth:t.auth},t);f.push(r.outputs[u]),void 0!==r.outputs[p]&&(g=r.outputs[p])}catch(o){if(o instanceof co){const n=o.details?.value;void 0!==n&&f.push(n),m=!0,await t.emit({type:ce.LOOP_ITERATION_COMPLETED,iteration:e,metadata:{broken:!0}});break}throw o}await t.emit({type:ce.LOOP_ITERATION_COMPLETED,iteration:e})}await t.emit({type:ce.LOOP_COMPLETED,metadata:{broken:m}});const y={results:f,completed:f,iterations:f.length,broken:m};return void 0!==g&&(y[p]=g),y}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.items.label",placeholder:"graph.node.loop.foreach.fields.items.placeholder",type:"textarea"}),Re({handle:"items"}),D("design:type",Array)],_r.prototype,"items",void 0),S([b(),i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.slice.label",placeholder:"graph.node.loop.foreach.fields.slice.placeholder",type:"number"}),Re({handle:"slice"}),D("design:type",Number)],_r.prototype,"slice",void 0),S([b(),$e({handle:"item"}),D("design:type",Object)],_r.prototype,"item",void 0),S([b(),Ce({handle:"loop",connectionRules:{allowSelf:!0,maxConnections:1}}),D("design:type",Object)],_r.prototype,"loop",void 0),S([b(),$e({handle:"completed"}),D("design:type",Array)],_r.prototype,"completed",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.maxIterations.label",type:"number"}),Re({handle:"maxIterations",userControlled:!0}),D("design:type",Number)],_r.prototype,"maxIterations",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.condition.label",type:"code"}),Re({handle:"condition",userControlled:!0}),D("design:type",Object)],_r.prototype,"condition",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.itemPort.label",type:"text"}),Re({handle:"itemPort",userControlled:!0}),D("design:type",String)],_r.prototype,"itemPort",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.resultPort.label",type:"text"}),Re({handle:"resultPort",userControlled:!0}),D("design:type",String)],_r.prototype,"resultPort",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.statePort.label",type:"text"}),Re({handle:"statePort",userControlled:!0}),D("design:type",String)],_r.prototype,"statePort",void 0),_r=S([De("graph-foreach-loop-node",{kind:"core.loop.foreach",category:"Loop",color:"#eab308",icon:"ti-repeat",width:120,height:140,labels:["loop","iteration","foreach"],metadata:{title:"graph.node.loop.foreach.name",description:"graph.node.loop.foreach.description",loop:{maxIterations:100,itemPort:"item",resultPort:"result",slice:1}}}),E()],_r);class Sr{constructor(){this.expressionEvaluator=new jo}evaluate(e,t){if(this.isConditionExpression(e))return this.expressionEvaluator.evaluate(e,t);const o=this.resolveValue(e.left,t),n=e.right;switch(e.type){case Zt.TRUTHY:return!!o;case Zt.FALSY:return!o;case Zt.EQUALS:return o===n;case Zt.NOT_EQUALS:return o!==n;case Zt.GREATER_THAN:return Number(o)>Number(n);case Zt.GREATER_THAN_OR_EQUAL:return Number(o)>=Number(n);case Zt.LESS_THAN:return Number(n)>Number(o);case Zt.LESS_THAN_OR_EQUAL:return Number(n)>=Number(o);case Zt.EXISTS:return null!=o;case Zt.CUSTOM:throw new to("Custom condition evaluators are not supported in v1","GRAPH_CUSTOM_CONDITION_UNSUPPORTED");default:throw new to(`Unknown condition type '${e.type}'`,"GRAPH_UNKNOWN_CONDITION_TYPE",{condition:e})}}async evaluateAsync(e,t,o,n){return Go(e)?Fo(e,n,o):this.evaluate(e,t)}resolveValue(e,t){if(!e)return t;const o=e.split(".");let n=t;for(const e of o){if(null==n)return;n=n[e]}return n}isConditionExpression(e){return"string"==typeof e.op}}let Dr=class extends Zn{async execute(e,t){const o=xr(this,t,"until"),n=e.inputs,r=Ar(o.maxIterations,t.limits?.maxLoopIterations,100,"until"),i=o.condition;if(!i)throw new no("until node is missing a condition");const a=o.statePort??"state",s=o.inputPort??a,d=o.outputPort??a,l=o.body,c=t.engine;if(!c)throw new to("until node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");let u=n.state,p=0;await t.emit({type:ce.LOOP_STARTED});let h=!1;do{if(p>=r)throw await t.emit({type:ce.LOOP_LIMIT_REACHED,iteration:p}),new ro(`until loop exceeded max iterations (${r})`);await t.emit({type:ce.LOOP_ITERATION_STARTED,iteration:p}),u=(await c.execute(l,{[s]:u,iteration:p},{parentRunId:t.runId,path:[...t.path,"iteration:"+p],auth:t.auth},t)).outputs[d],await t.emit({type:ce.LOOP_ITERATION_COMPLETED,iteration:p});const e=await(new Sr).evaluateAsync(i,u,t,{...n,state:u});await t.emit({type:ce.LOOP_CONDITION_EVALUATED,iteration:p,payload:{result:e}}),p++,h=e}while(!h);return await t.emit({type:ce.LOOP_COMPLETED}),{state:u,iterations:p}}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.state.label",placeholder:"graph.node.loop.until.fields.state.placeholder",type:"textarea"}),Re({handle:"state"}),D("design:type",Object)],Dr.prototype,"state",void 0),S([b(),$e({handle:"state"}),D("design:type",Object)],Dr.prototype,"stateOut",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.maxIterations.label",type:"number"}),Re({handle:"maxIterations",userControlled:!0}),D("design:type",Number)],Dr.prototype,"maxIterations",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.condition.label",type:"code"}),Re({handle:"condition",userControlled:!0}),D("design:type",Object)],Dr.prototype,"condition",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.statePort.label",type:"text"}),Re({handle:"statePort",userControlled:!0}),D("design:type",String)],Dr.prototype,"statePort",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.inputPort.label",type:"text"}),Re({handle:"inputPort",userControlled:!0}),D("design:type",String)],Dr.prototype,"inputPort",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.outputPort.label",type:"text"}),Re({handle:"outputPort",userControlled:!0}),D("design:type",String)],Dr.prototype,"outputPort",void 0),Dr=S([De("graph-until-loop-node",{kind:"core.loop.until",category:"Loop",color:"#eab308",icon:"ti-player-stop",width:96,height:96,labels:["loop","conditional","until"],metadata:{title:"graph.node.loop.until.name",description:"graph.node.loop.until.description",loop:{maxIterations:50,statePort:"state",condition:{type:"greaterThanOrEqual",left:"iteration",right:2}}}}),E()],Dr);let Pr=class extends Zn{async execute(e,t){const o=xr(this,t,"while"),n=e.inputs,r=Ar(o.maxIterations,t.limits?.maxLoopIterations,100,"while"),i=o.condition;if(!i)throw new no("while node is missing a condition");const a=o.statePort??"state",s=o.inputPort??a,d=o.outputPort??a,l=o.body,c=t.engine;if(!c)throw new to("while node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");let u=n.state,p=0;for(await t.emit({type:ce.LOOP_STARTED});await(new Sr).evaluateAsync(i,u,t,{...n,state:u});){if(p>=r)throw await t.emit({type:ce.LOOP_LIMIT_REACHED,iteration:p}),new ro(`while loop exceeded max iterations (${r})`);await t.emit({type:ce.LOOP_CONDITION_EVALUATED,iteration:p,payload:{result:!0}}),await t.emit({type:ce.LOOP_ITERATION_STARTED,iteration:p}),u=(await c.execute(l,{[s]:u,iteration:p},{parentRunId:t.runId,path:[...t.path,"iteration:"+p],auth:t.auth},t)).outputs[d],await t.emit({type:ce.LOOP_ITERATION_COMPLETED,iteration:p}),p++}return await t.emit({type:ce.LOOP_COMPLETED}),{state:u,iterations:p}}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.state.label",placeholder:"graph.node.loop.while.fields.state.placeholder",type:"textarea"}),Re({handle:"state"}),D("design:type",Object)],Pr.prototype,"state",void 0),S([b(),$e({handle:"state"}),D("design:type",Object)],Pr.prototype,"stateOut",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.maxIterations.label",type:"number"}),Re({handle:"maxIterations",userControlled:!0}),D("design:type",Number)],Pr.prototype,"maxIterations",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.condition.label",type:"code"}),Re({handle:"condition",userControlled:!0}),D("design:type",Object)],Pr.prototype,"condition",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.statePort.label",type:"text"}),Re({handle:"statePort",userControlled:!0}),D("design:type",String)],Pr.prototype,"statePort",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.inputPort.label",type:"text"}),Re({handle:"inputPort",userControlled:!0}),D("design:type",String)],Pr.prototype,"inputPort",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.outputPort.label",type:"text"}),Re({handle:"outputPort",userControlled:!0}),D("design:type",String)],Pr.prototype,"outputPort",void 0),Pr=S([De("graph-while-loop-node",{kind:"core.loop.while",category:"Loop",color:"#eab308",icon:"ti-arrows-loop",width:96,height:96,labels:["loop","conditional","while"],metadata:{title:"graph.node.loop.while.name",description:"graph.node.loop.while.description",loop:{maxIterations:50,statePort:"state",condition:{type:"lessThan",left:"iteration",right:3}}}}),E()],Pr);let Rr=class extends Zn{execute(e){const t=e.inputs;return{value:t?.value??null}}};S([$e({handle:"value",connectionRules:{allowMultiple:!0}}),D("design:type",Object)],Rr.prototype,"value",void 0),Rr=S([De("graph-input-value-node",{kind:"value",category:"Boundary",color:"#0f766e",icon:"ti-circle-plus",labels:["workflow","input","value"],metadata:{title:"graph.node.boundary.input.name",description:"graph.node.boundary.input.description"}}),E()],Rr);let $r=class extends Zn{execute(e){return{}}};function Cr(e,t,o,n={}){return{id:e,label:t,direction:o,...n}}function Tr(e){const t=e,o=ve(t),n=o?.metadata?.title;return Tt(t,n?{name:n}:{})}S([b(),Re({handle:"value"}),D("design:type",Object)],$r.prototype,"value",void 0),$r=S([De("graph-output-value-node",{kind:"result",category:"Boundary",color:"#0f766e",icon:"ti-circle-minus",width:96,height:96,labels:["workflow","output","value"],metadata:{title:"graph.node.boundary.output.name",description:"graph.node.boundary.output.description"}}),E()],$r);const Lr={kind:"core.loop.foreach",capabilities:["loop"],display:{name:"graph.node.loop.foreach.name",description:"graph.node.loop.foreach.description",category:"Loop",color:"#eab308",icon:{type:"catalogue",name:"ti-repeat"},width:120,height:140,labels:["loop","iteration","foreach"]},inputs:[Cr("items","graph.node.loop.foreach.ports.input.items.label","input",{required:!0,schema:{type:"array",items:{type:"any"}}}),Cr("slice","graph.node.loop.foreach.ports.input.slice.label","input",{schema:{type:"number",integer:!0,min:1}}),Cr("state","graph.node.loop.foreach.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[Cr("results","graph.node.loop.foreach.ports.output.results.label","output",{schema:{type:"array",items:{type:"any"}}}),Cr("completed","graph.node.loop.foreach.ports.output.completed.label","output",{schema:{type:"array",items:{type:"any"}}}),Cr("iterations","graph.node.loop.foreach.ports.output.iterations.label","output",{schema:{type:"number",integer:!0,min:0}}),Cr("broken","graph.node.loop.foreach.ports.output.broken.label","output",{schema:{type:"boolean"}}),Cr("state","graph.node.loop.foreach.ports.output.state.label","output",{schema:{type:"any"}})],parameters:[{type:"number",id:"maxIterations",label:"graph.node.loop.foreach.fields.maxIterations.label",integer:!0,min:1},{type:"object",id:"condition",label:"graph.node.loop.foreach.fields.condition.label"},{type:"string",id:"itemPort",label:"graph.node.loop.foreach.fields.itemPort.label"},{type:"string",id:"resultPort",label:"graph.node.loop.foreach.fields.resultPort.label"},{type:"string",id:"statePort",label:"graph.node.loop.foreach.fields.statePort.label"},{type:"number",id:"slice",label:"graph.node.loop.foreach.fields.slice.label",integer:!0,min:1}]},Mr={kind:"core.loop.while",capabilities:["loop"],display:{name:"graph.node.loop.while.name",description:"graph.node.loop.while.description",category:"Loop",color:"#eab308",icon:{type:"catalogue",name:"ti-arrows-loop"},width:120,height:140,labels:["loop","conditional","while"]},inputs:[Cr("state","graph.node.loop.while.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[Cr("state","graph.node.loop.while.ports.output.state.label","output",{schema:{type:"any"}}),Cr("iterations","graph.node.loop.while.ports.output.iterations.label","output",{schema:{type:"number",integer:!0,min:0}})],parameters:[{type:"number",id:"maxIterations",label:"graph.node.loop.while.fields.maxIterations.label",integer:!0,min:1},{type:"object",id:"condition",label:"graph.node.loop.while.fields.condition.label",required:!0},{type:"string",id:"statePort",label:"graph.node.loop.while.fields.statePort.label"},{type:"string",id:"inputPort",label:"graph.node.loop.while.fields.inputPort.label"},{type:"string",id:"outputPort",label:"graph.node.loop.while.fields.outputPort.label"}]},jr={kind:"core.loop.until",capabilities:["loop"],display:{name:"graph.node.loop.until.name",description:"graph.node.loop.until.description",category:"Loop",color:"#eab308",icon:{type:"catalogue",name:"ti-player-stop"},width:120,height:140,labels:["loop","conditional","until"]},inputs:[Cr("state","graph.node.loop.until.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[Cr("state","graph.node.loop.until.ports.output.state.label","output",{schema:{type:"any"}}),Cr("iterations","graph.node.loop.until.ports.output.iterations.label","output",{schema:{type:"number",integer:!0,min:0}})],parameters:[{type:"number",id:"maxIterations",label:"graph.node.loop.until.fields.maxIterations.label",integer:!0,min:1},{type:"object",id:"condition",label:"graph.node.loop.until.fields.condition.label",required:!0},{type:"string",id:"statePort",label:"graph.node.loop.until.fields.statePort.label"},{type:"string",id:"inputPort",label:"graph.node.loop.until.fields.inputPort.label"},{type:"string",id:"outputPort",label:"graph.node.loop.until.fields.outputPort.label"}]},Gr=[Tr(Rr),Tr($r),Tr(Ir),Tr(Nr),Tr(Er),Tr(br),Tr(vr),Tr(wr),(Ur=Tr(rr),{...Ur,dynamicPorts:[{type:"togglePort",parameter:"else",equals:!0,port:{id:"else",label:"graph.node.flow_control.if.ports.output.else.label",direction:"output",schema:{type:"any"}}}]}),(e=>({...e,outputs:[],parameters:[...e.parameters,{type:"collection",id:"cases",label:"graph.node.flow_control.switch.fields.cases.label",required:!0,itemIdPath:"outputPort",itemLabelPath:"label"},{type:"boolean",id:"hasDefault",label:"graph.node.flow_control.switch.fields.hasDefault.label",defaultValue:!1},{type:"object",id:"switch",label:"graph.node.flow_control.switch.fields.switch.label",required:!1}],dynamicPorts:[{type:"repeatFromParameter",parameter:"cases",itemIdPath:"outputPort",itemLabelPath:"label",direction:"output",portIdTemplate:"${id}",defaultPort:{id:"case",label:"graph.node.flow_control.switch.ports.output.case.label",direction:"output",schema:{type:"any"}}},{type:"togglePort",parameter:"hasDefault",equals:!0,port:{id:"default",label:"graph.node.flow_control.switch.ports.output.default.label",direction:"output",schema:{type:"any"}}}]}))(Tr(ir)),Tr(mr),Tr(fr),Tr(or),Tr(nr),Tr(hr),Tr(gr),Tr(yr),Tr(er),Tr(Or),Lr,Mr,jr];var Ur;const Fr=Object.fromEntries(Gr.map(e=>[e.kind,e])),Br=[Ir,Nr,Er,br,vr,wr],Wr=[rr,ir,fr,or,nr,gr,er],qr=[hr,mr,yr],Hr=[_r,Pr,Dr],Kr=[Rr,$r],Vr={value:Rr,result:$r,"core.trigger.manual":Ir,"core.trigger.webhook":Nr,"core.trigger.schedule":Er,"core.trigger.event":br,"core.trigger.form":vr,"core.trigger.chat":wr,"core.flow.if":rr,"core.flow.switch":ir,"core.utility.map":mr,"core.flow.delay":fr,"core.flow.errorBoundary":or,"core.flow.humanApproval":nr,"core.utility.code":hr,"core.flow.log":gr,"core.utility.log":yr,"core.flow.break":er,"core.agent":Or,"core.loop.foreach":_r,"core.loop.while":Pr,"core.loop.until":Dr};function zr(e){return{execute:(t,o)=>e.instantiate({...Qn(o.node),...t.parameters,...o.node.state??{}}).execute(t,o)}}function Jr(){const e=[];for(const[t,o]of Object.entries(Fr)){const n=Vr[t];n&&e.push(Xn({manifest:o,executor:zr(n)}))}return e}function Xr(e,...t){for(const o of Jr())e.register(o,{},...t);return e}class Yr{resolve(e){const t=this.createValidator(e);return{name:e.name,required:e.required,validate:t}}resolveAll(e){const t={};for(const o of e)t[o.name]=this.resolve(o);return t}createValidator(e){switch((e.type??e.designType??"").toLowerCase()){case"string":return e=>"string"==typeof e;case"number":return e=>"number"==typeof e;case"boolean":return e=>"boolean"==typeof e;case"date":return e=>e instanceof Date||"string"==typeof e&&!isNaN(Date.parse(e));case"array":return e=>Array.isArray(e);case"bigint":return e=>"bigint"==typeof e;default:return()=>!0}}}class Qr{constructor(e){this.resolver=e}validateWorkflowInputs(e,t){this.validatePorts(e.inputs,t,"workflow input")}validateWorkflowOutputs(e,t){this.validatePorts(e.outputs,t,"workflow output")}validateNodeInputs(e,t){const o=(e.ports??[]).filter(e=>"input"===e.direction);this.validatePorts(o,t,`node '${e.name}' input`)}validateNodeOutputs(e,t){const o=(e.ports??[]).filter(e=>"output"===e.direction);this.validatePorts(o,t,`node '${e.name}' output`)}validatePorts(e,t,o){if(e)for(const n of e){const e=Object.prototype.hasOwnProperty.call(t,n.name);if(n.required&&!e)throw new no(`Missing required ${o} port '${n.name}'`);if(e&&!this.resolver.resolve(n).validate(t[n.name]))throw new no(`Invalid value for ${o} port '${n.name}'`)}}}const Zr=["node","definition","executor","execute","ports","component"];function ei(e,t,o,n){return{code:e,path:t,message:o,...void 0!==n?.nodeId?{nodeId:n.nodeId}:{},...void 0!==n?.edgeId?{edgeId:n.edgeId}:{},...n?.details?{details:n.details}:{}}}function ti(e,t){const o=[];for(const n of Object.keys(e))Zr.includes(n)&&o.push(ei("document.forbidden-field",`${t}.${n}`,`Field '${n}' is not accepted in a canonical workflow document: node, definition, executor, execute, ports and component fields are rejected at the boundary`,{details:{field:n}}));return o}function oi(e,t){t.push(...ti(e,"$")),e.inputs.forEach((e,o)=>t.push(...ti(e,`inputs[${o}]`))),e.outputs.forEach((e,o)=>t.push(...ti(e,`outputs[${o}]`)));for(const o of e.nodes)t.push(...ti(o,`nodes[${o.id}]`)),o.loop&&(t.push(...ti(o.loop,`nodes[${o.id}].loop`)),oi(o.loop.body,t));for(const o of e.edges)t.push(...ti(o,`edges[${o.id}]`))}function ni(e,t){const o=[];e.nodes.length>t.maxNodes&&o.push(ei("document.limit.nodes","$.nodes",`Document declares ${e.nodes.length} nodes; at most ${t.maxNodes} are allowed`,{details:{count:e.nodes.length,limit:t.maxNodes}})),e.edges.length>t.maxEdges&&o.push(ei("document.limit.edges","$.edges",`Document declares ${e.edges.length} edges; at most ${t.maxEdges} are allowed`,{details:{count:e.edges.length,limit:t.maxEdges}}));const n=ri(e);n>t.maxNestingDepth&&o.push(ei("document.limit.depth","$.nodes",`Document nests loop bodies ${n} levels deep; at most ${t.maxNestingDepth} levels are allowed`,{details:{depth:n,limit:t.maxNestingDepth}}));const r=Buffer.byteLength(JSON.stringify(e),"utf8");return r>t.maxDocumentBytes&&o.push(ei("document.limit.size","$",`Document serializes to ${r} bytes; at most ${t.maxDocumentBytes} bytes are allowed`,{details:{bytes:r,limit:t.maxDocumentBytes}})),o}function ri(e,t=0){let o=t;for(const n of e.nodes)n.loop?.body&&(o=Math.max(o,ri(n.loop.body,t+1)));return o}async function ii(e,t,...o){const n=[];for(const r of e.nodes)t.has(r.kind,...o)||n.push(ei("node.unknown-kind",`nodes[${r.id}].kind`,`Node '${r.id}' references kind '${r.kind}' which is not registered in the backend catalogue`,{nodeId:r.id,details:{kind:r.kind}})),r.loop?.body&&n.push(...await ii(r.loop.body,t,...o));return n}async function ai(e,t={},...o){const n={...ar,...t.limits},r=[];if(!pt(e))return r.push(ei("document.shape","$","Payload is not a canonical GraphWorkflowDocument: id and name must be strings and inputs, outputs, nodes and edges must be arrays")),{valid:!1,issues:r};if(!Ue(e))return r.push(ei("document.json-unsafe","$","Document contains JSON-unsafe values: functions, class instances, undefined, NaN/Infinity, symbol keys and unsafe prototype keys (__proto__/prototype/constructor) are rejected")),{valid:!1,issues:r};oi(e,r),r.push(...(e=>{const t=[],o=new Set;for(const n of[...e.inputs,...e.outputs])o.has(n.id)?t.push(ei("document.duplicate-port-id",`ports[${n.id}]`,`Workflow port '${n.id}' is declared more than once; workflow port ids must be unique`)):o.add(n.id);const n=new Set;for(const o of e.nodes)n.has(o.id)?t.push(ei("document.duplicate-node-id",`nodes[${o.id}]`,`Node '${o.id}' is declared more than once; node ids must be unique`,{nodeId:o.id})):n.add(o.id);const r=new Set;for(const o of e.edges)r.has(o.id)?t.push(ei("document.duplicate-edge-id",`edges[${o.id}]`,`Edge '${o.id}' is declared more than once; edge ids must be unique`,{edgeId:o.id})):r.add(o.id);return t})(e)),r.push(...ni(e,n)),mn(e,r);try{ot(e)}catch(e){const t=e instanceof A?e.message:e+"";r.push(ei("document.structure","$",t))}return t.catalogue&&r.push(...await ii(e,t.catalogue,...o)),{valid:0===r.length,issues:r}}class si{constructor(e,t){this.iteration=e,this.metadata=t}}function di(e,t,o={}){const n=e?.owner??null;return!n||n===t||(null==t||""===t)&&!0===o.allowAnonymousAccess}function li(e,t){return(e?.owner??null)===(t??null)}function ci(e,t,o){if(!li(e,t))throw new L(`${o.resourceKind} '${o.resourceId}' is owned by another user`)}function ui(e,t,o){if(!di(e,t,o))throw new L(`${o.resourceKind} '${o.resourceId}' is owned by another user`)}function pi(e){if(null===e||"object"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(e=>pi(e)).join(",")}]`;const t=e;return`{${Object.keys(t).filter(e=>void 0!==t[e]).sort().map(e=>`${JSON.stringify(e)}:${pi(t[e])}`).join(",")}}`}function hi(e){return Y("sha256").update(pi(e)).digest("hex")}class fi{constructor(e={}){this.events=new Map,this.listeners=new Map,this.limits={...ue,...e}}async append(e){let t=this.events.get(e.runId);t||(t=[],this.events.set(e.runId,t)),t.push(e),this.enforceRetention(t);for(const t of this.listeners.get(e.runId)??[])try{t(e)}catch{}}async listAfter(e,t){const o=this.events.get(e);return o?o.filter(e=>e.sequence>t):[]}subscribe(e,t){let o=this.listeners.get(e);return o||(o=new Set,this.listeners.set(e,o)),o.add(t),()=>{o.delete(t),0===o.size&&this.listeners.delete(e)}}release(e){this.events.delete(e),this.listeners.delete(e)}enforceRetention(e){const t=this.limits.maxEventsPerRun;for(;e.length>t;){const t=e.findIndex(e=>!he(e.type));if(-1===t)break;e.splice(t,1)}}}function gi(e){return new jt({runId:e.runId,workflowId:e.workflowId,...e.ownerUser?{owner:e.ownerUser}:{},status:e.status,...e.documentFingerprint?{documentFingerprint:e.documentFingerprint}:{},...void 0!==e.result?{result:mi(e.result)}:{},...e.error?{error:mi(e.error)}:{},createdAt:new Date(e.createdAt),...e.startedAt?{startedAt:new Date(e.startedAt)}:{},...e.finishedAt?{finishedAt:new Date(e.finishedAt)}:{}})}function mi(e){if(null!=e)return JSON.parse(JSON.stringify(e))}class yi{constructor(){this.runs=new Map}async saveRun(e){this.runs.set(e.runId,{...e})}async readRun(e){const t=this.runs.get(e);return t?{...t}:null}async listRuns(e){return[...this.runs.values()].filter(t=>t.workflowId===e).map(e=>gi(e))}release(e){this.runs.delete(e)}}class wi{constructor(e,t={}){this.sequences=new Map,this.chains=new Map,this.store=e,this.limits={...ue,...t}}async publish(e){const t=e.runId,o=(this.sequences.get(t)??0)+1;this.sequences.set(t,o);const n={...e,payload:this.limitPayload(e.payload),sequence:o,timestamp:(new Date).toISOString()},r=(this.chains.get(t)??Promise.resolve()).then(()=>this.store.append(n));return this.chains.set(t,r.catch(()=>{})),await r,n}lastSequence(e){return this.sequences.get(e)??0}release(e){this.sequences.delete(e),this.chains.delete(e)}limitPayload(e){if(void 0===e)return;let t;try{t=JSON.stringify(e)}catch{return{nonSerializable:!0}}return t.length>this.limits.maxEventPayloadBytes?{truncated:!0,reason:"event payload exceeds the configured byte limit",bytes:t.length}:e}}class bi{constructor(e,t,o,n={},r={}){this.controllers=new Map,this.completions=new Map,this.timeouts=new Map,this.engine=e,this.runStore=t,this.publisher=o,this.hooks=n,this.limits={...ue,...r}}begin(e){const t=this.controllers.get(e);if(t)return t;const o=new AbortController;return this.controllers.set(e,o),o}abort(e,t){const o=this.controllers.get(e);return!!o&&(o.signal.aborted||o.abort(t),!0)}isAborted(e){return!0===this.controllers.get(e)?.signal.aborted}abortReason(e){const t=this.controllers.get(e)?.signal;if(t?.aborted)return"timeout"===t.reason?"timeout":"user"}waitFor(e){return this.completions.get(e)}schedule(e,t,o,...n){const r=this.completions.get(e.runId);if(r)return r;const i=this.runExecution({...e},t,o,...n).catch(async t=>{const o=vi(t);try{await this.emitTerminal({...e},ce.WORKFLOW_FAILED,o)}catch{}return await this.finalize({...e},"failed",void 0,o,...n)});return this.completions.set(e.runId,i),i}release(e){this.controllers.delete(e),this.completions.delete(e);const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.publisher.release(e)}armTimeout(e){const t=setTimeout(()=>{this.timeouts.delete(e),this.abort(e,"timeout")},this.limits.executionTimeoutMs);this.timeouts.set(e,t)}async runExecution(e,t,o,...n){const r=e.runId;let i,a,s=!1;const d=this.engine.observe({refresh:async t=>{t.runId===r&&(t.error&&(i=t.error),he((await this.publisher.publish(this.envelopeOf(e,t))).type)?s=!0:t.type===ce.WORKFLOW_STARTED&&"validating"===e.status&&(e.status="running",await this.persist(e,...n)))}});this.armTimeout(r);try{if(this.isAborted(r)){const t={name:"GraphRunCancelledError",message:`Graph run '${r}' was cancelled before execution started`,code:"GRAPH_RUN_CANCELLED"};return i=t,await this.emitTerminal(e,ce.WORKFLOW_CANCELLED,t),s=!0,await this.finalize(e,"cancelled",void 0,t,...n)}let d,l;e.status="validating",e.startedAt=(new Date).toISOString(),await this.persist(e,...n);try{({document:d,fingerprint:l}=await t(...n)),e.documentFingerprint=l,await this.persist(e,...n)}catch(t){const o=vi(t);return i=o,s||(await this.emitTerminal(e,ce.WORKFLOW_FAILED,o),s=!0),await this.finalize(e,"failed",void 0,o,...n)}if(this.isAborted(r)){const t={name:"GraphRunCancelledError",message:`Graph run '${r}' was cancelled before execution started`,code:"GRAPH_RUN_CANCELLED"};return i=t,s||(await this.emitTerminal(e,ce.WORKFLOW_CANCELLED,t),s=!0),await this.finalize(e,"cancelled",void 0,t,...n)}try{a=await this.engine.execute(d,o,{runId:r,abortSignal:this.controllers.get(r)?.signal,metadata:{documentFingerprint:l}},...n)}catch(e){i=vi(e)}const c=this.abortReason(r);let u,p;return"timeout"===c?(u="failed",p=i??{name:"GraphRunTimeoutError",message:`Graph run '${r}' exceeded the configured execution timeout of ${this.limits.executionTimeoutMs}ms`,code:"GRAPH_RUN_TIMEOUT"}):"user"===c?(u="cancelled",p=i):a?.status===se.SUCCEEDED?u="succeeded":a?.status===se.CANCELLED?(u="cancelled",p=i):(u="failed",p=i??vi(new to(a?`Graph run '${r}' failed`:`Graph run '${r}' failed without a result`,"GRAPH_RUN_FAILED",{runId:r}))),s||await this.emitTerminal(e,"succeeded"===u?ce.WORKFLOW_COMPLETED:"cancelled"===u?ce.WORKFLOW_CANCELLED:ce.WORKFLOW_FAILED,p),await this.finalize(e,u,a,p,...n)}finally{d();const e=this.timeouts.get(r);e&&(clearTimeout(e),this.timeouts.delete(r))}}async emitTerminal(e,t,o){await this.publisher.publish({runId:e.runId,workflowId:e.workflowId,type:t,error:o})}async finalize(e,t,o,n,...r){e.status=t,o&&(e.result=o),n&&(e.error=n),e.startedAt||(e.startedAt=(new Date).toISOString()),e.finishedAt=(new Date).toISOString(),await this.persist(e,...r);try{await(this.hooks.onRunCompleted?.(e,o))}catch{}return e}async persist(e,...t){await this.runStore.saveRun({...e},...t)}envelopeOf(e,t){return{runId:e.runId,workflowId:t.workflowId??e.workflowId,type:t.type,nodeId:t.nodeId,edgeId:t.edgeId,payload:void 0===t.payload?void 0:Ge(t.payload)?t.payload:{nonSerializable:!0},error:t.error,parentRunId:t.parentRunId,path:t.path}}}function vi(e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack,code:e.graphCode??("number"==typeof e.code?e.code+"":e.code)}:{name:"UnknownError",message:e+""}}class Ii{constructor(e,t,o,n={}){this.activeByCaller=new Map,this.callerKeysByRun=new Map,this.releaseTimers=new Map,this.engine=e,this.runStore=t,this.eventStore=o,this.publisher=new wi(o,n.limits),this.executor=new bi(e,t,this.publisher,{onRunCompleted:n.onRunCompleted},n.limits),this.options={...n,limits:{...ue,...n.limits}}}get limits(){return this.options.limits}async createRun(e,t,o,...n){this.validateCreateRequest(e);const r=e.workflowId??e.workflow?.id??"";if(!r)throw new A("Graph run request must carry a workflow document with an id or a saved workflowId");if(e.workflowId&&!this.options.documentResolver)throw new A("Graph run requests by workflowId require a document resolver");const i=o??t??"anonymous",a=this.activeByCaller.get(i)??new Set;if(a.size>=this.options.limits.maxConcurrentRuns)throw new A(`Graph run rejected: the configured limit of ${this.options.limits.maxConcurrentRuns} concurrent runs per caller is exhausted`);const s=this.generateRunId(),d={runId:s,workflowId:r,ownerUser:t,status:"queued",createdAt:(new Date).toISOString()};this.executor.begin(s),await this.runStore.saveRun({...d},...n);const l=this.documentProviderFor(e,t);return a.add(s),this.activeByCaller.set(i,a),this.callerKeysByRun.set(s,i),this.executor.schedule(d,l,e.inputs??{},...n).catch(()=>{}).finally(()=>this.finishActiveRun(s)),d}async getRun(e,t,...o){const n=await this.runStore.readRun(e,...o);if(!n)throw new _(`No graph run found for runId '${e}'`);return this.assertOwnership(n,t),n}async listRunsByWorkflow(e,t,...o){return(await this.runStore.listRuns(e,...o)).filter(e=>di({owner:e.owner},t,{allowAnonymousAccess:!0===this.options.allowAnonymousAccess})).sort((e,t)=>{const o=e.updatedAt instanceof Date?e.updatedAt.getTime():NaN,n=t.updatedAt instanceof Date?t.updatedAt.getTime():NaN;return(Number.isFinite(n)?n:0)-(Number.isFinite(o)?o:0)})}async cancelRun(e,t,...o){const n=await this.runStore.readRun(e,...o);if(!n)throw new _(`No graph run found for runId '${e}'`);return this.assertWriteOwnership(n,t),"succeeded"===(r=n.status)||"failed"===r||"cancelled"===r||(this.executor.abort(e,"user"),n.status="cancelled",n.finishedAt=(new Date).toISOString(),await this.runStore.saveRun({...n},...o)),n;var r}async resumeRun(e,t,o,...n){const r=await this.runStore.readRun(e,...n);if(!r)throw new _(`No graph run found for runId '${e}'`);this.assertWriteOwnership(r,o);const i=this.engine.backend,a=i.resume;if("function"!=typeof a)throw new to(`Graph execution backend '${i.constructor?.name??"GraphExecutionBackend"}' does not support resume`,"GRAPH_RESUME_UNSUPPORTED_BACKEND",{runId:e});let s;try{s=await a.call(i,e,t,...n)}catch(e){throw(d=e)instanceof to?new to(d.message,d.graphCode):d}var d;const l={...s,runId:e,caller:o};return await this.publisher.publish({runId:e,workflowId:r.workflowId,type:ce.WORKFLOW_RESUMED,payload:l}),l}async listEvents(e,t,o,...n){return await this.getRun(e,o,...n),this.eventStore.listAfter(e,t)}async subscribeEvents(e,t,o,...n){return await this.getRun(e,t,...n),this.eventStore.subscribe(e,o)}subscribeRunEvents(e,t){return this.eventStore.subscribe(e.runId,t)}async waitForRun(e,t,...o){const n=this.executor.waitFor(e);return n&&await n,this.getRun(e,t,...o)}async executeAndWait(e,t,o,...n){const r=await this.createRun(e,t,o,...n);return this.waitForRun(r.runId,t,...n)}release(e){this.finishActiveRun(e);const t=this.releaseTimers.get(e);t&&(clearTimeout(t),this.releaseTimers.delete(e)),this.executor.release(e),this.eventStore.release?.(e)}finishActiveRun(e){const t=this.callerKeysByRun.get(e);if(void 0!==t){this.callerKeysByRun.delete(e);const o=this.activeByCaller.get(t);o&&(o.delete(e),0===o.size&&this.activeByCaller.delete(t))}if(this.releaseTimers.has(e))return;const o=setTimeout(()=>{this.releaseTimers.delete(e),this.release(e)},this.options.limits.eventReplayWindowMs);o.unref?.(),this.releaseTimers.set(e,o)}validateCreateRequest(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new A("Graph run request must be an object carrying either a workflow document or a workflowId plus inputs");const t=void 0!==e.workflow,o=void 0!==e.workflowId;if(t&&o)throw new A("Graph run request is ambiguous: supply either an unsaved workflow document or a saved workflowId, not both");if(!t&&!o)throw new A("Graph run request must supply either an unsaved workflow document or a saved workflowId");if(t&&!pt(e.workflow))throw new A("Graph run request carries a payload that is not a canonical GraphWorkflowDocument");if(void 0!==e.inputs&&!Ue(e.inputs))throw new A("Graph run inputs must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys and unsafe prototype keys (__proto__/prototype/constructor) are rejected");const n=(e=>{try{return JSON.stringify(e)?.length??0}catch{return Number.MAX_SAFE_INTEGER}})(e);if(n>this.options.limits.maxRequestBytes)throw new A(`Graph run request of ${n} bytes exceeds the configured limit of ${this.options.limits.maxRequestBytes} bytes`)}documentProviderFor(e,t){if(e.workflow){const t=e.workflow;return async()=>({document:t,fingerprint:hi(t)})}const o=e.workflowId;return async(...e)=>{const n=this.options.documentResolver;if(!n)throw new A("Graph run requests by workflowId require a document resolver");const r=await n.resolve(o,t,...e);return{document:r,fingerprint:hi(r)}}}assertOwnership(e,t){ui({owner:e.ownerUser},t,{allowAnonymousAccess:!0===this.options.allowAnonymousAccess,resourceKind:"Graph run",resourceId:e.runId})}assertWriteOwnership(e,t){ci({owner:e.ownerUser},t,{resourceKind:"Graph run",resourceId:e.runId})}generateRunId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new so("Cannot generate a graph run id: crypto.randomUUID is unavailable in this runtime",{runtime:typeof globalThis.crypto});return e.randomUUID()}}function Ei(e){if(!e)return;let t;try{t=e.cache?.user}catch{t=void 0}if(null==t)try{t=e.get("user")}catch{t=void 0}return"string"==typeof t&&t.length>0?t:void 0}function Ni(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&pt(e.document)&&!pt(e)}function Oi(e){return JSON.parse(JSON.stringify(e))}function ki(e){if(null==e)return 0;let t;try{t=e.getTime()}catch{return 0}return Number.isFinite(t)?t:0}let Ai=class extends H{constructor(e){super(Gt),this.catalogue=e}get limits(){return{...ar,...sr.graph.workflows.limits??{}}}get allowAnonymousAccess(){return!0===sr.graph.workflows.allowAnonymousAccess}async saveDocument(e,t,...o){const{ctx:n,ctxArgs:r}=(await this.logCtx(o,"saveDocument",!0)).for(this.saveDocument);if(!pt(t))throw new A("Payload is not a canonical GraphWorkflowDocument: id and name must be strings and inputs, outputs, nodes and edges must be arrays");if(t.id!==e)throw new A(`Document id '${t.id}' does not match the workflow id '${e}' from the request path`);const i=await this.validateDocument(t,n);if(!i.valid)throw new po(i.issues);const a=Ei(n),s=await this.readExistingForWrite(e,r);s&&this.assertWriteOwnership(e,s,a);const d=new Date;if(s)return s.name=t.name,s.document=Oi(t),s.updatedAt=d,this.update(s,...r);const l=new Gt({workflowId:e,name:t.name,document:Oi(t),...a?{owner:a}:{},updatedAt:d});return this.create(l,...r)}async getDocument(e,...t){const{ctx:o,ctxArgs:n}=(await this.logCtx(t,"getDocument",!0)).for(this.getDocument);let r;try{r=await this.read(e,...n)}catch{r=null}if(!r)throw new _(`No graph workflow found for workflowId '${e}'`);if(this.assertOwnership(e,r,Ei(o)),r.document)return Oi(r.document);throw new _(`Graph workflow '${e}' has no canonical document; legacy definition/state snapshots are no longer supported (DECAF-50 \xa74.26 R2-2)`)}async listWorkflows(...e){const{ctx:t,ctxArgs:o}=(await this.logCtx(e,"listWorkflows",!0)).for(this.listWorkflows),n=await this.listBy("workflowId",K.ASC,...o),r=Ei(t);return n.filter(e=>di(e,r,{allowAnonymousAccess:this.allowAnonymousAccess})).sort((e,t)=>ki(t.updatedAt)-ki(e.updatedAt))}async assertAccess(e,...t){const{ctx:o,ctxArgs:n}=(await this.logCtx(t,"assertAccess",!0)).for(this.assertAccess);let r;try{r=await this.read(e,...n)}catch{r=null}if(!r)throw new _(`No graph workflow found for workflowId '${e}'`);return this.assertOwnership(e,r,Ei(o)),r}async validateDocument(e,...t){const{ctx:o}=(await this.logCtx(t,"validateDocument",!0)).for(this.validateDocument);return await ai(e,{limits:this.limits,...this.catalogue?{catalogue:this.catalogue}:{}},o)}async saveSnapshot(e,t,...o){const{ctx:n,ctxArgs:r}=(await this.logCtx(o,"saveSnapshot",!0)).for(this.saveSnapshot);if(!Ue(t))throw new A("Workflow snapshot payload must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys and unsafe prototype keys (__proto__/prototype/constructor) are rejected");if(!Ni(t))throw new A("Workflow snapshots must wrap a canonical GraphWorkflowDocument ({ document, editor?, metadata? }): legacy definition/state snapshots are no longer accepted; save canonical documents via PUT /graph/workflows/{workflowId}");const i=Ei(n),a=await this.readExistingForWrite(e,r);a&&this.assertWriteOwnership(e,a,i);const s=new Date;if(a)return a.snapshot=t,await this.applyCanonicalWrapper(a,t,n),a.updatedAt=s,this.update(a,...r);const d=new Gt({workflowId:e,snapshot:t,...i?{owner:i}:{},updatedAt:s});return await this.applyCanonicalWrapper(d,t,n),this.create(d,...r)}async loadSnapshot(e,...t){const{ctx:o,ctxArgs:n}=(await this.logCtx(t,"loadSnapshot",!0)).for(this.loadSnapshot);try{const t=await this.read(e,...n);return this.assertOwnership(e,t,Ei(o)),t}catch{return null}}async readExistingForWrite(e,t){try{return await this.read(e,...t)}catch(e){if(e instanceof _)return null;throw e}}assertOwnership(e,t,o){ui(t??null,o??null,{allowAnonymousAccess:this.allowAnonymousAccess,resourceKind:"Graph workflow",resourceId:e})}assertWriteOwnership(e,t,o){ci(t??null,o??null,{resourceKind:"Graph workflow",resourceId:e})}async applyCanonicalWrapper(e,t,o){if(!Ni(t))return;if(t.document.id!==e.workflowId)throw new A(`Document id '${t.document.id}' does not match the workflow id '${e.workflowId}' from the request path`);const n=await ai(t.document,{limits:this.limits,...this.catalogue?{catalogue:this.catalogue}:{}},o);if(!n.valid)throw new po(n.issues);e.document=Oi(t.document),e.name=t.document.name}};Ai=S([F(Gt),D("design:paramtypes",[Function])],Ai);let xi=class extends H{constructor(){super(jt)}async saveRun(e,...t){const{ctxArgs:o}=(await this.logCtx(t,"saveRun",!0)).for(this.saveRun),n=gi(e);let r;try{r=await super.read(e.runId,...o)}catch{r=null}if(r)return r.workflowId=n.workflowId,r.owner=n.owner,r.status=n.status,r.documentFingerprint=n.documentFingerprint,r.result=n.result,r.error=n.error,r.startedAt=n.startedAt,r.finishedAt=n.finishedAt,void await this.update(r,...o);await this.create(n,...o)}async readRun(e,...t){const{ctxArgs:o}=(await this.logCtx(t,"readRun",!0)).for(this.readRun);try{return(e=>{const t=e.result;return{runId:e.runId,workflowId:e.workflowId,ownerUser:e.owner??null,status:(o=e.status,"string"==typeof o&&["queued","validating","running","succeeded","failed","cancelled"].includes(o)?e.status:"failed"),createdAt:e.createdAt.toISOString(),...e.startedAt?{startedAt:e.startedAt.toISOString()}:{},...e.finishedAt?{finishedAt:e.finishedAt.toISOString()}:{},...t?{result:t}:{},...e.error?{error:e.error}:{},...e.documentFingerprint?{documentFingerprint:e.documentFingerprint}:{}};var o})(await super.read(e,...o))}catch{return null}}async listRuns(e,...t){const{ctxArgs:o}=(await this.logCtx(t,"listRuns",!0)).for(this.listRuns);return await this.findBy("workflowId",e,...o)}};xi=S([F(jt),D("design:paramtypes",[])],xi);class _i{map(e){const t={};for(const[o,n]of Object.entries(e.nodeResults))t[o]={status:n.status,startedAt:n.startedAt?.toISOString(),finishedAt:n.finishedAt?.toISOString(),error:n.error,outputs:n.outputs,fromCache:n.fromCache,pinned:n.pinned};const o={};for(const t of e.events)t.edgeId&&"edge.valueRouted"===t.type&&(o[t.edgeId]={status:se.SUCCEEDED,lastValue:t.payload?.value,updatedAt:t.timestamp.toISOString()});const n=[...e.events];return{runId:e.runId,status:e.status,nodes:t,edges:o,outputs:e.outputs,events:n}}}export{Or as AgentNode,er as BreakFlowNode,wr as ChatTriggerNode,pr as CodeInputSchema,hr as CodeNode,jo as ConditionExpressionEvaluator,ar as DEFAULT_GRAPH_WORKFLOW_DOCUMENT_LIMITS,Nn as DEFAULT_GRAPH_WORKFLOW_VALIDATION_LIMITS,cn as DEFAULT_PINNING_METADATA,fr as DelayFlowNode,or as ErrorBoundaryFlowNode,br as EventTriggerNode,vr as FormTriggerNode,kr as GRAPH_AGENT_NODES,Kr as GRAPH_BOUNDARY_NODES,Vr as GRAPH_BUILT_IN_NODE_CLASSES_BY_KIND,Gr as GRAPH_BUILT_IN_NODE_MANIFESTS,Fr as GRAPH_BUILT_IN_NODE_MANIFESTS_BY_KIND,ur as GRAPH_CODE_DEFAULT_LANGUAGE,dr as GRAPH_CODE_DEFAULT_TIMEOUT_MS,cr as GRAPH_CODE_LANGUAGES,Xt as GRAPH_CODE_MAX_TIMEOUT_MS,Ht as GRAPH_DEFAULT_CONCURRENCY,Vt as GRAPH_DEFAULT_MAX_FOREACH_ITERATIONS,Kt as GRAPH_DEFAULT_MAX_LOOP_ITERATIONS,On as GRAPH_DOCUMENT_FORBIDDEN_FIELD_KEYS,Wr as GRAPH_FLOW_CONTROL_NODES,qt as GRAPH_LOCAL_EXECUTION_BACKEND,eo as GRAPH_LOOP_KIND,Hr as GRAPH_LOOP_NODES,Jt as GRAPH_MAX_FOREACH_ITERATIONS,zt as GRAPH_MAX_LOOP_ITERATIONS,Yt as GRAPH_PINNING_METADATA_KEY,Zo as GRAPH_PLAIN_SECRET_KEYS,Br as GRAPH_TRIGGER_NODES,qr as GRAPH_UTILITY_NODES,Wt as GRAPH_WORKFLOW_BOUNDARY,Zr as GRAPH_WORKFLOW_FORBIDDEN_FIELD_KEYS,So as GraphAuthValidator,co as GraphBreakSignal,Sr as GraphConditionEvaluator,Zt as GraphConditionType,wn as GraphConnectionPolicyValidator,In as GraphConnectionValidationError,En as GraphCredentialAuthorizationError,bn as GraphCredentialReferenceValidator,oo as GraphCycleError,vn as GraphDocumentValidationError,yn as GraphEdgeInstanceValidator,To as GraphEngineEventSink,sr as GraphEnvironment,Mo as GraphExecutionBackendRegistry,Ro as GraphExecutionContext,Pn as GraphExecutionEngine,to as GraphExecutionError,ho as GraphExecutionEventEmitter,fo as GraphExecutionEventFactory,$o as GraphExecutionFrame,_n as GraphExecutionPlanner,_i as GraphExecutionSnapshotMapper,_r as GraphForeachLoopNode,no as GraphInputError,Rr as GraphInputValueNode,si as GraphLoopExecutionContext,ro as GraphLoopLimitError,Zn as GraphNode,Vn as GraphNodeCatalogue,zn as GraphNodeExecutorRegistry,Jn as GraphNodeExecutorResolver,gn as GraphNodeInstanceValidator,Wn as GraphNodeManifestResolver,Ln as GraphNodeMethodNotFoundError,Mn as GraphNodeMethodRegistry,Tn as GraphNodeNotFoundError,Cn as GraphNodeRegistrationError,$r as GraphOutputValueNode,en as GraphParameterValidator,hn as GraphPinningDependencyResolver,io as GraphPinningError,pn as GraphPinningPolicy,ln as GraphPinningService,Qt as GraphPinningStrategy,ao as GraphPortError,Yr as GraphPortSchemaResolver,uo as GraphRunCancelledError,wi as GraphRunEventPublisher,bi as GraphRunExecutor,xi as GraphRunModelService,Ii as GraphRunService,so as GraphStoreError,dn as GraphTopology,lo as GraphTopologyError,Dr as GraphUntilLoopNode,tn as GraphValueModel,an as GraphValueRepository,Qr as GraphValueValidator,Pr as GraphWhileLoopNode,po as GraphWorkflowDocumentRejectedError,xn as GraphWorkflowDocumentValidator,Ai as GraphWorkflowService,nr as HumanApprovalFlowNode,rr as IfFlowNode,fi as InMemoryGraphRunEventStore,yi as InMemoryGraphRunStore,$n as IsolatedVmCodeSandboxEvaluator,fn as LocalGraphExecutionBackend,gr as LogFlowNode,Ir as ManualTriggerNode,mr as MapNode,Er as ScheduleTriggerNode,ir as SwitchFlowNode,yr as UtilityLogNode,Nr as WebhookTriggerNode,ui as assertGraphResourceOwnership,ci as assertGraphResourceWriteOwnership,Co as buildGraphExecutionResult,Jr as builtInGraphNodeRegistrations,di as canAccessGraphResource,li as canAccessGraphResourcePayload,Jo as checkGraphValueAgainstSchema,lr as clampGraphCodeTimeoutMs,mn as collectLooseNodeIssues,mo as composeGraphNamespace,sn as createGraphValueRepository,Yn as declaredGraphNodeMethods,go as decomposeGraphNamespace,xo as decomposeGraphNamespaces,Xn as defineGraphNode,Vo as detectGraphCodeModeSurfaces,Fo as evaluateCodeCondition,Wo as evaluateCondition,Bo as evaluateConditionSync,Io as findMalformedGraphNamespaces,vo as findUngrantedGraphNamespaces,ko as graphAuthDataFromRecord,Ao as graphAuthDataOf,zo as graphDocumentHasCodeMode,bo as graphNamespaceCovers,wo as graphNamespacePartsOf,Qn as graphNodeConfig,Eo as graphRolesFromNamespaces,hi as graphRunDocumentFingerprint,Ei as graphWorkflowOwnerOf,Go as isCodeCondition,Uo as isConditionExpression,Yo as isGraphCredentialReferenceLike,yo as isGraphNamespaceCacheEntryValid,kn as isGraphResolvedWorkflow,un as isPinnable,_o as mergeGraphAuthData,Xr as registerBuiltInGraphNodes,Lo as resolveGraphBackendCapabilities,Fn as resolveGraphDynamicPorts,Bn as resolveGraphNodeManifest,on as serializeGraphValueKey,Dn as stripFacadeOwnedBackendConfig,ai as validateGraphWorkflowDocumentAtBoundary};
|
|
2
2
|
//# sourceMappingURL=as-graph.js.map
|