@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.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e,t;e=this,t=function(e,t,o,n,r,a,i,s,d,l,c,u,p){"use strict";function h(e){var t=Object.create(null);return e&&Object.keys(e).forEach(o=>{if("default"!==o){var n=Object.getOwnPropertyDescriptor(e,o);Object.defineProperty(t,o,n.get?n:{enumerable:!0,get:()=>e[o]})}}),t.default=e,Object.freeze(t)}var f,g,m=h(l),y=h(c),w=h(u);r.ValidationKeys.REQUIRED,r.ValidationKeys.MIN,r.ValidationKeys.MIN_LENGTH,r.ValidationKeys.MAX,r.ValidationKeys.MAX_LENGTH,r.ValidationKeys.PATTERN,r.ValidationKeys.URL,r.ValidationKeys.STEP,r.ValidationKeys.DATE,r.ValidationKeys.EMAIL,r.ValidationKeys.PASSWORD,r.ValidationKeys.EQUALS,r.ValidationKeys.DIFF,r.ValidationKeys.LESS_THAN,r.ValidationKeys.LESS_THAN_OR_EQUAL,r.ValidationKeys.GREATER_THAN,r.ValidationKeys.GREATER_THAN_OR_EQUAL,(e=>{e.GRAPH="graph",e.NODE="graph.node",e.EDGE="graph.edge",e.PORT="graph.port",e.STATE="graph.state"})(f||(f={})),(e=>{e.INPUT="input",e.OUTPUT="output",e.CONNECTION="connection"})(g||(g={}));const _={};function b(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 v(e,t){_[e]=t}function N(e,t,o){const n=t?_[t]:void 0;return n?.color?n.color:e||"#64748b"}function I(e,t,o){const n=t?_[t]:void 0;return n?.icon?n.icon:e||"ti-pointer"}const E=["skip","passThroughFirstInput","emitDefaults"];function O(e){return E.includes(e)}var A,x,k,D;(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"})(A||(A={})),(e=>{e.IDLE="idle",e.RUNNING="running",e.BLOCKED="blocked",e.SUCCEEDED="succeeded",e.FAILED="failed",e.SKIPPED="skipped"})(x||(x={})),(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"})(k||(k={})),(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"})(D||(D={}));const S={maxRequestBytes:4e6,maxConcurrentRuns:32,maxEventsPerRun:1e4,maxEventPayloadBytes:256e3,executionTimeoutMs:6e5,eventReplayWindowMs:3e5},P=[D.WORKFLOW_COMPLETED,D.WORKFLOW_FAILED,D.WORKFLOW_CANCELLED];function R(e){return P.includes(e)}function C(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}function T(e){const t=n.Metadata.constr(e);if("function"==typeof t)return t;const o=e.constructor;return"function"==typeof o?o:e}function $(e){if(null!=e)return"string"==typeof e?e:e+""}function G(e,t,o){return $(e?.props?.label??e?.props?.name)??$(t?.name)??o??""}function L(e,t,o){const a=V(e,t);if(a?.model&&"function"==typeof a.model&&r.Model.isModel(a.model))return a.model;const i=n.Metadata.type(e,t);if("function"==typeof i&&r.Model.isModel(i))return i;const s=n.Metadata.getPropDesignTypes?.(e,t)?.designTypes||[];for(const e of s)if("function"==typeof e&&r.Model.isModel(e))return e;const d=o?.[r.ValidationKeys.TYPE]?.customTypes||[];for(const e of d)if("function"==typeof e&&r.Model.isModel(e))return e}function M(e,t){const o=[t,e.path??e.property].filter(Boolean).join(".");return{...e,path:o,children:e.children?.map(e=>M(e,o))}}function F(e){const t=T(e);return n.Metadata.get(t,f.NODE)}function V(e,t){const o=T(e);return n.Metadata.get(o,n.Metadata.key(f.PORT,t+""))}function j(e,t,o,r=new Set){const a=V(e,t);if(!a?.schema)return;const i=L(e,t,n.Metadata.validationFor(e,t));if(!i)return;if(r.has(i))return[];const s=new Set(r);return s.add(e),s.add(i),q(i,s).filter(e=>e.direction===o)}function U(e,t,o=new Set){const a=V(e,t);if(!a)return;const i=n.Metadata.validationFor(e,t),s=L(e,t,i);if(a.schema&&s)return;const d=r.Model.uiElementOf(e,t)||void 0,l=r.Model.uiDecorationOf(e,t,"uiprop"),c=n.Metadata.type(e,t),u=$(a.type??i?.[r.ValidationKeys.TYPE]?.customTypes?.[0]?.name??d?.props?.type??l?.type??c?.name),p=(a.expand||s&&!o.has(s))&&s?(()=>{const n=new Set(o);return n.add(e),n.add(s),q(s,n).map(e=>M(e,t))})():void 0;return{property:t,path:t,direction:a.direction,name:t,label:G(d,l,t),type:u?.toLowerCase(),required:!!i?.[r.ValidationKeys.REQUIRED],hidden:!!r.Model.uiIsHidden(e,t),designType:c?.name,element:d,prop:l,validation:i,graph:a,connectionRules:a.connectionRules,composite:!!p?.length,children:p,model:s?.name}}function B(e){return q(T(e))}function q(e,t=new Set){const o=n.Metadata.properties(e)||[],r=[];for(const n of o){const o=n+"",a=V(e,o);if(a?.schema){const n=j(e,o,a.direction,t);if(n){r.push(...n);continue}}const i=U(e,o,t);i&&r.push(i)}return r}function W(e){return e.flatMap(e=>e.children&&e.children.length?W(e.children):[e])}function H(e){const t=T(e),o=r.Model.uiModelOf(t),a=F(t)||{},i=o?.tag||t.name,s=B(t),d=((e,t)=>{const o=t.portGroups||[],r=new Map(o.map(e=>[e.property,e])),a=[],i=n.Metadata.properties(e)||[];for(const t of i){const o=t+"",i=V(e,o);if(!i?.schema)continue;if(!L(e,o,n.Metadata.validationFor(e,o)))continue;const s=r.get(o);a.push(s?{...s,toggle:s.toggle??"all"}:{property:o,toggle:"all"})}for(const e of o)a.some(t=>t.property===e.property)||a.push(e);return a.length?a:void 0})(t,a),l=a.namespaces?.length?a.namespaces:(e=>{if(null==e)return[];let t,o=e;try{o=n.Metadata.constr(e)}catch{o=e}try{t=n.Metadata.get(o,"auth-namespace")}catch{t=void 0}return C(t)??[]})(t),c=l.length?l:void 0;return{name:t.name,tag:i,kind:a.kind||i,category:a.category,color:a.color,effectiveColor:N(a.color,a.category),group:a.group,height:a.height,icon:a.icon,effectiveIcon:I(a.icon,a.category),labels:a.labels||[],maxChildren:a.maxChildren,minWidth:a.minWidth,width:a.width,shape:a.shape,cornerRadius:a.cornerRadius,sizeRules:a.sizeRules,props:o?.props,ui:o,graph:a,ports:s,portGroups:d,namespaces:c}}const K=new Set,z=new Set;function J(e,t,r){return n.Decoration.for(f.NODE).define({decorator:(e,t,r)=>{const a={kind:t?.kind||e,...t};return t=>{const i=n.apply(o.uimodel(e,r),n.metadata(f.NODE,a))(t);var s;return s=t,K.add(s),i}},args:[e,t,r]}).apply()}function X(e,t){return n.Decoration.for(f.PORT).define({decorator:(e,t)=>(o,r)=>{const a={direction:e,...t};return n.apply(n.propMetadata(n.Metadata.key(f.PORT,r),a))(o,r)},args:[e,t]}).apply()}function Y(e){return X(g.INPUT,{...e,schema:!0})}function Q(e){return X(g.OUTPUT,{...e,schema:!0})}function Z(e){return X(g.CONNECTION,e)}o.RenderingEngine.prototype.renderAsNode=(e,t,...o)=>H(e),n.Metadata.nodes=(()=>[...K]).bind(n.Metadata),n.Metadata.workflows=(()=>[...z]).bind(n.Metadata);const ee=["__proto__","prototype","constructor"];function te(e){return ee.includes(e)}function oe(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function ne(e){return null===e||"string"==typeof e||"number"==typeof e&&Number.isFinite(e)||"boolean"==typeof e}function re(e){return!!ne(e)||(Array.isArray(e)?e.every(e=>re(e)):!!oe(e)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&!te(t)&&re(e[t])))}function ae(e){if(void 0===e)return!1;if("number"==typeof e)return Number.isFinite(e);if("function"==typeof e)return!1;if(re(e))return!0;if(Array.isArray(e))return e.every(e=>ae(e));if(oe(e)){const t=Reflect.ownKeys(e);for(const o of t){if("string"!=typeof o)return!1;if(te(o))return!1;if(!ae(e[o]))return!1}return!0}return!1}function ie(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>ie(e));const t={};for(const[o,n]of Object.entries(e))t[o]=ie(n);return t}const se={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"},de={date:"date",datetime:"date-time","date-time":"date-time",duration:"duration"};function le(e){return e?se[e.toLowerCase()]??"any":"any"}function ce(e,t){const o=e[t];if(o&&"object"==typeof o)return o.value}function ue(e,t){const o=ce(e,t);return"number"==typeof o&&Number.isFinite(o)?o:void 0}function pe(e,t,o){const n=e??{},a=(e=>{const t=ce(e,r.ValidationKeys.ENUM);if(Array.isArray(t)&&t.every(ne))return t})(n);if(a)return{type:"enum",values:a};const i=(e=>{const t=e[r.ValidationKeys.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(le(e)){case"string":{const t=(e=>{if(e)return de[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=ue(t,r.ValidationKeys.MIN),a=ue(t,r.ValidationKeys.MAX);return void 0!==n&&(o.min=n),void 0!==a&&(o.max=a),o}case"boolean":return{type:"boolean"};case"array":return((e,t)=>{const o={type:"array",items:he(e,t)},n=ue(e,r.ValidationKeys.MIN),a=ue(e,r.ValidationKeys.MAX);return void 0!==n&&(o.minItems=n),void 0!==a&&(o.maxItems=a),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 he(e,t){if((e=>{const t=e[r.ValidationKeys.LIST];return!!t?.clazz?.length})(e))return{type:"model",name:fe(e)};const o=ce(e,r.ValidationKeys.TYPE);if("string"==typeof o){const e=le(o);return"model"===e?{type:"model",name:o}:{type:e}}if(t&&"array"!==t){const e=le(t);return"model"===e?{type:"model",name:t}:{type:e}}return{type:"any"}}function fe(e){const t=e[r.ValidationKeys.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 ge(e){return"workflow"===e.scope}function me(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 we(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&&re(t)}return"expression"===t&&2===Object.keys(e).length&&"string"==typeof e.expression}const _e=["any","string","number","boolean","array","object","enum","model"];function be(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&(e=>_e.includes(e))(e.type)}function ve(e,t={seen:[]}){if(t.seen.includes(e))throw new a.ValidationError(`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.ValidationError("Document 'id' is required and must be a non-empty string");if("string"!=typeof e.name||!e.name)throw new a.ValidationError("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.ValidationError("Workflow port 'id' is required and must be a non-empty string");if(o.has(t.id))throw new a.ValidationError(`Workflow port '${t.id}' is declared more than once; workflow port ids must be unique`);if(void 0!==t.schema&&!be(t.schema))throw new a.ValidationError(`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)Ne(t,r);for(const t of e.nodes)t.loop&&Ie(t,t.loop,n),t.errorBoundary&&Ee(t,t.errorBoundary,n);const i=new Set;for(const t of e.edges)Ae(t,i);for(const t of e.edges)xe(t.source,0,o,r,`Edge '${t.id}' source`),xe(t.target,0,o,r,`Edge '${t.id}' target`);if(void 0!==e.settings&&!ae(e.settings))throw new a.ValidationError("Document settings must be JSON-safe (a map of JSON-safe values)");if(void 0!==e.metadata&&!ae(e.metadata))throw new a.ValidationError("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&&!ae(e.ui))throw new a.ValidationError("Document ui must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed")}function Ne(e,t){if("string"!=typeof e.id||!e.id)throw new a.ValidationError("Node 'id' is required and must be a non-empty string");if(t.has(e.id))throw new a.ValidationError(`Node id '${e.id}' is declared more than once; node ids must be unique`);if("string"!=typeof e.kind||!e.kind)throw new a.ValidationError(`Node '${e.id}' must declare a non-empty string 'kind'`);if(void 0===e.parameters||null===e.parameters)throw new a.ValidationError(`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 a.ValidationError(`Node '${e.id}' input binding key '${t}' is not allowed (unsafe prototype-pollutant key)`);if(!we(o))throw new a.ValidationError(`Node '${e.id}' input binding for '${t}' must be a valid GraphInputBinding (edge, literal, or expression)`);if("literal"===o.mode&&!ae(o.value))throw new a.ValidationError(`Node '${e.id}' literal binding for '${t}' must contain JSON-safe values`);if("expression"===o.mode&&!o.expression)throw new a.ValidationError(`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 a.ValidationError(`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.ValidationError(`Node '${e.id}' output binding for '${t}' must be an object with enabled and alias settings`)}if(!ae(e.parameters))throw new a.ValidationError(`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.ValidationError(`Node '${e.id}' state must be an object when present`);if(!ae(e.state))throw new a.ValidationError(`Node '${e.id}' state must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed`)}}function Ie(e,t,o){if(!t.body||"object"!=typeof t.body)throw new a.ValidationError(`Node '${e.id}' loop configuration requires a body document`);if(ve(t.body,o),!(void 0===t.maxIterations||Number.isFinite(t.maxIterations)&&t.maxIterations>0))throw new a.ValidationError(`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.ValidationError(`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.ValidationError(`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 a.ValidationError(`Node '${e.id}' loop mapping key '${t}' is not allowed (unsafe prototype-pollutant key)`);Oe(n,e.id,t)}}function Ee(e,t,o){if(!t.try||"object"!=typeof t.try)throw new a.ValidationError(`Node '${e.id}' error-boundary configuration requires a try body document`);ve(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.ValidationError(`Node '${e.id}' error-boundary ${n} body must be a document`);ve(r,o)}}function Oe(e,t,o){if(!e||"object"!=typeof e)throw new a.ValidationError(`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.ValidationError(`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.ValidationError(`Node '${t}' loop mapping '${o}' referencing a node must reference a node id and a port`);break;case"literal":if(!ae(e.value))throw new a.ValidationError(`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.ValidationError(`Node '${t}' loop mapping '${o}' expression references must be non-empty expressions`);break;default:throw new a.ValidationError(`Node '${t}' loop mapping '${o}' must use a workflow, node, literal, or expression reference source`)}}function Ae(e,t){if("string"!=typeof e.id||!e.id)throw new a.ValidationError("Edge 'id' is required and must be a non-empty string");if(t.has(e.id))throw new a.ValidationError(`Edge id '${e.id}' is declared more than once; edge ids must be unique`);if(!ye(e.source))throw new a.ValidationError(`Edge '${e.id}' source endpoint is not a valid GraphEndpoint`);if(!ye(e.target))throw new a.ValidationError(`Edge '${e.id}' target endpoint is not a valid GraphEndpoint`);if("data"!==e.type&&"connection"!==e.type)throw new a.ValidationError(`Edge '${e.id}' type '${e.type+""}' is not a valid edge type (data or connection are allowed)`);if(t.add(e.id),!ae(e))throw new a.ValidationError(`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 xe(e,t,o,n,r){if(ge(e)){if(!o.has(e.port))throw new a.ValidationError(`${r} references workflow port '${e.port}' which is not declared on the document`)}else if(me(e)){if(!n.has(e.nodeId))throw new a.ValidationError(`${r} references node '${e.nodeId}' which is not part of the document`);if("string"!=typeof e.port||!e.port)throw new a.ValidationError(r+" node endpoints must reference a non-empty port identifier")}}const ke=["expression","template"],De=["javascript","typescript","json","text"];function Se(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return!(!(e=>ke.includes(e))(t.mode)||"string"!=typeof t.expression||!t.expression||void 0!==t.language&&!(e=>De.includes(e))(t.language)||void 0!==t.metadata&&!re(t.metadata))}function Pe(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 Re(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 Ce=["trigger","loop","branching","stateful","retryable","cancellable","parallel","resource"];function Te(e){return Ce.includes(e)}function $e(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.ValidationError("Graph node manifest does not conform to the required shape");if(!ae(e))throw new a.ValidationError("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 Ge=["loadOptions","listSearch","resourceLocator","resourceMapping","validateParameter","action"];function Le(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.name&&(e=>Ge.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 Me(e){const t=e.element?.props?.value,o=t??e.prop?.value??e.validation?.defaultValue;if(void 0!==o&&"function"!=typeof o&&ae(o))try{return JSON.parse(JSON.stringify(o))}catch{return}}function Fe(e){if(e.type&&e.type in de)return{type:"string",format:de[e.type]};const t=(e=>{for(const t of[e.graph?.type,e.element?.props?.type,e.prop?.type])if("string"==typeof t&&"any"!==le(t))return t})(e);return t?pe((e=>{if(!e)return;const t=Object.entries(e).filter(([e])=>e!==r.ValidationKeys.TYPE);return Object.fromEntries(t)})(e.validation),t):pe(e.validation,e.type,e.model)}function Ve(e){const t={};for(const[o,n]of Object.entries(e.graph?.metadata??{}))ae(n)&&(t[o]=JSON.parse(JSON.stringify(n)));return Object.keys(t).length?t:void 0}function je(e){switch(e){case"output":return"output";case"connection":return"connection";default:return"input"}}function Ue(e){const t=e.graph?.handle;return"connection"!==e.direction&&"string"==typeof t&&t?t:e.path??e.property}function Be(e,t){const o={id:Ue(e),label:e.label,direction:je(e.direction),schema:Fe(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 a=Ze(e.graph?.connectionRules)??t;a&&(o.connectionPolicy=a);const i=(e=>{const t=e.element;if(!t||!ae(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)?ie(n):{}}})(e);i&&(o.element=i);const s=Ve(e);return s&&(o.metadata=s),o}function qe(e){const t={type:"string",id:Ue(e),label:e.label,required:e.required};if(e.hidden)return((e,t)=>{const o={...t,type:"hidden"},n=Me(e);return void 0!==n&&(o.defaultValue=n),We(o)})(e,t);const o=Me(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=Ve(e);if(r&&(t.metadata=r),(e=>{const t=ze(e);return"code"===t||"code-editor"===t})(e))return We({...t,type:"code",language:Ye(e)});const a=Fe(e);switch(a.type){case"number":{const o={...t,type:"number",integer:a.integer,min:a.min,max:a.max},n=Ke(e.validation?.step);return void 0!==n&&(o.step=n),We(o)}case"boolean":return We({...t,type:"boolean"});case"enum":return We({...t,type:"options",options:a.values.map(e=>({value:e,label:e+""}))});case"array":{const e={...t,type:"collection"};return void 0!==a.maxItems&&(e.maxItems=a.maxItems),We(e)}case"object":case"model":return We({...t,type:"object"});default:return We({...t,type:"string",multiline:!!Je(e)||void 0,pattern:He(e.validation?.pattern),minLength:Ke(e.validation?.minlength),maxLength:Ke(e.validation?.maxlength)})}}function We(e){const t=e;for(const e of Object.keys(t))void 0===t[e]&&delete t[e];return e}function He(e){const t=e?.value;return"string"==typeof t?t:void 0}function Ke(e){const t=e?.value;return"number"==typeof t&&Number.isFinite(t)?t:void 0}function ze(e){const t=e.element?.tag;return"string"==typeof t&&t?t:void 0}function Je(e){return"textarea"===ze(e)||"textarea"===(e=>{const t=e.element?.props?.type;return"string"==typeof t?t:void 0})(e)}const Xe=["javascript","typescript","json","text"];function Ye(e){const t=e.element?.props?.language;return"string"==typeof t&&Xe.includes(t)?t:"javascript"}function Qe(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 a=((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 a&&(o.icon=a),"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 Ze(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 a=t.maxConnections;return"number"==typeof a&&Number.isFinite(a)&&(o.maxConnections=a),Object.keys(o).length?o:void 0}function et(e,t={}){const o="function"==typeof e?e:e.constructor;if(!F(o))throw new a.ValidationError(`Node '${o?.name??e+""}' is not decorated with @node and cannot produce a manifest`);const n=H(o),r=W(B(o)),i=[],s=[],d=[],l=[],c=Ze(n.graph?.connectionRules);for(const e of r)("connection"===e.direction?d:"output"===e.direction?s:i).push(Be(e,c)),"input"===e.direction&&l.push(qe(e));const u={kind:t.kind??n.kind??n.name,display:Qe(n,t),inputs:i,outputs:s,parameters:l};return d.length&&(u.connections=d),n.namespaces?.length&&(u.namespaces=n.namespaces.slice()),$e(u),u}let tt=class extends s.BaseModel{constructor(e){super(e)}};i.__decorate([s.pk({type:String,generated:!1}),n.description("Unique graph run id"),o.uielement("ngx-decaf-crud-field",{label:"graph.run.id.label",readonly:!0}),i.__metadata("design:type",String)],tt.prototype,"runId",void 0),i.__decorate([s.column(),r.required(),s.index(),n.description("Workflow document id the run executes"),o.uilistprop("workflowId"),o.uielement("ngx-decaf-crud-field",{label:"graph.run.workflowId.label"}),i.__metadata("design:type",String)],tt.prototype,"workflowId",void 0),i.__decorate([s.column(),n.description("Owning user; absent for anonymous callers"),o.uielement("ngx-decaf-crud-field",{label:"graph.run.owner.label"}),i.__metadata("design:type",String)],tt.prototype,"owner",void 0),i.__decorate([s.column(),r.required(),r.type(String),s.index(),n.description("Current run lifecycle status"),o.uilistprop("status"),o.uielement("ngx-decaf-crud-field",{label:"graph.run.status.label",readonly:!0}),i.__metadata("design:type",String)],tt.prototype,"status",void 0),i.__decorate([s.column(),n.description("Fingerprint of the executed document"),o.uielement("ngx-decaf-crud-field",{label:"graph.run.fingerprint.label",readonly:!0}),i.__metadata("design:type",String)],tt.prototype,"documentFingerprint",void 0),i.__decorate([s.column(),n.prop(),n.description("Workflow input values keyed by input port id"),i.__metadata("design:type",Object)],tt.prototype,"inputs",void 0),i.__decorate([s.column(),n.prop(),n.description("Execution result, present on successful completion"),i.__metadata("design:type",Object)],tt.prototype,"result",void 0),i.__decorate([s.column(),n.prop(),n.description("Structured error payload, present on failure"),i.__metadata("design:type",Object)],tt.prototype,"error",void 0),i.__decorate([r.date(),s.column(),n.description("Run creation timestamp"),i.__metadata("design:type",Date)],tt.prototype,"createdAt",void 0),i.__decorate([r.date(),s.column(),n.description("Execution start timestamp, once it has started"),i.__metadata("design:type",Date)],tt.prototype,"startedAt",void 0),i.__decorate([r.date(),s.column(),n.description("Terminal-state timestamp, once the run has finished"),i.__metadata("design:type",Date)],tt.prototype,"finishedAt",void 0),tt=i.__decorate([o.uilistmodel("ngx-decaf-list-item",{icon:"ti-player-play"}),o.uimodel("ngx-decaf-crud-form"),n.description("Persistable graph run lifecycle record"),s.table("graph_run"),r.model(),i.__metadata("design:paramtypes",[Object])],tt);let ot=class extends s.BaseModel{constructor(e){super(e)}};i.__decorate([s.pk({type:String,generated:!1}),i.__metadata("design:type",String)],ot.prototype,"workflowId",void 0),i.__decorate([s.column(),i.__metadata("design:type",String)],ot.prototype,"name",void 0),i.__decorate([s.column(),i.__metadata("design:type",Object)],ot.prototype,"document",void 0),i.__decorate([s.column(),i.__metadata("design:type",String)],ot.prototype,"owner",void 0),i.__decorate([s.column(),i.__metadata("design:type",Object)],ot.prototype,"snapshot",void 0),ot=i.__decorate([s.table("graph_workflow"),r.model(),i.__metadata("design:paramtypes",[Object])],ot),v("Trigger",{color:"#3b82f6",icon:"ti-bolt"}),v("Flow Control",{color:"#f59e0b",icon:"ti-arrows-split-2"}),v("Utility",{color:"#0d9488",icon:"ti-tool"}),v("Loop",{color:"#eab308",icon:"ti-repeat"}),v("Workflow",{color:"#f97316",icon:"ti-sitemap"}),v("Pipeline",{color:"#0ea5e9",icon:"ti-git-merge"}),v("Node",{color:"#8b5cf6",icon:"ti-point-filled"}),v("Agent",{color:"#7c3aed",icon:"ti-robot"}),v("model",{color:"#3b82f6",icon:"ti-cpu"}),v("memory",{color:"#10b981",icon:"ti-database"}),v("workspace",{color:"#f59e0b",icon:"ti-folder"});const nt=new Set;function rt(e,t){return e.config[t]}function at(e){return Array.isArray(e)?e.map(e=>e+"").join(", "):e+""}(()=>{const e=[{key:k.NODE_ID,shouldInclude:e=>null!=rt(e,k.NODE_ID),render:e=>rt(e,k.NODE_ID)+""},{key:k.WORKFLOW_ID,shouldInclude:e=>null!=rt(e,k.WORKFLOW_ID),render:e=>rt(e,k.WORKFLOW_ID)+""},{key:k.RUN_ID,shouldInclude:e=>null!=rt(e,k.RUN_ID),render:e=>rt(e,k.RUN_ID)+""},{key:k.USER,shouldInclude:e=>null!=rt(e,k.USER),render:e=>rt(e,k.USER)+""},{key:k.ROLES,shouldInclude(e){const t=rt(e,k.ROLES);return Array.isArray(t)&&t.length>0},render:e=>at(rt(e,k.ROLES))},{key:k.NAMESPACES,shouldInclude(e){const t=rt(e,k.NAMESPACES);return Array.isArray(t)&&t.length>0},render:e=>at(rt(e,k.NAMESPACES))},{key:k.ORGANIZATION,shouldInclude:e=>null!=rt(e,k.ORGANIZATION),render:e=>rt(e,k.ORGANIZATION)+""},{key:k.IP,shouldInclude:e=>null!=rt(e,k.IP),render:e=>rt(e,k.IP)+""}];for(const o of e)nt.has(o.key)||(t.logParameterRegistry.register(o),nt.add(o.key))})();const it="$workflow",st=1e3,dt=1e4,lt=3e4;var ct,ut;e.GraphPinningStrategy=void 0,(ct=e.GraphPinningStrategy||(e.GraphPinningStrategy={})).MANUAL="manual",ct.AUTOMATIC="automatic",ct.DISABLED="disabled",e.GraphConditionType=void 0,(ut=e.GraphConditionType||(e.GraphConditionType={})).TRUTHY="truthy",ut.FALSY="falsy",ut.EQUALS="equals",ut.NOT_EQUALS="notEquals",ut.GREATER_THAN="greaterThan",ut.GREATER_THAN_OR_EQUAL="greaterThanOrEqual",ut.LESS_THAN="lessThan",ut.LESS_THAN_OR_EQUAL="lessThanOrEqual",ut.EXISTS="exists",ut.CUSTOM="custom";class pt extends a.InternalError{constructor(e,t="GRAPH_EXECUTION_ERROR",o){super(e,pt.name,500),this.graphCode=t,this.details=o,this.name=this.constructor.name}}class ht extends pt{constructor(e){super("Graph workflow contains an unsupported cycle","GRAPH_CYCLE_ERROR",e)}}class ft extends pt{constructor(e,t){super(e,"GRAPH_INPUT_ERROR",t)}}class gt extends pt{constructor(e,t){super(e,"GRAPH_LOOP_LIMIT_ERROR",t)}}class mt extends pt{constructor(e,t){super(e,"GRAPH_PINNING_ERROR",t)}}class yt extends pt{constructor(e,t){super(e,"GRAPH_STORE_ERROR",t)}}class wt extends pt{constructor(e,t){super(e,"GRAPH_TOPOLOGY_ERROR",t)}}class _t extends pt{constructor(e){super("Break signal","GRAPH_BREAK_SIGNAL",{value:e}),this.isBreakSignal=!0,this.name="GraphBreakSignal"}}class bt extends pt{constructor(e){super(`Graph run '${e}' was cancelled`,"GRAPH_RUN_CANCELLED",{runId:e}),this.name=bt.name}}class vt extends a.ValidationError{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=vt.name,this.issues=e}}class Nt{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 It{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 pt("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 Et(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(),a=o[1].split(",").map(e=>e.trim()).filter(e=>e.length>0);return n&&r&&0!==a.length?{organization:n,departments:a,role:r}:void 0}function Ot(e){return`${e.organization}.${e.departments.join(",")}.${e.role}`}function At(e){if(!e||"string"!=typeof e.namespace||!e.parts)return!1;const t=Et(e.namespace);return!!t&&Ot(t)===Ot(e.parts)}function xt(e,t){const o="string"==typeof e?e.trim():"";if(o){if(t)for(const e of t)if(e&&e.namespace===o&&At(e))return e.parts;return Et(o)}}function kt(e,t,o={},n){const r=xt(e,n),a=xt(t,n);return!(!r||!a)&&r.organization===a.organization&&r.role===a.role&&("exact"===(o.mode??"inherit")?r.departments.length===a.departments.length&&r.departments.every((e,t)=>e===a.departments[t]):r.departments.length<=a.departments.length&&r.departments.every((e,t)=>e===a.departments[t]))}function Dt(e,t,o={},n){return e.filter(e=>!t.some(t=>kt(t,e,o,n)))}function St(e){return e.filter(e=>void 0===Et(e))}function Pt(e,t){const o=new Set;for(const n of e){const e=xt(n,t);e&&o.add(e.role)}return[...o]}function Rt(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}function Ct(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 Tt(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 a=Rt(e.roles);a&&(t.roles=a);const i=Rt(e.namespaces);return i&&(t.namespaces=i,t.namespaceCache=Gt(i)),t}function $t(e){return e?Tt({user:Ct(e,"user"),organization:Ct(e,"organization"),ip:Ct(e,"ip"),roles:Ct(e,"roles"),namespaces:Ct(e,"namespaces")}):{}}function Gt(e){const t=[];for(const o of e){const e=Et(o);e&&t.push({namespace:o,parts:e})}return t}function Lt(...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??Gt(o.namespaces):void 0!==o.namespaceCache&&(t.namespaceCache=o.namespaceCache));return t}class Mt{constructor(e={}){this.options=e}get enabled(){return!0===this.options.enabled}validate(e,o,n,r){if(!this.enabled)return;const a=r??this.options.logger??t.Logging.for("GraphAuth"),i=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=C(e.namespaces),o=C(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 '${i}'`,s?.namespaces??[],n,s?.roles??[],a);for(const e of o.nodes)this.assertGranted(`node '${e.id}'`,e.manifest.namespaces??[],n,[],a)}assertGranted(e,t,o,n,r){const a=o.namespaces??[],i=Dt(t,a,this.options.match,o.namespaceCache),d=Pt(a,o.namespaceCache),l=n.filter(e=>!d.includes(e));if(0===i.length&&0===l.length)return;const c=[...new Set([...St(t),...St(a)])],u=[];throw i.length&&u.push("namespace(s) "+i.join(", ")),l.length&&u.push("role(s) "+l.join(", ")),r.warn(`Graph access denied for ${e} for user ${o.user??"anonymous"}: missing ${u.join(" and ")}${c.length?`; malformed namespace(s) ${c.join(", ")} failed closed`:""}`),new s.ForbiddenError(`Access to ${e} requires ${u.join(" and ")}`)}}class Ft{constructor(e){this.baseOptions=e,this.inner=t.Logging.for("GraphRun").for(this.attributeConfig(e))}attributeConfig(e){return{[k.NODE_ID]:e.nodeId,[k.WORKFLOW_ID]:e.workflowId,[k.RUN_ID]:e.runId,[k.USER]:e.user??null,[k.ROLES]:e.roles,[k.NAMESPACES]:e.namespaces,[k.ORGANIZATION]:e.organization,[k.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:D.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 Vt(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}class jt extends s.Context{constructor(e,t,o,n,r,a,i,s,d={},l,c,u){super(),this.runId=e,this.parentRunId=t,this.workflowId=o,this.document=n,this.node=r,this.manifest=a,this.path=i,this.emitFn=s,this.metadata=d,this.engine=l,this.abortSignal=c,this.limits=u;const p=Tt(d);this.accumulate({...p,operation:"execute"});const h="string"==typeof d?.user?d.user:null;this.runLogger=new Ft({runId:e,workflowId:o,nodeId:r.id,user:h,roles:Vt(d?.roles),namespaces:Vt(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 $t(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:D.NODE_OUTPUT,payload:e})}async log(e,t){await this.emit({type:D.NODE_OUTPUT,payload:{message:e,payload:t}})}}class Ut{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 Bt(e,t,o,n,r){const a=e.valueStore.getWorkflowValues(),i={};for(const[t,o]of e.nodeResults)i[t]=o;const s=[...e.events];return{runId:e.runId,workflowId:t.id||t.name,status:n,document:t,inputs:{...o},outputs:a,nodeResults:i,events:s,startedAt:e.startedAt,finishedAt:e.finishedAt,metadata:r}}class qt{constructor(e){this.catalogue=e}async resolveNodes(e,t,o,...n){const r=new Map;for(const[a,i]of e.entries()){const e=`nodes[${a}]`;if(this.catalogue.has(i.kind,...n))try{const e=await this.catalogue.resolveManifest(i.kind,i,o,...n),t=this.catalogue.getExecutor(i.kind,...n);r.set(i.id,{instance:i,manifest:e,executor:t})}catch(o){t.push({code:"kind.resolution-failed",path:e+".kind",message:`Node '${i.id}' kind '${i.kind}' failed to resolve: ${o.message}`,nodeId:i.id,details:{kind:i.kind}})}else t.push({code:"kind.unknown",path:e+".kind",message:`Node '${i.id}' references kind '${i.kind}' which is not registered in the backend catalogue`,nodeId:i.id,details:{kind:i.kind}})}return r}validateEffectivePorts(e,t,o,n){const r=!0===t.policies?.allowUndeclaredParameters,a=new Set(t.inputs.map(e=>e.id)),i=new Set(t.outputs.map(e=>e.id));for(const i of Object.keys(e.inputBindings??{}))r||a.has(i)||o.push({code:"binding.unknown-port",path:`${n}.inputBindings.${i}`,message:`Node '${e.id}' input binding '${i}' does not refer to an effective input port of kind '${t.kind}'`,nodeId:e.id,details:{effectiveInputs:[...a]}});for(const a of Object.keys(e.outputBindings??{}))r||i.has(a)||o.push({code:"binding.unknown-port",path:`${n}.outputBindings.${a}`,message:`Node '${e.id}' output binding '${a}' does not refer to an effective output port of kind '${t.kind}'`,nodeId:e.id,details:{effectiveOutputs:[...i]}})}}function Wt(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&&Wt(e,t,`${o}.nodes[${r.id}].loop.body`)}}function Ht(e,t){if(!t)return{valid:!0};switch(t.type){case"any":default:return{valid:!0};case"string":return"string"!=typeof e?Kt("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}:Kt("number");case"boolean":return"boolean"!=typeof e?Kt("boolean"):{valid:!0};case"array":if(!Array.isArray(e))return Kt("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=Ht(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 Kt(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=Ht(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 Kt(e){return{valid:!1,message:`expected a ${e} value`}}function zt(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 Jt=new Set(["loop"]),Xt=["secret","secrets","password","passwd","token","accessToken","refreshToken","apiKey","api_key","privateKey","credentials"];class Yt{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 a=!0===t.policies?.allowUndeclaredParameters,i=new Map(t.parameters.map(e=>[e.id,e]));for(const[r,s]of Object.entries(e.parameters??{})){const d=i.get(r);if(!d){a||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 a of t.parameters)void 0===(e.parameters??{})[a.id]&&(this.isParameterSatisfiedByInput(e,a.id,r)||(!0===a.required||(a.validation??[]).some(e=>"required"===e.kind))&&void 0===a.defaultValue&&o.push({code:"parameter.required-missing",path:`${n}.parameters.${a.id}`,message:`Node '${e.id}' is missing required parameter '${a.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(Se(e))return{valid:!0};switch(t.type){case"string":case"code":case"expression":return"string"!=typeof e?Kt("string"):{valid:!0};case"number":return"number"==typeof e&&Number.isFinite(e)?{valid:!0}:Kt("number");case"boolean":return"boolean"!=typeof e?Kt("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}:Kt("array");case"object":case"resourceLocator":return null===e||"object"!=typeof e||Array.isArray(e)?Kt("object"):{valid:!0};case"credential":return zt(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 a of Object.keys(e.metadata??{}))Jt.has(a)?o.push({code:"metadata.key-not-allowed",path:`${n}.metadata.${a}`,message:`Node '${e.id}' metadata key '${a}' is reserved and must not be set directly`,nodeId:e.id}):Array.isArray(r)&&!r.includes(a)&&o.push({code:"metadata.key-not-allowed",path:`${n}.metadata.${a}`,message:`Node '${e.id}' metadata key '${a}' 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||O(n)||t.push({code:"disabled.invalid-behavior",path:o+".metadata.disabledBehavior",message:`Node '${e.id}' disabled behavior '${n+""}' is not one of: ${E.join(", ")}`,nodeId:e.id})}validateBindingShapes(e,t,o,n){for(const[r,a]of Object.entries(e.inputBindings??{})){if("literal"===a.mode){const i=t.inputs.find(e=>e.id===r);if(i?.schema){const t=Ht(a.value,i.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"!==a.mode||"string"==typeof a.expression&&a.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,a={}){const i=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 i){const o=(e.inputBindings??{})[t];o&&"literal"===o.mode&&!0!==a.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&&(i.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(O(o))return o;const n=t?.disabledBehavior;return O(n)?n:"skip"}}class Qt{resolveEdges(e,t,o){const n=new Set(e.inputs.map(e=>e.id)),r=new Set(e.outputs.map(e=>e.id)),a=[];for(const[i,s]of(e.edges??[]).entries()){const e=`edges[${i}]`,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),a.push(c)}return a}resolveEndpoint(e,t,o,n,r,a,i){const s=e[t];return ge(s)?("source"===t?n.has(s.port):r.has(s.port))?{nodeId:it,port:s.port}:void a.push({code:"edge.unknown-port",path:`${i}.${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}}):me(s)?o.get(s.nodeId)?{nodeId:s.nodeId,port:s.port}:void a.push({code:"edge.unknown-node",path:`${i}.${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 a.push({code:"edge.invalid-endpoint",path:`${i}.${t}`,message:`Edge '${e.id}' ${t} endpoint is not a valid GraphEndpoint`,edgeId:e.id})}validateDirectionAndType(e,t,o,n,r,a){let i=!0;const s=t.nodeId===it?void 0:n.get(t.nodeId),d=o.nodeId===it?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,a),i=!1),!d||l(d)||this.hasPortDirection(d,o.port,"input")||(this.pushPortIssue(e,"target",o,d,r,a),i=!1);else{if(!s||!d)return r.push({code:"edge.boundary-routing",path:a,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:a,message:`Connection edge '${e.id}' endpoints must both be connection ports`,edgeId:e.id,details:{sourcePort:t.port,targetPort:o.port}}),!1}return i}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,a){const i="source"===t?"output":"input";r.push({code:"data"===e.type?"edge.invalid-direction":"edge.type-mismatch",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} port '${o.port}' on node '${o.nodeId}' is not an ${i} port of kind '${n.manifest.kind}'`,edgeId:e.id,nodeId:o.nodeId,details:{port:o.port,expected:i}})}}class Zt{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(":"),a=n.slice(0,o),i=n.slice(o+1),s=e.nodeById.get(a),d=s?.manifest.connections?.find(e=>e.id===i)?.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 '${i}' on node '${a}' accepts at most ${l} connection(s) but has ${r.length}`,nodeId:a,edgeId:r[r.length-1].id,details:{port:i,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),a=r?.manifest.kind;if(!o.allowedNodeKinds?.length||a&&o.allowedNodeKinds.includes(a)||n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source kind '${a??"unknown"}' is not in the allowed node kinds of target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{allowedNodeKinds:o.allowedNodeKinds}}),a&&o.blockedNodeKinds?.includes(a)&&n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source kind '${a}' 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 eo{constructor(e){this.authorizer=e}async validate(e,t,o,n){const r=this.collectReferences(e,t);for(const a of t.credentials??[]){const i=r.find(e=>void 0===e.credentialType||e.credentialType===a.type);if(i){if(this.checkType(i,a))o.push({code:"credential.type-mismatch",path:n,message:`Node '${e.id}' credential '${i.credentialId}' has type '${i.credentialType}' but kind '${t.kind}' requires '${a.type}'`,nodeId:e.id,details:{credentialType:i.credentialType??"",requiredType:a.type}});else if(this.authorizer){if(!await this.authorizer.hasCredential(i)){o.push({code:"credential.not-found",path:n,message:`Node '${e.id}' references credential '${i.credentialId}' which does not exist`,nodeId:e.id,details:{credentialId:i.credentialId}});continue}await this.authorizer.authorize(i,a)||o.push({code:"credential.unauthorized",path:n,message:`Node '${e.id}' is not authorized to use credential '${i.credentialId}'`,nodeId:e.id,details:{credentialId:i.credentialId}})}}else!1!==a.required&&o.push({code:"credential.missing",path:n,message:`Node '${e.id}' does not provide the required credential of type '${a.type}'`,nodeId:e.id,details:{credentialType:a.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];zt(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))zt(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(Xt);for(const[r,a]of Object.entries(e.parameters??{}))this.scanPlainSecretValue(a,[r],e,o+".parameters",n,t);for(const[r,a]of Object.entries(e.metadata??{}))this.scanPlainSecretValue(a,[r],e,o+".metadata",n,t)}scanPlainSecretValue(e,t,o,n,r,a,i=0){const s=t[t.length-1];if(r.has(s))a.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>i&&null!==e)if(Array.isArray(e))for(const s of e)this.scanPlainSecretValue(s,[...t,"[]"],o,n,r,a,i+1);else if("object"==typeof e)for(const[s,d]of Object.entries(e))this.scanPlainSecretValue(d,[...t,s],o,n,r,a,i+1)}}class to extends a.ValidationError{constructor(e,t=[]){super(e),this.issues=t,this.name=to.name}}class oo extends a.ValidationError{constructor(e,t){super(e),this.edgeId=t,this.name=oo.name}}class no extends s.AuthorizationError{constructor(e){super(e),this.name=no.name}}const ro={maxDocumentBytes:2e6,maxNestingDepth:10,maxNodes:500,maxEdges:1e3},ao=["node","definition","executor","execute","ports","component"];function io(e){if(!e||"object"!=typeof e)return!1;const t=e;return Pe(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 so(e,t){const o=[];for(const n of Object.keys(e))ao.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 lo{constructor(e){this.options=e,this.parameterValidator=new Yt,this.edgeValidator=new Qt,this.connectionPolicyValidator=new Zt,this.nodeValidator=new qt(e.catalogue),this.credentialValidator=new eo(e.credentialAuthorizer)}async validateOrThrow(e,...t){const o=await this.validate(e,0,...t);if(!o.valid||!o.resolved)throw new to(`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={...ro,...this.options.limits};if(!await this.validateStructure(e,r,t,n,...o))return{valid:!1,issues:n};const a=await this.nodeValidator.resolveNodes(e.nodes,n,this.options.resolutionContext,...o),i=e.nodes.filter(e=>a.has(e.id)).map(e=>a.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 i)this.parameterValidator.validate(e.instance,e.manifest,n,`nodes[${e.instance.id}]`,s.get(e.instance.id));for(const e of i)this.nodeValidator.validateEffectivePorts(e.instance,e.manifest,n,`nodes[${e.instance.id}]`);const d=this.edgeValidator.resolveEdges(e,a,n),l=new Map,c=new Map;for(const e of d){if(e.targetNodeId!==it){const t=l.get(e.targetNodeId)??[];t.push(e),l.set(e.targetNodeId,t)}if(e.sourceNodeId!==it){const t=c.get(e.sourceNodeId)??[];t.push(e),c.set(e.sourceNodeId,t)}}this.connectionPolicyValidator.validate({edges:d,nodeById:a},n),this.validateAcyclicity(i,d,e,n),Wt(e,n);for(const e of i)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 i)await this.credentialValidator.validate(e.instance,e.manifest,n,`nodes[${e.instance.id}]`);return this.validateCapabilities(i,n),n.length>0?{valid:!1,issues:n}:{valid:!0,issues:n,resolved:{document:e,nodes:i,edges:d,nodeById:a,incomingByNode:l,outgoingByNode:c}}}async validateStructure(e,t,o,n,...r){if(!Pe(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"}),!ae(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(...so(e,"$"));for(const t of[...e.inputs,...e.outputs])n.push(...so(t,"ports"));for(const t of e.nodes)n.push(...so(t,`nodes[${t.id}]`));for(const t of e.edges)n.push(...so(t,`edges[${t.id}]`));this.validateUniqueIds(e,n),this.validateLimits(e,t,o,n);try{ve(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,a]of[["input",e.inputs],["output",e.outputs]]){const e="input"===r?o:n;for(const o of a)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 a=new Set;for(const o of e.edges)a.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}):a.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[a,i]of e){if(!i)continue;const e=await this.validate(i,t+1,...n);for(const t of e.issues)o.push({...t,path:`nodes[${r.id}].${a}.${t.path}`,nodeId:t.nodeId??r.id})}}}validateAcyclicity(e,t,o,n){const r=new Set(e.map(e=>e.instance.id)),a=new Map(e.map(e=>[e.instance.id,0]));for(const e of t)r.has(e.sourceNodeId)&&a.has(e.targetNodeId)&&a.set(e.targetNodeId,(a.get(e.targetNodeId)??0)+1);const i=[...a.entries()].filter(([,e])=>0===e).map(([e])=>e),s=[];for(;i.length>0;){const e=i.shift();s.push(e);for(const o of t){if(o.sourceNodeId!==e)continue;if(!a.has(o.targetNodeId))continue;const t=(a.get(o.targetNodeId)??1)-1;a.set(o.targetNodeId,t),0===t&&i.push(o.targetNodeId)}}if(s.length!==a.size){const e=[...a.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===it&&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??[])Te(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}))}}}function co(e){return[e.namespace??"default",e.workflowId,e.nodeId,e.version??"default",e.fingerprint].join(":")}function uo(t){return new e.GraphValueModel({id:co(t.key),workflowId:t.key.workflowId,nodeId:t.key.nodeId,fingerprint:t.key.fingerprint,...void 0!==t.key.namespace?{namespace:t.key.namespace}:{},...void 0!==t.key.version?{version:t.key.version}:{},pinned:t.pinned,outputs:t.outputs,createdAt:new Date(t.createdAt),updatedAt:new Date(t.updatedAt),...t.expiresAt?{expiresAt:new Date(t.expiresAt)}:{},...t.metadata?{metadata:t.metadata}:{}})}function po(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}:{}}}function ho(t){return new(0,s.Repository.forModel(e.GraphValueModel,t.alias).constructor)(t)}e.GraphExecutionPlanner=class extends s.Service{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"}'`),!io(e))throw new wt("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),a=this.buildPlanEdges(e),i=this.buildIncomingMap(a),s=this.buildOutgoingMap(a),d=this.topologicalLayers(r,a);return{resolved:e,workflowId:e.document.id||e.document.name,nodes:r,edges:a,layers:d,incomingByNode:i,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===it)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===it)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!==it),n=new Set(o.map(e=>e.id)),r=t.filter(e=>n.has(e.sourceNodeId)&&n.has(e.targetNodeId)),a=new Map;for(const e of o)a.set(e.id,0);for(const e of r)a.set(e.targetNodeId,(a.get(e.targetNodeId)??0)+1);const i=[],s=new Set;let d=o.filter(e=>0===(a.get(e.id)??0)),l=0;for(;d.length>0;){const e={index:l++,nodes:d};i.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=(a.get(e.targetNodeId)??1)-1;if(a.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 ht({unplannedNodes:e,workflowId:o[0]?.manifest.kind})}return i}},e.GraphExecutionPlanner=i.__decorate([s.service(),i.__metadata("design:paramtypes",[])],e.GraphExecutionPlanner),e.GraphValueModel=class extends s.BaseModel{constructor(e){super(e)}},i.__decorate([s.pk({type:String,generated:!1}),i.__metadata("design:type",String)],e.GraphValueModel.prototype,"id",void 0),i.__decorate([s.column(),s.index(),i.__metadata("design:type",String)],e.GraphValueModel.prototype,"workflowId",void 0),i.__decorate([s.column(),s.index(),i.__metadata("design:type",String)],e.GraphValueModel.prototype,"nodeId",void 0),i.__decorate([s.column(),i.__metadata("design:type",String)],e.GraphValueModel.prototype,"fingerprint",void 0),i.__decorate([s.column(),i.__metadata("design:type",String)],e.GraphValueModel.prototype,"namespace",void 0),i.__decorate([s.column(),i.__metadata("design:type",String)],e.GraphValueModel.prototype,"version",void 0),i.__decorate([s.column(),i.__metadata("design:type",Boolean)],e.GraphValueModel.prototype,"pinned",void 0),i.__decorate([s.column(),i.__metadata("design:type",Object)],e.GraphValueModel.prototype,"outputs",void 0),i.__decorate([s.column(),i.__metadata("design:type",Date)],e.GraphValueModel.prototype,"createdAt",void 0),i.__decorate([s.column(),i.__metadata("design:type",Date)],e.GraphValueModel.prototype,"updatedAt",void 0),i.__decorate([s.column(),i.__metadata("design:type",Date)],e.GraphValueModel.prototype,"expiresAt",void 0),i.__decorate([s.column(),i.__metadata("design:type",Object)],e.GraphValueModel.prototype,"metadata",void 0),e.GraphValueModel=i.__decorate([s.table("graph_value"),r.model(),i.__metadata("design:paramtypes",[Object])],e.GraphValueModel),e.GraphValueRepository=class extends s.Repository{constructor(t){super(t,e.GraphValueModel,!0),this.runtimeValues=new Map}seedWorkflowInputs(e){this.runtimeValues.set(it,{...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(it)??{};o[e]=t,this.runtimeValues.set(it,o)}getWorkflowValues(){return{...this.runtimeValues.get(it)??{}}}snapshot(){return Object.fromEntries(this.runtimeValues.entries())}async readCached(e,...t){try{return po(await this.read(co(e),...t))}catch{return}}async writeCached(e,t,...o){const n=co(e);let r;try{r=await this.read(n,...o)}catch{r=void 0}r?await this.update(Object.assign(r,uo(t)),...o):await this.create(uo(t),...o)}async deleteCached(e,...t){try{await this.delete(co(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=>po(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}},e.GraphValueRepository=i.__decorate([s.repository(e.GraphValueModel,n.DefaultFlavour),i.__metadata("design:paramtypes",[Function])],e.GraphValueRepository);class fo{static upstreamNodes(e,t,o=!1){const n=new Set,r=[e];for(;r.length;){const e=r.pop(),a=t.get(e)??[];for(const e of a)!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(),a=t.get(e)??[];for(const e of a)!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 go{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 mt(`Node '${e}' not found in plan`);if(!this.policy.canPin(o))throw new mt(`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 mt(`Node '${o}' has no completed output to pin`);const a=r.inputs??{},i=this.dependencyFingerprints(t,o,e.result),s=this.createValueKey(e.document.id,n,a,i),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 a=this.createValueKey(e,t,o,n,r),i=await this.store.readCached(a);if(i&&i.pinned){if(i.expiresAt&&new Date(i.expiresAt)<new Date)return;return i}}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)},a=this.stableSerialize(r);return this.simpleHash(a)}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=a=>{if(n.has(a))return;n.add(a);const i=fo.upstreamNodes(a,e.incomingByNode,!1);for(const e of i)t.has(e)&&r(e);o.push(a)};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 a=o.nodeResults[t],i=a?.inputs??{},s=this.dependencyFingerprints(e,t,o);r[t]=this.computeFingerprint(e.workflowId,n,i,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 mo={enabled:!0,strategy:"manual",includeDependencies:!0};function yo(e){return!0===e?.enabled&&"disabled"!==e.strategy}class wo{canPin(e){return yo(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?{...mo,...t}:{...mo,enabled:!1}}}class _o{getDependencies(e,t){return fo.upstreamNodes(t,e.incomingByNode,!1)}getPinSet(e,t){const o=this.getDependencies(e,t);return o.add(t),o}}class bo extends s.ClientBasedService{constructor(){super()}async initialize(...t){const o=t[0];if(!o||"object"!=typeof o||!o.registry)return this._config=void 0,this._client=void 0,{config:void 0,client:void 0};const n=o.catalogue??o.registry.catalog,r=o.valueAdapter??s.Adapter.current;if(!r)throw new pt("GraphExecutionEngine requires a Decaf adapter for cached/pinned values: pass `valueAdapter` or configure one via `Adapter.setCurrent(...)`","GRAPH_VALUE_ADAPTER_MISSING");const a={registry:o.registry,catalogue:n,planner:o.planner??new e.GraphExecutionPlanner,valueAdapter:r,eventEmitter:o.eventEmitter??new Nt,documentValidator:o.documentValidator??new lo({catalogue:n,limits:o.documentLimits,credentialAuthorizer:o.credentialAuthorizer}),authValidator:new Mt({enabled:!0===o.authEnabled,...o.authMatch?{match:o.authMatch}:{}}),...o.codeSandboxEvaluator?{codeSandboxEvaluator:o.codeSandboxEvaluator}:{}};return this._config=o,this._client=a,await(o.onEngineCreated?.(this)),{config:o,client:a}}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:a}=(await this.logCtx(n,"execute",!0)).for(this.execute);r.debug(`Executing workflow '${e.id||e.name}'`);const i=this.mergeOptions(o);this.assertNotAborted(i);const s=Lt($t(a),i.auth);i.auth=s,i.metadata={...i.metadata??{},...s};const d=i.runId??this.generateRunId(),l=i.path??[],c=new It,u=ho(this.valueAdapter);u.seedWorkflowInputs(this.withWorkflowInputDefaults(e,t));const p=async t=>{await this.emitEvent(m,{type:t.type??D.NODE_OUTPUT,runId:d,parentRunId:i.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:i.parentRunId,workflowId:e.id||e.name,path:l,...t});await this.emitter.updateObservers(o)};await h({type:D.VALIDATION_STARTED,status:A.PLANNING});const f=await this.documentValidator.validate(e,0,a);if(!f.valid||!f.resolved)throw await h({type:D.VALIDATION_FAILED,status:A.FAILED,payload:{issues:f.issues}}),new to(`Graph workflow document '${e.id}' failed validation with ${f.issues.length} issue(s)`,f.issues);await h({type:D.VALIDATION_COMPLETED,status:A.PLANNING,payload:{issues:f.issues.length}}),this.assertNotAborted(i);const g=await this.planner.plan(f.resolved);this.client.authValidator.validate(e,g,s,r),r.debug(`Authorized workflow '${e.id||e.name}' for user ${s.user??"anonymous"}`);const m=new Ut(d,g,u,c);await this.emitEvent(m,{type:D.WORKFLOW_STARTED,runId:d,parentRunId:i.parentRunId,workflowId:g.workflowId,path:l,status:A.RUNNING,payload:{inputs:t}}),await this.emitEvent(m,{type:D.WORKFLOW_PLANNED,runId:d,parentRunId:i.parentRunId,workflowId:g.workflowId,path:l,status:A.PLANNING,payload:{layers:g.layers.length,nodes:g.nodes.length}});try{for(const e of g.layers)this.assertNotAborted(i),await this.executeLayer(m,g,e.nodes,i,p);this.assertNotAborted(i);const o=[...m.nodeResults.values()].find(e=>e.status===A.FAILED);if(o?.error)throw new pt(o.error.message,o.error.code??"GRAPH_EXECUTION_ERROR",o.error.details);return m.finish(),await this.emitEvent(m,{type:D.WORKFLOW_COMPLETED,runId:d,parentRunId:i.parentRunId,workflowId:g.workflowId,path:l,status:A.SUCCEEDED,payload:{outputs:u.getWorkflowValues()}}),Bt(m,e,t,A.SUCCEEDED,i.metadata)}catch(o){if(o instanceof _t)throw m.finish(),o;m.finish();const n=this.toErrorPayload(o);return o instanceof bt||!0===i.abortSignal?.aborted?(await this.emitEvent(m,{type:D.WORKFLOW_CANCELLED,runId:d,parentRunId:i.parentRunId,workflowId:g.workflowId,path:l,status:A.CANCELLED,error:n}),Bt(m,e,t,A.CANCELLED,i.metadata)):(await this.emitEvent(m,{type:D.WORKFLOW_FAILED,runId:d,parentRunId:i.parentRunId,workflowId:g.workflowId,path:l,status:A.FAILED,error:n}),Bt(m,e,t,A.FAILED,i.metadata))}}async pinNode(e){const t=this.createPinningService();await t.pinNode(e),await this.emitPinningEvent(e.nodeId,D.NODE_PINNED)}async unpinNode(e){const t=this.createPinningService();await t.unpinNode(e),await this.emitPinningEvent(e.nodeId,D.NODE_UNPINNED)}createPinningService(){const e=ho(this.valueAdapter);return new go(e,new wo,new _o)}async emitPinningEvent(e,t){const o=(new It).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,r){const a=Math.max(1,n.concurrency??4),i=[...o];for(;i.length>0;){const o=i.splice(0,a);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);if(!0===o.instance.disabled)return void await this.executeDisabledNode(e,t,o,n);const a=new Date,i=[...n.path??[],o.id];await this.emitEvent(e,{type:D.NODE_STARTED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:A.RUNNING}),this.emitNodeStateChanged(e,t,o,i,x.RUNNING,A.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 r=new Date,d={nodeId:o.id,status:A.CACHED,inputs:s,outputs:n.outputs,startedAt:a,finishedAt:r,fromCache:!0,pinned:!0,events:[]};return e.recordNodeResult(d),await this.emitEvent(e,{type:D.NODE_CACHE_HIT,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:A.CACHED,payload:{outputs:n.outputs}}),await this.emitEvent(e,{type:D.NODE_COMPLETED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:A.SUCCEEDED,payload:{outputs:n.outputs,fromCache:!0}}),void this.emitNodeStateChanged(e,t,o,i,x.SUCCEEDED,A.SUCCEEDED)}}try{const d=new jt(e.runId,n.parentRunId,t.workflowId,t.resolved.document,o.instance,o.manifest,i,r,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:A.SUCCEEDED,inputs:s,outputs:p,startedAt:a,finishedAt:h,events:[]};e.recordNodeResult(f),await this.emitEvent(e,{type:D.NODE_COMPLETED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:A.SUCCEEDED,payload:{outputs:p}}),this.emitNodeStateChanged(e,t,o,i,x.SUCCEEDED,A.SUCCEEDED)}catch(r){if(r instanceof _t)throw r;const d=new Date,l=this.toErrorPayload(r),c={nodeId:o.id,status:A.FAILED,inputs:s,error:l,startedAt:a,finishedAt:d,events:[]};if(e.recordNodeResult(c),await this.emitEvent(e,{type:D.NODE_FAILED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:A.FAILED,error:l}),this.emitNodeStateChanged(e,t,o,i,x.FAILED,A.FAILED),n.failFast??1)throw r}}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===it||e.isDataEdgeActive(t.id))}async skipInactiveNode(e,t,o,n){const r=new Date,a=[...n.path??[],o.id];await this.emitEvent(e,{type:D.NODE_SKIPPED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:A.SKIPPED,payload:{reason:"branchNotSelected"}});const i={nodeId:o.id,status:A.SKIPPED,inputs:{},startedAt:r,finishedAt:new Date,events:[]};e.recordNodeResult(i),this.emitNodeStateChanged(e,t,o,a,x.SKIPPED,A.SKIPPED)}async executeDisabledNode(e,t,o,n){const r=new Date,a=[...n.path??[],o.id],i=Yt.disabledBehaviorOf(o.instance,t.resolved.document.settings);if(await this.emitEvent(e,{type:D.NODE_SKIPPED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:A.SKIPPED,payload:{disabled:!0,behavior:i}}),"skip"===i){const n={nodeId:o.id,status:A.SKIPPED,inputs:{},startedAt:r,finishedAt:new Date,events:[]};return e.recordNodeResult(n),void this.emitNodeStateChanged(e,t,o,a,x.SKIPPED,A.SKIPPED)}const s=await this.resolveNodeInputs(e,t,o,n);let d;if("passThroughFirstInput"===i){const n=(t.incomingByNode.get(o.id)??[]).find(e=>"data"===e.type),r=o.manifest.outputs[0]?.id??"value",a=n?e.valueStore.getPort(n.sourceNodeId,n.sourcePort):Object.values(s)[0];d={[r]:a}}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:A.SUCCEEDED,inputs:s,outputs:d,startedAt:r,finishedAt:new Date,events:[]};e.recordNodeResult(l),this.emitNodeStateChanged(e,t,o,a,x.SUCCEEDED,A.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)),r=Object.keys(t).filter(e=>!n.has(e));if(r.length>0)throw new pt(`Node '${e.id}' of kind '${e.kind}' produced unknown output(s): ${r.join(", ")}`,"GRAPH_OUTPUT_VALIDATION_FAILED",{nodeId:e.id,unknownOutputs:r});const a=o.outputs.filter(e=>!0===e.required&&!(e.id in t)).map(e=>e.id);if(a.length>0)throw new pt(`Node '${e.id}' of kind '${e.kind}' did not produce required output(s): ${a.join(", ")}`,"GRAPH_OUTPUT_VALIDATION_FAILED",{nodeId:e.id,missingRequired:a});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??""}:zt(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:""}:zt(o)&&(t[e]={credentialId:o.credentialId,credentialType:o.credentialType})}return t}async resolveNodeInputs(e,t,o,n){const r={},a=(t.incomingByNode.get(o.id)??[]).filter(e=>"data"===e.type),i=new Map;for(const e of a){const t=i.get(e.targetPort)??[];t.push(e),i.set(e.targetPort,t)}for(const[t,o]of i)if(1===o.length)r[t]=e.valueStore.getPort(o[0].sourceNodeId,o[0].sourcePort);else{let n,a=!1;for(const t of o){const o=e.valueStore.getPort(t.sourceNodeId,t.sourcePort);r[t.sourcePort]=o,void 0!==o&&(n=o,a=!0)}a&&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[a,i]of Object.entries(n))r[a]=Se(i)?await this.evaluateValueTemplate(i,e,t,o):i;return r}async evaluateValueTemplate(e,t,o,n){const r=this.codeSandboxEvaluator;if(!r)throw new pt(`Value template on node '${t.id}' requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator`,"GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{nodeId:t.id});const a=e.language??("expression"===e.mode?"javascript":"text"),i="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:i,language:"typescript"===a?"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 pt(`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 a=n.metadata;return await r.evaluate({code:t,language:"javascript",input:o,vars:a?.vars??void 0,item:a?.item,index:a?.index,abortSignal:n.abortSignal})}async tryPinnedValue(e,t,o,n){if(!(new wo).shouldUsePinnedValue(o))return;const r=this.createPinningService(),a=this.computeDependencyFingerprints(e,t,o.id);return r.readPinnedValue(t.workflowId,o,n,a)}computeDependencyFingerprints(e,t,o){const n=this.createPinningService(),r=(new _o).getDependencies(t,o),a={};for(const o of r){const r=t.nodes.find(e=>e.id===o);if(r){const i=e.nodeResults.get(o),s=i?.inputs??{},d=this.computeDependencyFingerprints(e,t,o);a[o]=n.computeFingerprint(t.workflowId,r,s,d)}}return a}routeOutgoingEdges(e,t,o,n){const r=(t.outgoingByNode.get(o.id)??[]).filter(e=>"data"===e.type);for(const a of r){if(!Object.prototype.hasOwnProperty.call(n,a.sourcePort))continue;const r=n[a.sourcePort];e.activateDataEdge(a.id),a.targetNodeId===it&&e.valueStore.setWorkflowOutput(a.targetPort,r),this.emitEdgeStateChanged(e,t,o,a,x.SUCCEEDED,A.SUCCEEDED),this.emitEvent(e,{type:D.EDGE_VALUE_ROUTED,runId:e.runId,workflowId:t.workflowId,edgeId:a.id,nodeId:o.id,path:[],payload:{edge:a,value:r}}).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,r,a){this.emitEvent(e,{type:D.NODE_STATE_CHANGED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:n,status:a,payload:{nodeId:o.id,state:r,runId:e.runId,workflowId:t.workflowId,status:a}}).catch(()=>{})}emitEdgeStateChanged(e,t,o,n,r,a){this.emitEvent(e,{type:D.EDGE_STATE_CHANGED,runId:e.runId,workflowId:t.workflowId,edgeId:n.id,nodeId:o.id,path:[],status:a,payload:{edgeId:n.id,state:r,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,status:a}}).catch(()=>{})}mergeOptions(e){return{concurrency:4,failFast:!0,validateInputs:!0,validateOutputs:!0,maxLoopIterations:st,maxForeachIterations:dt,usePinnedValues:!0,writeThroughCache:!1,path:[],metadata:{},...this.defaultOptions,...e}}executionLimits(e){return{maxLoopIterations:e.maxLoopIterations??st,maxForeachIterations:e.maxForeachIterations??dt}}assertNotAborted(e){if(!0===e.abortSignal?.aborted)throw new bt(e.runId??"unknown")}generateRunId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new pt("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 vo=new Set(["process","require","module","exports","global","globalThis","Function","eval","fetch","XMLHttpRequest","WebSocket","Worker","Deno","Bun","__dispatch"]);class No extends s.ClientBasedService{constructor(){super()}async initialize(...e){const t=e[0]??{},o=t&&"object"==typeof t?t:{};return this._config=o,this._client=d,{config:o,client:d}}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 pt("Code sandbox received empty code","GRAPH_CODE_SANDBOX_EMPTY_CODE");const n=((e,t)=>"javascript"===t?e:w.transpileModule(e,{compilerOptions:{target:w.ScriptTarget.ES2022,module:w.ModuleKind.None,strict:!0,noEmitHelpers:!0,importHelpers:!1}}).outputText.replace(/^"use strict";\s*/,""))(o,e.language??"javascript");(e=>{if(e.length>1e5)throw new pt("Code exceeds the maximum length of 100000 characters","GRAPH_CODE_SANDBOX_CODE_TOO_LONG",{length:e.length});let t;try{t=m.parse(`async function __validate() {\n${e}\n}`,{ecmaVersion:"latest",sourceType:"script"})}catch{try{t=m.parse(e,{ecmaVersion:"latest",sourceType:"module"})}catch(t){throw new pt("Code failed to parse: "+t.message,"GRAPH_CODE_SANDBOX_PARSE_ERROR",{code:e,error:t.message})}}y.full(t,e=>{const t=e;if("ImportDeclaration"===t.type)throw new pt("Imports are not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"import"});if("ExportNamedDeclaration"===t.type||"ExportDefaultDeclaration"===t.type)throw new pt("Exports are not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"export"});if("Identifier"===t.type&&"string"==typeof t.name&&vo.has(t.name))throw new pt(`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 pt("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 pt("eval() is not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"eval"})})})(n);const r=!(e=>/\breturn\b[\s;]/.test(e))(n),a=r?n.replace(/[\s;]+$/,""):n,i={$input:e.input??{},$vars:e.vars??{},$item:e.item,$index:e.index,$node:e.nodes??{},$output:void 0},s=Object.keys(i),l=r?`return (${a});`:a,c=`"use strict";\nasync function __userFunction(${s.join(", ")}) {\n${l}\n}\n__userFunction(${s.join(", ")}).then(function(__r) { return JSON.stringify({ v: __r }); });`,u=new d.Isolate({memoryLimit:this.defaultMemoryMb}),p=await u.createContext();try{const t=p.global;e.logger&&await this.injectConsole(p,e.logger);for(const[e,o]of Object.entries(i))await t.set(e,new d.ExternalCopy(void 0===o?null:o).copyInto());let o;try{o=await u.compileScript(c,{filename:"graph-code-node.js"})}catch(e){if(!r)throw new pt("Code failed to compile: "+e.message,"GRAPH_CODE_SANDBOX_COMPILE_ERROR",{code:n,error:e.message});{const e=a,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 u.compileScript(t,{filename:"graph-code-node.js"})}catch(e){throw new pt("Code failed to compile: "+e.message,"GRAPH_CODE_SANDBOX_COMPILE_ERROR",{code:n,error:e.message})}}}const l=e.timeoutMs??this.defaultTimeoutMs;let h;try{h=await this.runBounded(o,p,l,e.abortSignal)}catch(e){if(e instanceof pt)throw e;const t=e.message;if(t.includes("timed out")||t.includes("timeout"))throw new pt(`Code execution timed out after ${l} ms`,"GRAPH_CODE_SANDBOX_TIMEOUT",{timeoutMs:l});if(t.includes("memory")||t.includes("heap"))throw new pt(`Code exceeded the memory limit of ${this.defaultMemoryMb} MB`,"GRAPH_CODE_SANDBOX_MEMORY_LIMIT",{memoryMb:this.defaultMemoryMb});throw new pt("Code execution failed: "+t,"GRAPH_CODE_SANDBOX_RUNTIME_ERROR",{code:n,error:t})}if("string"!=typeof h)throw new pt("Code sandbox returned an unexpected non-string result","GRAPH_CODE_SANDBOX_UNEXPECTED_RESULT",{result:h});return JSON.parse(h).v}finally{p.release(),u.dispose()}}async runBounded(e,t,o,n){const r=e.run(t,{timeout:o,promise:!0});r.catch(()=>{});const a=[r];let i,s;try{return a.push(new Promise((e,t)=>{i=setTimeout(()=>{t(new pt(`Code execution timed out after ${o} ms`,"GRAPH_CODE_SANDBOX_TIMEOUT",{timeoutMs:o}))},o+100)})),n&&a.push(new Promise((e,t)=>{const r=()=>{const e="timeout"===n.reason;t(new pt(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(a)}finally{i&&clearTimeout(i),s?.()}}async injectConsole(e,t){const o=new d.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(" "),a=1===n.length?n[0]:n;switch(e){case"log":case"info":default:t.info(r,a);break;case"warn":t.warn(r,a);break;case"error":t.error(r,a);break;case"debug":case"dir":case"dirxml":case"table":t.debug(r,a);break;case"trace":t.trace(r,a);break;case"group":case"groupCollapsed":t.debug("[group] "+r,a);break;case"groupEnd":t.debug("[groupEnd]",void 0);break;case"time":case"timeEnd":case"timeLog":case"count":case"countReset":t.debug(`[${e}] ${r}`,a);break;case"assert":n[0]||t.error("Assertion failed: "+r,a);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 Io extends a.InternalError{constructor(e){super(e,Io.name,500)}}class Eo extends a.NotFoundError{constructor(e){super(e),this.name=Eo.name}}class Oo extends a.NotFoundError{constructor(e){super(e),this.name=Oo.name}}class Ao{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 Io(`Method declaration for kind '${this.kind}' is missing a name`);if(this.declarations.has(e.name))throw new Io(`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 Io(`Method implementation '${e}' for kind '${this.kind}' is not a function`);if(!this.declarations.has(e))throw new Io(`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 Io(`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 Oo(`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 xo(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 ko(e,t,o){const n=xo(t,e.itemIdPath),r=e.itemLabelPath?xo(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 Do(e,t){switch(t){case"input":return e.inputs;case"output":return e.outputs;default:return e.connections}}function So(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 a=Do(o,n.direction);e.forEach((e,t)=>{const{id:o,label:i}=ko(n,e,t),s=(d={id:o,index:t,label:i??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?ie(n.defaultPort):{id:s,label:i??s,direction:n.direction};l.id=s,l.direction=n.direction,i&&(l.label=i),a.push(l)})}else if("togglePort"===n.type){if(t[n.parameter]!==n.equals)continue;const e=ie(n.port);if(!r(e.direction,e.id))continue;Do(o,e.direction).push(e)}return o}function Po(e,t){const o=So(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),ie(n)}class Ro{async resolve(e,t,o,n,r){if(o){const a=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)})(a))throw new Io(`resolveManifest provider for kind '${e}' returned a value that does not conform to GraphResolvedNodeManifest`);if(!ae(a))throw new Io(`resolveManifest provider for kind '${e}' returned a non-JSON-safe resolved manifest`);const i=ie(a);return!i.namespaces?.length&&t.namespaces?.length&&(i.namespaces=t.namespaces.slice()),i}return Po(t,n.parameters??{})}}const Co=["edge","literal","expression"];function To(e){return Co.includes(e)}function $o(e,t,o){if("string"!=typeof o||!o)throw new Io(`Manifest for kind '${e}' has a ${t} with an empty port id`);if(te(o))throw new Io(`Manifest for kind '${e}' has a ${t} with unsafe port id '${o}'`)}function Go(e){return e}function Lo(e){if(!e)return;const t={...e.metadata??{},...e.parameters??{},...e.state??{}};return e.loop&&(t.loop=e.loop),t}e.GraphNodeCatalogue=class extends s.Service{constructor(){super(),this.entries=new Map,this.resolver=new Ro,this.fallbackContext=new s.Context}withContext(e){return e[e.length-1]instanceof s.Context?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 Io("Graph node registration is required");if(!e.manifest||"object"!=typeof e.manifest)throw new Io("Graph node registration is missing a manifest");if(!e.executor||"function"!=typeof e.executor.execute)throw new Io(`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 Io("Graph node manifest kind is required and must be a non-empty string");const a=r.kind;if(this.entries.has(a)&&!t.replace)throw new Io(`Graph node kind '${a}' is already registered; pass { replace: true } to replace it`);try{$e(r)}catch(e){throw new Io(`Manifest for kind '${a}' 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($o(e,t+" port",r?.id),o.has(r.id))throw new Io(`Manifest for kind '${e}' declares duplicate static ${t} port id '${r.id}'`);if(o.add(r.id),void 0!==r.defaultMode&&!To(r.defaultMode))throw new Io(`Manifest for kind '${e}' declares invalid default binding mode '${r.defaultMode+""}' on ${t} port '${r.id}'`)}}})(a,r);const i=((e,t)=>{const o=new Set;for(const n of t.parameters){const t=n?.id;if("string"!=typeof t||!t)throw new Io(`Manifest for kind '${e}' has a parameter with an empty id`);if(te(t))throw new Io(`Manifest for kind '${e}' has a parameter with unsafe id '${t}'`);if(o.has(t))throw new Io(`Manifest for kind '${e}' declares duplicate parameter id '${t}'`);o.add(t)}return o})(a,r);((e,t,o)=>{for(const n of t.dynamicPorts??[]){if(!n||"string"!=typeof n.parameter||!n.parameter)throw new Io(`Manifest for kind '${e}' has a dynamic-port rule without a parameter reference`);if(!o.has(n.parameter))throw new Io(`Manifest for kind '${e}' has a dynamic-port rule referencing missing parameter '${n.parameter}'`);if("togglePort"===n.type){if(!n.port)throw new Io(`Manifest for kind '${e}' has a togglePort rule without a port`);$o(e,"togglePort rule port",n.port.id)}if("repeatFromParameter"===n.type&&"string"!=typeof n.portIdTemplate)throw new Io(`Manifest for kind '${e}' has a repeatFromParameter rule without a portIdTemplate`)}})(a,r,i),((e,t)=>{for(const o of t.credentials??[]){if(!Re(o))throw new Io(`Manifest for kind '${e}' has a malformed credential requirement`);if(!o.type)throw new Io(`Manifest for kind '${e}' has a credential requirement with an empty type`)}})(a,r),((e,t)=>{for(const o of t.methods??[])if(!Le(o))throw new Io(`Manifest for kind '${e}' has a malformed method declaration`)})(a,r);const s=new Ao(a,r.methods??[],e.methods??{});return this.entries.set(a,{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 Io("Graph executor kind is required");if(!t||"function"!=typeof t.execute)throw new Io(`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 a={kind:e,display:{name:e},inputs:[],outputs:[],parameters:[],policies:{allowUndeclaredParameters:!0,allowUnknownOutputs:!0}};return this.entries.set(e,{registration:{manifest:a,executor:t},methods:new Ao(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 Eo(`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),ie(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,a=[];for(const e of o){if(r&&!r.has(e))continue;const o=this.getManifest(e,...t);n&&!n.has(o.display.category??"")||a.push(o)}return a}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)}},e.GraphNodeCatalogue=i.__decorate([s.service(),i.__metadata("design:paramtypes",[])],e.GraphNodeCatalogue),e.GraphNodeExecutorRegistry=class extends s.Service{constructor(t=new e.GraphNodeCatalogue){super(),this.catalogue=t}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 pt("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 Eo)throw new pt(`No graph executor registered for kind '${e}'`,"GRAPH_EXECUTOR_NOT_FOUND",{kind:e});throw t}}},e.GraphNodeExecutorRegistry=i.__decorate([s.service(),i.__metadata("design:paramtypes",[e.GraphNodeCatalogue])],e.GraphNodeExecutorRegistry),e.GraphNodeExecutorResolver=class extends s.Service{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)}},e.GraphNodeExecutorResolver=i.__decorate([s.service(),i.__metadata("design:paramtypes",[Function,Object])],e.GraphNodeExecutorResolver);class Mo extends r.Model{constructor(e){super(),r.Model.fromModel(this,e)}execute(e,t){throw new pt(`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)}}function Fo(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+""}}e.BreakFlowNode=class extends Mo{execute(e,t){throw new _t(e.inputs.value)}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.break.fields.value.label",placeholder:"graph.node.flow_control.break.fields.value.placeholder",type:"textarea"}),Y({handle:"value"}),i.__metadata("design:type",Object)],e.BreakFlowNode.prototype,"value",void 0),e.BreakFlowNode=i.__decorate([J("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"}}),r.model()],e.BreakFlowNode),e.ErrorBoundaryFlowNode=class extends Mo{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 pt("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"]}),a=Object.values(r.nodeResults).find(e=>e.status===A.FAILED);if(a)throw new pt(a.error?.message??"error boundary try body failed",a.error?.code??"GRAPH_ERROR_BOUNDARY",a.error?.details);return{result:r.outputs.result??r.outputs}}catch(r){let a=r;if(o.catch){const i=await n.execute(o.catch,{...e.inputs,error:Fo(r)},{parentRunId:t.runId,path:[...t.path,"catch"]});a=i.outputs.error??i.outputs}return{error:a}}finally{o.finally&&await n.execute(o.finally,e.inputs,{parentRunId:t.runId,path:[...t.path,"finally"]})}}},i.__decorate([r.required(),o.uielement("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"}),Y({handle:"value"}),i.__metadata("design:type",Object)],e.ErrorBoundaryFlowNode.prototype,"value",void 0),i.__decorate([Q({handle:"result"}),i.__metadata("design:type",Object)],e.ErrorBoundaryFlowNode.prototype,"result",void 0),i.__decorate([Q({handle:"error"}),i.__metadata("design:type",Object)],e.ErrorBoundaryFlowNode.prototype,"error",void 0),e.ErrorBoundaryFlowNode=i.__decorate([J("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}}),r.model()],e.ErrorBoundaryFlowNode),e.HumanApprovalFlowNode=class extends Mo{execute(e){const t=e.inputs.value??e.inputs;return!1===this.approved?{rejected:t}:{approved:t}}},i.__decorate([r.required(),Y({handle:"value"}),i.__metadata("design:type",Object)],e.HumanApprovalFlowNode.prototype,"value",void 0),i.__decorate([o.uielement("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"}),Y({handle:"message",userControlled:!0}),i.__metadata("design:type",String)],e.HumanApprovalFlowNode.prototype,"message",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.human_approval.fields.approved.label",type:"checkbox"}),Y({handle:"approved",userControlled:!0}),i.__metadata("design:type",Boolean)],e.HumanApprovalFlowNode.prototype,"approved",void 0),i.__decorate([Q({handle:"approved"}),i.__metadata("design:type",Object)],e.HumanApprovalFlowNode.prototype,"approvedOut",void 0),i.__decorate([Q({handle:"rejected"}),i.__metadata("design:type",Object)],e.HumanApprovalFlowNode.prototype,"rejectedOut",void 0),e.HumanApprovalFlowNode=i.__decorate([J("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}}),r.model()],e.HumanApprovalFlowNode);class Vo{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 pt(`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 pt("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}}async function jo(e,t,o,n){if("object"==typeof(r=e)&&null!==r&&"type"in r&&"code"===r.type){const t=n.engine?.codeSandboxEvaluator;if(!t)throw new pt("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 r=n.metadata;return!!await t.evaluate({code:e.code,language:e.language,input:o,vars:r?.vars??void 0,item:r?.item,index:r?.index,nodes:r?.nodes??void 0,logger:n.logger,abortSignal:n.abortSignal})}var r;if((e=>"object"==typeof e&&null!==e&&"op"in e&&"string"==typeof e.op)(e))return(new Vo).evaluate(e,t);throw new pt("Unknown switch case condition type \u2014 must be ConditionExpression (op) or CodeCondition (type: 'code')","GRAPH_UNKNOWN_SWITCH_CONDITION",{condition:e})}e.IfFlowNode=class extends Mo{execute(e){const t=e.inputs,o=t.value??t;if(!this.condition)throw new pt("If node has no condition configured","GRAPH_IF_NO_CONDITION",{input:t});const n=(new Vo).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 pt("If node condition evaluated to false and the else branch is disabled","GRAPH_IF_ELSE_DISABLED",{condition:this.condition})}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.value.label",placeholder:"graph.node.flow_control.if.fields.value.placeholder",type:"textarea"}),Y({handle:"value"}),i.__metadata("design:type",Object)],e.IfFlowNode.prototype,"value",void 0),i.__decorate([r.required(),Q({handle:"then"}),i.__metadata("design:type",Object)],e.IfFlowNode.prototype,"then",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.condition.label",placeholder:"graph.node.flow_control.if.fields.condition.placeholder",type:"code"}),Y({handle:"condition",userControlled:!0,type:"object"}),i.__metadata("design:type",Object)],e.IfFlowNode.prototype,"condition",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.else.label",type:"checkbox"}),Y({handle:"else",userControlled:!0}),i.__metadata("design:type",Boolean)],e.IfFlowNode.prototype,"else",void 0),e.IfFlowNode=i.__decorate([J("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"}}),r.model()],e.IfFlowNode),e.SwitchFlowNode=class extends Mo{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,a=r.value??r,i=((e,t)=>t===e||"object"!=typeof t||null===t||Array.isArray(t)?e:{...t,...e})(r,a);for(const e of n)if(await jo(e.condition,i,r,t))return{[e.outputPort]:a};if(!0!==o.hasDefault)throw new pt("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]:a}}static applyMetadata(e){const t=H(this),o=e.defaultPort??"default",n=!0===e.hasDefault,r=t.ports.filter(t=>!e.cases.some(e=>e.outputPort===t.property)),a=r.filter(e=>e.property!==o),i=r.find(e=>e.property===o),s=[...a,...e.cases.map(e=>({property:e.outputPort,name:e.label,direction:g.OUTPUT,label:e.label,required:!1,hidden:!1,path:e.outputPort}))];return n&&i&&s.push(i),{ports:s,size:b(t,{cases:e.cases.length}),dataPatch:{switchMetadata:e}}}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.value.label",placeholder:"graph.node.flow_control.switch.fields.value.placeholder",type:"textarea"}),Y({handle:"value"}),i.__metadata("design:type",Object)],e.SwitchFlowNode.prototype,"value",void 0),i.__decorate([r.required(),Q({handle:"default"}),i.__metadata("design:type",Object)],e.SwitchFlowNode.prototype,"default",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.cases.label",type:"collection"}),i.__metadata("design:type",Object)],e.SwitchFlowNode.prototype,"cases",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.hasDefault.label",type:"checkbox"}),i.__metadata("design:type",Boolean)],e.SwitchFlowNode.prototype,"hasDefault",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.defaultPort.label",type:"text"}),i.__metadata("design:type",String)],e.SwitchFlowNode.prototype,"defaultPort",void 0),e.SwitchFlowNode=i.__decorate([J("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"}}),r.model()],e.SwitchFlowNode);const Uo={maxDocumentBytes:2e6,maxNestingDepth:10,maxNodes:500,maxEdges:1e3},Bo=t.LoggedEnvironment.accumulate({graph:{workflows:{limits:{...Uo},allowAnonymousAccess:!1},execution:{maxCodeTimeoutMs:lt}}});function qo(e,t){const o="number"==typeof e?e:Number(e);return Number.isFinite(o)&&o>0?Math.min(Math.floor(o),t):1e3}const Wo=["javascript","typescript"],Ho="javascript";e.CodeInputSchema=class extends r.Model{constructor(){super(...arguments),this.language=Ho}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.code.fields.language.label",type:"select"}),r.option([...Wo]),r.type(String),i.__metadata("design:type",String)],e.CodeInputSchema.prototype,"language",void 0),i.__decorate([r.required(),o.uielement("code-editor",{label:"graph.node.utility.code.fields.code.label",placeholder:"graph.node.utility.code.fields.code.placeholder"}),Y({handle:"code"}),i.__metadata("design:type",String)],e.CodeInputSchema.prototype,"code",void 0),i.__decorate([o.hidden(),Y({handle:"data"}),i.__metadata("design:type",Object)],e.CodeInputSchema.prototype,"data",void 0),e.CodeInputSchema=i.__decorate([r.model()],e.CodeInputSchema),e.CodeNode=class extends Mo{async execute(e,t){const o=e.inputs,n=this.input,r=o.code??e.parameters?.code??n?.code??this.defaultCode,a=n?.language??Ho;if(!r||"string"!=typeof r||0===r.trim().length)throw new ft("Code node has no code to execute (input.code is empty)",{input:o});const i=t.engine?.codeSandboxEvaluator;if(!i)throw new pt("Code node execution requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator","GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{code:r});const s=Bo.graph.execution?.maxCodeTimeoutMs??lt,d=qo(this.timeoutMs,s),l=t.metadata,c={code:r,language:a,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:a,length:r.length,timeoutMs:d});const u=await i.evaluate(c);return await t.log("Code node executed",{hasResult:void 0!==u}),{result:u}}},i.__decorate([r.required(),Y({handle:"input",model:e.CodeInputSchema}),i.__metadata("design:type",e.CodeInputSchema)],e.CodeNode.prototype,"input",void 0),i.__decorate([r.min(1),r.max(lt),o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.code.fields.timeoutMs.label",type:"number"}),Y({handle:"timeoutMs"}),i.__metadata("design:type",Number)],e.CodeNode.prototype,"timeoutMs",void 0),i.__decorate([o.uielement("code-editor",{label:"graph.node.utility.code.fields.defaultCode.label",placeholder:"graph.node.utility.code.fields.defaultCode.placeholder"}),Y({handle:"defaultCode",userControlled:!0}),i.__metadata("design:type",String)],e.CodeNode.prototype,"defaultCode",void 0),i.__decorate([r.required(),Q({handle:"result"}),i.__metadata("design:type",Object)],e.CodeNode.prototype,"result",void 0),e.CodeNode=i.__decorate([J("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"}}),r.model()],e.CodeNode),e.DelayFlowNode=class extends Mo{execute(e){return{value:e.inputs.value??e.inputs}}},i.__decorate([r.required(),Y({handle:"value"}),i.__metadata("design:type",Object)],e.DelayFlowNode.prototype,"value",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.delay.fields.timeoutMs.label",type:"number"}),Y({handle:"timeoutMs"}),i.__metadata("design:type",Number)],e.DelayFlowNode.prototype,"timeoutMs",void 0),i.__decorate([r.required(),Q({handle:"value"}),i.__metadata("design:type",Object)],e.DelayFlowNode.prototype,"valueOut",void 0),e.DelayFlowNode=i.__decorate([J("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"}}),r.model()],e.DelayFlowNode),e.LogFlowNode=class extends Mo{execute(e,t){const o=e.inputs.value,n=this.level??"info";return t.logger[n](this.message??"Log node",{value:o}),{value:o}}},i.__decorate([r.required(),Y({handle:"value"}),i.__metadata("design:type",Object)],e.LogFlowNode.prototype,"value",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.log.fields.message.label",placeholder:"graph.node.utility.log.fields.message.placeholder",type:"textarea"}),Y({handle:"message"}),i.__metadata("design:type",String)],e.LogFlowNode.prototype,"message",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.log.fields.level.label",placeholder:"graph.node.utility.log.fields.level.placeholder",type:"text"}),Y({handle:"level",userControlled:!0}),i.__metadata("design:type",String)],e.LogFlowNode.prototype,"level",void 0),i.__decorate([r.required(),Q({handle:"value"}),i.__metadata("design:type",Object)],e.LogFlowNode.prototype,"valueOut",void 0),e.LogFlowNode=i.__decorate([J("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"}}),r.model()],e.LogFlowNode),e.MapNode=class extends Mo{execute(e){return{result:{mapped:e.inputs.value??e.inputs}}}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.map.fields.value.label",placeholder:"graph.node.utility.map.fields.value.placeholder",type:"textarea"}),Y({handle:"value"}),i.__metadata("design:type",Object)],e.MapNode.prototype,"value",void 0),i.__decorate([r.required(),Q({handle:"result"}),i.__metadata("design:type",Object)],e.MapNode.prototype,"result",void 0),e.MapNode=i.__decorate([J("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:{}}}),r.model()],e.MapNode),e.UtilityLogNode=class extends Mo{execute(e,t){const o=e.inputs.value,n=this.level??"info";return t.logger[n](this.message??"Log node",{value:o}),{value:o}}},i.__decorate([r.required(),Y({handle:"value"}),i.__metadata("design:type",Object)],e.UtilityLogNode.prototype,"value",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.utility_log.fields.message.label",placeholder:"graph.node.utility.utility_log.fields.message.placeholder",type:"textarea"}),Y({handle:"message"}),i.__metadata("design:type",String)],e.UtilityLogNode.prototype,"message",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.utility_log.fields.level.label",placeholder:"graph.node.utility.utility_log.fields.level.placeholder"}),Y({handle:"level",userControlled:!0,type:"string"}),i.__metadata("design:type",String)],e.UtilityLogNode.prototype,"level",void 0),i.__decorate([r.required(),Q({handle:"value"}),i.__metadata("design:type",Object)],e.UtilityLogNode.prototype,"valueOut",void 0),e.UtilityLogNode=i.__decorate([J("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"}}),r.model()],e.UtilityLogNode),e.ChatTriggerNode=class extends Mo{execute(e){return{message:e.inputs.message??null,sessionId:e.inputs.sessionId??null,userId:e.inputs.userId??null}}},i.__decorate([r.required(),Q({handle:"message"}),i.__metadata("design:type",String)],e.ChatTriggerNode.prototype,"message",void 0),i.__decorate([r.required(),Q({handle:"sessionId"}),i.__metadata("design:type",String)],e.ChatTriggerNode.prototype,"sessionId",void 0),i.__decorate([r.required(),Q({handle:"userId"}),i.__metadata("design:type",String)],e.ChatTriggerNode.prototype,"userId",void 0),e.ChatTriggerNode=i.__decorate([J("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"}}}),r.model()],e.ChatTriggerNode),e.EventTriggerNode=class extends Mo{execute(e){return{payload:e.inputs.payload??null}}},i.__decorate([r.required(),Q({handle:"payload"}),i.__metadata("design:type",Object)],e.EventTriggerNode.prototype,"payload",void 0),e.EventTriggerNode=i.__decorate([J("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"}}}),r.model()],e.EventTriggerNode),e.FormTriggerNode=class extends Mo{execute(e){return{payload:e.inputs.payload??null}}},i.__decorate([r.required(),Y({handle:"schema"}),o.uielement("ngx-decaf-model-builder",{label:"graph.node.trigger.form.fields.schema.label",placeholder:"graph.node.trigger.form.fields.schema.placeholder"}),i.__metadata("design:type",Object)],e.FormTriggerNode.prototype,"schema",void 0),i.__decorate([r.required(),Q({handle:"payload"}),i.__metadata("design:type",Object)],e.FormTriggerNode.prototype,"payload",void 0),e.FormTriggerNode=i.__decorate([J("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:[]}}}),r.model()],e.FormTriggerNode),e.ManualTriggerNode=class extends Mo{execute(e){return{payload:e.inputs.payload??null}}},i.__decorate([r.required(),Q({handle:"payload"}),i.__metadata("design:type",Object)],e.ManualTriggerNode.prototype,"payload",void 0),e.ManualTriggerNode=i.__decorate([J("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:{}}}}),r.model()],e.ManualTriggerNode),e.ScheduleTriggerNode=class extends Mo{execute(e){return{payload:e.inputs.payload??null}}},i.__decorate([r.required(),Y({handle:"cron"}),o.uielement("app-cron-selector-field",{label:"graph.node.trigger.schedule.fields.cron.label",placeholder:"graph.node.trigger.schedule.fields.cron.placeholder"}),i.__metadata("design:type",String)],e.ScheduleTriggerNode.prototype,"cron",void 0),i.__decorate([r.required(),Q({handle:"payload"}),i.__metadata("design:type",Object)],e.ScheduleTriggerNode.prototype,"payload",void 0),e.ScheduleTriggerNode=i.__decorate([J("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"}}}),r.model()],e.ScheduleTriggerNode),e.WebhookTriggerNode=class extends Mo{execute(e){return{payload:e.inputs.payload??null}}},i.__decorate([r.required(),Y({handle:"schema"}),o.uielement("ngx-decaf-model-builder",{label:"graph.node.trigger.webhook.fields.schema.label",placeholder:"graph.node.trigger.webhook.fields.schema.placeholder"}),i.__metadata("design:type",Object)],e.WebhookTriggerNode.prototype,"schema",void 0),i.__decorate([r.required(),Q({handle:"payload"}),i.__metadata("design:type",Object)],e.WebhookTriggerNode.prototype,"payload",void 0),e.WebhookTriggerNode=i.__decorate([J("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"}}}),r.model()],e.WebhookTriggerNode),e.AgentNode=class extends Mo{execute(e){return{response:"[Agent response] "+(e.inputs.prompt??""),actions:[]}}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.agent.agent.fields.prompt.label",placeholder:"graph.node.agent.agent.fields.prompt.placeholder",type:"textarea"}),Y({handle:"prompt"}),i.__metadata("design:type",String)],e.AgentNode.prototype,"prompt",void 0),i.__decorate([r.required(),Q({handle:"response"}),i.__metadata("design:type",String)],e.AgentNode.prototype,"response",void 0),i.__decorate([r.required(),Q({handle:"actions"}),i.__metadata("design:type",Array)],e.AgentNode.prototype,"actions",void 0),i.__decorate([Z({category:"model",handle:"model"}),i.__metadata("design:type",Object)],e.AgentNode.prototype,"model",void 0),i.__decorate([Z({category:"memory",handle:"memory"}),i.__metadata("design:type",Object)],e.AgentNode.prototype,"memory",void 0),i.__decorate([Z({category:"workspace",handle:"workspace"}),i.__metadata("design:type",Object)],e.AgentNode.prototype,"workspace",void 0),e.AgentNode=i.__decorate([J("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"}}),r.model()],e.AgentNode);const Ko=[e.AgentNode];function zo(e,t,o,n){const r=t??o;if(null==e)return Math.min(o,r);const a=Number(e);if(!Number.isFinite(a)||0>=a)throw new ft(n+" loop maxIterations must be a positive finite number");return Math.min(Math.floor(a),r)}function Jo(e,t,o){const n=t.node.loop,r=t.metadata?.loop;if(!n?.body&&!r?.body)throw new ft(o+" node is missing loop configuration (instance.loop.body)");const a=t=>{const o=e[t]??n?.[t]??r?.[t],a=Number(o);return void 0!==o&&Number.isFinite(a)?a:void 0},i=t=>{const o=e[t]??r?.[t];return"string"==typeof o?o:void 0};return{body:n?.body??r?.body,maxIterations:a("maxIterations"),timeoutMs:a("timeoutMs"),concurrency:a("concurrency"),condition:e.condition??r?.condition,inputPort:i("inputPort"),outputPort:i("outputPort"),itemPort:i("itemPort"),resultPort:i("resultPort"),statePort:i("statePort"),slice:a("slice")}}e.GraphForeachLoopNode=class extends Mo{async execute(e,t){const o=Jo(this,t,"foreach"),n=e.inputs,r=n.items,a=zo(o.maxIterations,t.limits?.maxForeachIterations,1e3,"foreach");if(!Array.isArray(r))throw new ft("foreach input 'items' must be an array");const i=t.engine;if(!i)throw new pt("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>a)throw new gt(`foreach exceeded max iterations (${l} > ${a})`);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:D.LOOP_STARTED});for(let e=0;l>e;e++){await t.emit({type:D.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 i.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 _t){const n=o.details?.value;void 0!==n&&f.push(n),m=!0,await t.emit({type:D.LOOP_ITERATION_COMPLETED,iteration:e,metadata:{broken:!0}});break}throw o}await t.emit({type:D.LOOP_ITERATION_COMPLETED,iteration:e})}await t.emit({type:D.LOOP_COMPLETED,metadata:{broken:m}});const y={results:f,completed:f,iterations:f.length,broken:m};return void 0!==g&&(y[p]=g),y}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.items.label",placeholder:"graph.node.loop.foreach.fields.items.placeholder",type:"textarea"}),Y({handle:"items"}),i.__metadata("design:type",Array)],e.GraphForeachLoopNode.prototype,"items",void 0),i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.slice.label",placeholder:"graph.node.loop.foreach.fields.slice.placeholder",type:"number"}),Y({handle:"slice"}),i.__metadata("design:type",Number)],e.GraphForeachLoopNode.prototype,"slice",void 0),i.__decorate([r.required(),Q({handle:"item"}),i.__metadata("design:type",Object)],e.GraphForeachLoopNode.prototype,"item",void 0),i.__decorate([r.required(),Z({handle:"loop",connectionRules:{allowSelf:!0,maxConnections:1}}),i.__metadata("design:type",Object)],e.GraphForeachLoopNode.prototype,"loop",void 0),i.__decorate([r.required(),Q({handle:"completed"}),i.__metadata("design:type",Array)],e.GraphForeachLoopNode.prototype,"completed",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.maxIterations.label",type:"number"}),Y({handle:"maxIterations",userControlled:!0}),i.__metadata("design:type",Number)],e.GraphForeachLoopNode.prototype,"maxIterations",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.condition.label",type:"code"}),Y({handle:"condition",userControlled:!0}),i.__metadata("design:type",Object)],e.GraphForeachLoopNode.prototype,"condition",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.itemPort.label",type:"text"}),Y({handle:"itemPort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphForeachLoopNode.prototype,"itemPort",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.resultPort.label",type:"text"}),Y({handle:"resultPort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphForeachLoopNode.prototype,"resultPort",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.statePort.label",type:"text"}),Y({handle:"statePort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphForeachLoopNode.prototype,"statePort",void 0),e.GraphForeachLoopNode=i.__decorate([J("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}}}),r.model()],e.GraphForeachLoopNode);class Xo{constructor(){this.expressionEvaluator=new Vo}evaluate(t,o){if(this.isConditionExpression(t))return this.expressionEvaluator.evaluate(t,o);const n=this.resolveValue(t.left,o),r=t.right;switch(t.type){case e.GraphConditionType.TRUTHY:return!!n;case e.GraphConditionType.FALSY:return!n;case e.GraphConditionType.EQUALS:return n===r;case e.GraphConditionType.NOT_EQUALS:return n!==r;case e.GraphConditionType.GREATER_THAN:return Number(n)>Number(r);case e.GraphConditionType.GREATER_THAN_OR_EQUAL:return Number(n)>=Number(r);case e.GraphConditionType.LESS_THAN:return Number(r)>Number(n);case e.GraphConditionType.LESS_THAN_OR_EQUAL:return Number(r)>=Number(n);case e.GraphConditionType.EXISTS:return null!=n;case e.GraphConditionType.CUSTOM:throw new pt("Custom condition evaluators are not supported in v1","GRAPH_CUSTOM_CONDITION_UNSUPPORTED");default:throw new pt(`Unknown condition type '${t.type}'`,"GRAPH_UNKNOWN_CONDITION_TYPE",{condition: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}}function Yo(e,t,o,n={}){return{id:e,label:t,direction:o,...n}}function Qo(e){const t=e,o=F(t),n=o?.metadata?.title;return et(t,n?{name:n}:{})}e.GraphUntilLoopNode=class extends Mo{async execute(e,t){const o=Jo(this,t,"until"),n=e.inputs,r=zo(o.maxIterations,t.limits?.maxLoopIterations,100,"until"),a=o.condition;if(!a)throw new ft("until node is missing a condition");const i=o.statePort??"state",s=o.inputPort??i,d=o.outputPort??i,l=o.body,c=t.engine;if(!c)throw new pt("until node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");let u=n.state,p=0;await t.emit({type:D.LOOP_STARTED});let h=!1;do{if(p>=r)throw await t.emit({type:D.LOOP_LIMIT_REACHED,iteration:p}),new gt(`until loop exceeded max iterations (${r})`);await t.emit({type:D.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:D.LOOP_ITERATION_COMPLETED,iteration:p});const e=(new Xo).evaluate(a,u);await t.emit({type:D.LOOP_CONDITION_EVALUATED,iteration:p,payload:{result:e}}),p++,h=e}while(!h);return await t.emit({type:D.LOOP_COMPLETED}),{state:u,iterations:p}}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.state.label",placeholder:"graph.node.loop.until.fields.state.placeholder",type:"textarea"}),Y({handle:"state"}),i.__metadata("design:type",Object)],e.GraphUntilLoopNode.prototype,"state",void 0),i.__decorate([r.required(),Q({handle:"state"}),i.__metadata("design:type",Object)],e.GraphUntilLoopNode.prototype,"stateOut",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.maxIterations.label",type:"number"}),Y({handle:"maxIterations",userControlled:!0}),i.__metadata("design:type",Number)],e.GraphUntilLoopNode.prototype,"maxIterations",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.condition.label",type:"code"}),Y({handle:"condition",userControlled:!0}),i.__metadata("design:type",Object)],e.GraphUntilLoopNode.prototype,"condition",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.statePort.label",type:"text"}),Y({handle:"statePort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphUntilLoopNode.prototype,"statePort",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.inputPort.label",type:"text"}),Y({handle:"inputPort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphUntilLoopNode.prototype,"inputPort",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.outputPort.label",type:"text"}),Y({handle:"outputPort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphUntilLoopNode.prototype,"outputPort",void 0),e.GraphUntilLoopNode=i.__decorate([J("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}}}}),r.model()],e.GraphUntilLoopNode),e.GraphWhileLoopNode=class extends Mo{async execute(e,t){const o=Jo(this,t,"while"),n=e.inputs,r=zo(o.maxIterations,t.limits?.maxLoopIterations,100,"while"),a=o.condition;if(!a)throw new ft("while node is missing a condition");const i=o.statePort??"state",s=o.inputPort??i,d=o.outputPort??i,l=o.body,c=t.engine;if(!c)throw new pt("while node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");let u=n.state,p=0;for(await t.emit({type:D.LOOP_STARTED});(new Xo).evaluate(a,u);){if(p>=r)throw await t.emit({type:D.LOOP_LIMIT_REACHED,iteration:p}),new gt(`while loop exceeded max iterations (${r})`);await t.emit({type:D.LOOP_CONDITION_EVALUATED,iteration:p,payload:{result:!0}}),await t.emit({type:D.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:D.LOOP_ITERATION_COMPLETED,iteration:p}),p++}return await t.emit({type:D.LOOP_COMPLETED}),{state:u,iterations:p}}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.state.label",placeholder:"graph.node.loop.while.fields.state.placeholder",type:"textarea"}),Y({handle:"state"}),i.__metadata("design:type",Object)],e.GraphWhileLoopNode.prototype,"state",void 0),i.__decorate([r.required(),Q({handle:"state"}),i.__metadata("design:type",Object)],e.GraphWhileLoopNode.prototype,"stateOut",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.maxIterations.label",type:"number"}),Y({handle:"maxIterations",userControlled:!0}),i.__metadata("design:type",Number)],e.GraphWhileLoopNode.prototype,"maxIterations",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.condition.label",type:"code"}),Y({handle:"condition",userControlled:!0}),i.__metadata("design:type",Object)],e.GraphWhileLoopNode.prototype,"condition",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.statePort.label",type:"text"}),Y({handle:"statePort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphWhileLoopNode.prototype,"statePort",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.inputPort.label",type:"text"}),Y({handle:"inputPort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphWhileLoopNode.prototype,"inputPort",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.outputPort.label",type:"text"}),Y({handle:"outputPort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphWhileLoopNode.prototype,"outputPort",void 0),e.GraphWhileLoopNode=i.__decorate([J("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}}}}),r.model()],e.GraphWhileLoopNode),e.GraphInputValueNode=class extends Mo{execute(e){const t=e.inputs;return{value:t?.value??null}}},i.__decorate([Q({handle:"value",connectionRules:{allowMultiple:!0}}),i.__metadata("design:type",Object)],e.GraphInputValueNode.prototype,"value",void 0),e.GraphInputValueNode=i.__decorate([J("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"}}),r.model()],e.GraphInputValueNode),e.GraphOutputValueNode=class extends Mo{execute(e){return{}}},i.__decorate([r.required(),Y({handle:"value"}),i.__metadata("design:type",Object)],e.GraphOutputValueNode.prototype,"value",void 0),e.GraphOutputValueNode=i.__decorate([J("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"}}),r.model()],e.GraphOutputValueNode);const Zo={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:[Yo("items","graph.node.loop.foreach.ports.input.items.label","input",{required:!0,schema:{type:"array",items:{type:"any"}}}),Yo("slice","graph.node.loop.foreach.ports.input.slice.label","input",{schema:{type:"number",integer:!0,min:1}}),Yo("state","graph.node.loop.foreach.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[Yo("results","graph.node.loop.foreach.ports.output.results.label","output",{schema:{type:"array",items:{type:"any"}}}),Yo("completed","graph.node.loop.foreach.ports.output.completed.label","output",{schema:{type:"array",items:{type:"any"}}}),Yo("iterations","graph.node.loop.foreach.ports.output.iterations.label","output",{schema:{type:"number",integer:!0,min:0}}),Yo("broken","graph.node.loop.foreach.ports.output.broken.label","output",{schema:{type:"boolean"}}),Yo("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}]},en={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:[Yo("state","graph.node.loop.while.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[Yo("state","graph.node.loop.while.ports.output.state.label","output",{schema:{type:"any"}}),Yo("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"}]},tn={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:[Yo("state","graph.node.loop.until.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[Yo("state","graph.node.loop.until.ports.output.state.label","output",{schema:{type:"any"}}),Yo("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"}]},on=[Qo(e.GraphInputValueNode),Qo(e.GraphOutputValueNode),Qo(e.ManualTriggerNode),Qo(e.WebhookTriggerNode),Qo(e.ScheduleTriggerNode),Qo(e.EventTriggerNode),Qo(e.FormTriggerNode),Qo(e.ChatTriggerNode),(nn=Qo(e.IfFlowNode),{...nn,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"}}}]}))(Qo(e.SwitchFlowNode)),Qo(e.MapNode),Qo(e.DelayFlowNode),Qo(e.ErrorBoundaryFlowNode),Qo(e.HumanApprovalFlowNode),Qo(e.CodeNode),Qo(e.LogFlowNode),Qo(e.UtilityLogNode),Qo(e.BreakFlowNode),Qo(e.AgentNode),Zo,en,tn];var nn;const rn=Object.fromEntries(on.map(e=>[e.kind,e])),an=[e.ManualTriggerNode,e.WebhookTriggerNode,e.ScheduleTriggerNode,e.EventTriggerNode,e.FormTriggerNode,e.ChatTriggerNode],sn=[e.IfFlowNode,e.SwitchFlowNode,e.DelayFlowNode,e.ErrorBoundaryFlowNode,e.HumanApprovalFlowNode,e.LogFlowNode,e.BreakFlowNode],dn=[e.CodeNode,e.MapNode,e.UtilityLogNode],ln=[e.GraphForeachLoopNode,e.GraphWhileLoopNode,e.GraphUntilLoopNode],cn=[e.GraphInputValueNode,e.GraphOutputValueNode],un={value:e.GraphInputValueNode,result:e.GraphOutputValueNode,"core.trigger.manual":e.ManualTriggerNode,"core.trigger.webhook":e.WebhookTriggerNode,"core.trigger.schedule":e.ScheduleTriggerNode,"core.trigger.event":e.EventTriggerNode,"core.trigger.form":e.FormTriggerNode,"core.trigger.chat":e.ChatTriggerNode,"core.flow.if":e.IfFlowNode,"core.flow.switch":e.SwitchFlowNode,"core.utility.map":e.MapNode,"core.flow.delay":e.DelayFlowNode,"core.flow.errorBoundary":e.ErrorBoundaryFlowNode,"core.flow.humanApproval":e.HumanApprovalFlowNode,"core.utility.code":e.CodeNode,"core.flow.log":e.LogFlowNode,"core.utility.log":e.UtilityLogNode,"core.flow.break":e.BreakFlowNode,"core.agent":e.AgentNode,"core.loop.foreach":e.GraphForeachLoopNode,"core.loop.while":e.GraphWhileLoopNode,"core.loop.until":e.GraphUntilLoopNode};function pn(e){return{execute:(t,o)=>e.instantiate({...Lo(o.node),...t.parameters,...o.node.state??{}}).execute(t,o)}}function hn(){const e=[];for(const[t,o]of Object.entries(rn)){const n=un[t];n&&e.push(Go({manifest:o,executor:pn(n)}))}return e}const fn=["node","definition","executor","execute","ports","component"];function gn(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 mn(e,t){const o=[];for(const n of Object.keys(e))fn.includes(n)&&o.push(gn("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 yn(e,t){t.push(...mn(e,"$")),e.inputs.forEach((e,o)=>t.push(...mn(e,`inputs[${o}]`))),e.outputs.forEach((e,o)=>t.push(...mn(e,`outputs[${o}]`)));for(const o of e.nodes)t.push(...mn(o,`nodes[${o.id}]`)),o.loop&&(t.push(...mn(o.loop,`nodes[${o.id}].loop`)),yn(o.loop.body,t));for(const o of e.edges)t.push(...mn(o,`edges[${o.id}]`))}function wn(e,t){const o=[];e.nodes.length>t.maxNodes&&o.push(gn("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(gn("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=_n(e);n>t.maxNestingDepth&&o.push(gn("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(gn("document.limit.size","$",`Document serializes to ${r} bytes; at most ${t.maxDocumentBytes} bytes are allowed`,{details:{bytes:r,limit:t.maxDocumentBytes}})),o}function _n(e,t=0){let o=t;for(const n of e.nodes)n.loop?.body&&(o=Math.max(o,_n(n.loop.body,t+1)));return o}async function bn(e,t,...o){const n=[];for(const r of e.nodes)t.has(r.kind,...o)||n.push(gn("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 bn(r.loop.body,t,...o));return n}async function vn(e,t={},...o){const n={...Uo,...t.limits},r=[];if(!Pe(e))return r.push(gn("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(!ae(e))return r.push(gn("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};yn(e,r),r.push(...(e=>{const t=[],o=new Set;for(const n of[...e.inputs,...e.outputs])o.has(n.id)?t.push(gn("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(gn("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(gn("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(...wn(e,n)),Wt(e,r);try{ve(e)}catch(e){const t=e instanceof a.ValidationError?e.message:e+"";r.push(gn("document.structure","$",t))}return t.catalogue&&r.push(...await bn(e,t.catalogue,...o)),{valid:0===r.length,issues:r}}function Nn(e,t,o){const n=e?.owner??null;if(n&&n!==t&&(null!=t&&""!==t||!0!==o.allowAnonymousAccess))throw new s.ForbiddenError(`${o.resourceKind} '${o.resourceId}' is owned by another user`)}function In(e){if(null===e||"object"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(e=>In(e)).join(",")}]`;const t=e;return`{${Object.keys(t).filter(e=>void 0!==t[e]).sort().map(e=>`${JSON.stringify(e)}:${In(t[e])}`).join(",")}}`}function En(e){return p.createHash("sha256").update(In(e)).digest("hex")}class On{constructor(e,t={}){this.sequences=new Map,this.chains=new Map,this.store=e,this.limits={...S,...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 An{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={...S,...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 a=this.runExecution({...e},t,o,...n).catch(async t=>{const o=xn(t);try{await this.emitTerminal({...e},D.WORKFLOW_FAILED,o)}catch{}return await this.finalize({...e},"failed",void 0,o,...n)});return this.completions.set(e.runId,a),a}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 a,i,s=!1;const d=this.engine.observe({refresh:async t=>{t.runId===r&&(t.error&&(a=t.error),R((await this.publisher.publish(this.envelopeOf(e,t))).type)?s=!0:t.type===D.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 a=t,await this.emitTerminal(e,D.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=xn(t);return a=o,s||(await this.emitTerminal(e,D.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 a=t,s||(await this.emitTerminal(e,D.WORKFLOW_CANCELLED,t),s=!0),await this.finalize(e,"cancelled",void 0,t,...n)}try{i=await this.engine.execute(d,o,{runId:r,abortSignal:this.controllers.get(r)?.signal,metadata:{documentFingerprint:l}},...n)}catch(e){a=xn(e)}const c=this.abortReason(r);let u,p;return"timeout"===c?(u="failed",p=a??{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=a):i?.status===A.SUCCEEDED?u="succeeded":i?.status===A.CANCELLED?(u="cancelled",p=a):(u="failed",p=a??xn(new pt(i?`Graph run '${r}' failed`:`Graph run '${r}' failed without a result`,"GRAPH_RUN_FAILED",{runId:r}))),s||await this.emitTerminal(e,"succeeded"===u?D.WORKFLOW_COMPLETED:"cancelled"===u?D.WORKFLOW_CANCELLED:D.WORKFLOW_FAILED,p),await this.finalize(e,u,i,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:re(t.payload)?t.payload:{nonSerializable:!0},error:t.error,parentRunId:t.parentRunId,path:t.path}}}function xn(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+""}}function kn(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 Dn(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&Pe(e.document)&&!Pe(e)}function Sn(e){return JSON.parse(JSON.stringify(e))}function Pn(e){if(null!=e)return JSON.parse(JSON.stringify(e))}e.GraphWorkflowService=class extends s.ModelService{constructor(e){super(ot),this.catalogue=e}get limits(){return{...Uo,...Bo.graph.workflows.limits??{}}}get allowAnonymousAccess(){return!0===Bo.graph.workflows.allowAnonymousAccess}async saveDocument(e,t,...o){const{ctx:n,ctxArgs:r}=(await this.logCtx(o,"saveDocument",!0)).for(this.saveDocument);if(!Pe(t))throw new a.ValidationError("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.ValidationError(`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 vt(i.issues);const s=kn(n);let d;try{d=await this.read(e,...r)}catch{d=null}this.assertOwnership(e,d,s);const l=new Date;if(d)return d.name=t.name,d.document=Sn(t),d.updatedAt=l,this.update(d,...r);const c=new ot({workflowId:e,name:t.name,document:Sn(t),...s?{owner:s}:{},updatedAt:l});return this.create(c,...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 a.NotFoundError(`No graph workflow found for workflowId '${e}'`);if(this.assertOwnership(e,r,kn(o)),r.document)return Sn(r.document);throw new a.NotFoundError(`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 vn(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(!ae(t))throw new a.ValidationError("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(!Dn(t))throw new a.ValidationError("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=kn(n);let s;try{s=await this.read(e,...r)}catch{s=null}this.assertOwnership(e,s,i);const d=new Date;if(s)return s.snapshot=t,await this.applyCanonicalWrapper(s,t,n),s.updatedAt=d,this.update(s,...r);const l=new ot({workflowId:e,snapshot:t,...i?{owner:i}:{},updatedAt:d});return await this.applyCanonicalWrapper(l,t,n),this.create(l,...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,kn(o)),t}catch{return null}}assertOwnership(e,t,o){Nn(t??null,o??null,{allowAnonymousAccess:this.allowAnonymousAccess,resourceKind:"Graph workflow",resourceId:e})}async applyCanonicalWrapper(e,t,o){if(!Dn(t))return;if(t.document.id!==e.workflowId)throw new a.ValidationError(`Document id '${t.document.id}' does not match the workflow id '${e.workflowId}' from the request path`);const n=await vn(t.document,{limits:this.limits,...this.catalogue?{catalogue:this.catalogue}:{}},o);if(!n.valid)throw new vt(n.issues);e.document=Sn(t.document),e.name=t.document.name}},e.GraphWorkflowService=i.__decorate([s.service(ot),i.__metadata("design:paramtypes",[Function])],e.GraphWorkflowService),e.GraphRunModelService=class extends s.ModelService{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:Pn(e.result)}:{},...e.error?{error:Pn(e.error)}:{},createdAt:new Date(e.createdAt),...e.startedAt?{startedAt:new Date(e.startedAt)}:{},...e.finishedAt?{finishedAt:new Date(e.finishedAt)}:{}}))(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}}},e.GraphRunModelService=i.__decorate([s.service(tt),i.__metadata("design:paramtypes",[])],e.GraphRunModelService),e.ConditionExpressionEvaluator=Vo,e.DEFAULT_GRAPH_WORKFLOW_DOCUMENT_LIMITS=Uo,e.DEFAULT_GRAPH_WORKFLOW_VALIDATION_LIMITS=ro,e.DEFAULT_PINNING_METADATA=mo,e.GRAPH_AGENT_NODES=Ko,e.GRAPH_BOUNDARY_NODES=cn,e.GRAPH_BUILT_IN_NODE_CLASSES_BY_KIND=un,e.GRAPH_BUILT_IN_NODE_MANIFESTS=on,e.GRAPH_BUILT_IN_NODE_MANIFESTS_BY_KIND=rn,e.GRAPH_CODE_DEFAULT_LANGUAGE=Ho,e.GRAPH_CODE_DEFAULT_TIMEOUT_MS=1e3,e.GRAPH_CODE_LANGUAGES=Wo,e.GRAPH_CODE_MAX_TIMEOUT_MS=lt,e.GRAPH_DEFAULT_CONCURRENCY=4,e.GRAPH_DEFAULT_MAX_FOREACH_ITERATIONS=1e3,e.GRAPH_DEFAULT_MAX_LOOP_ITERATIONS=100,e.GRAPH_DOCUMENT_FORBIDDEN_FIELD_KEYS=ao,e.GRAPH_FLOW_CONTROL_NODES=sn,e.GRAPH_LOOP_KIND={FOREACH:"core.loop.foreach",WHILE:"core.loop.while",UNTIL:"core.loop.until"},e.GRAPH_LOOP_NODES=ln,e.GRAPH_MAX_FOREACH_ITERATIONS=dt,e.GRAPH_MAX_LOOP_ITERATIONS=st,e.GRAPH_PINNING_METADATA_KEY="graph.pinnable",e.GRAPH_PLAIN_SECRET_KEYS=Xt,e.GRAPH_TRIGGER_NODES=an,e.GRAPH_UTILITY_NODES=dn,e.GRAPH_WORKFLOW_BOUNDARY=it,e.GRAPH_WORKFLOW_FORBIDDEN_FIELD_KEYS=fn,e.GraphAuthValidator=Mt,e.GraphBreakSignal=_t,e.GraphConditionEvaluator=Xo,e.GraphConnectionPolicyValidator=Zt,e.GraphConnectionValidationError=oo,e.GraphCredentialAuthorizationError=no,e.GraphCredentialReferenceValidator=eo,e.GraphCycleError=ht,e.GraphDocumentValidationError=to,e.GraphEdgeInstanceValidator=Qt,e.GraphEnvironment=Bo,e.GraphExecutionContext=jt,e.GraphExecutionEngine=bo,e.GraphExecutionError=pt,e.GraphExecutionEventEmitter=Nt,e.GraphExecutionEventFactory=It,e.GraphExecutionFrame=Ut,e.GraphExecutionSnapshotMapper=class{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:A.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}}},e.GraphInputError=ft,e.GraphLoopExecutionContext=class{constructor(e,t){this.iteration=e,this.metadata=t}},e.GraphLoopLimitError=gt,e.GraphNode=Mo,e.GraphNodeInstanceValidator=qt,e.GraphNodeManifestResolver=Ro,e.GraphNodeMethodNotFoundError=Oo,e.GraphNodeMethodRegistry=Ao,e.GraphNodeNotFoundError=Eo,e.GraphNodeRegistrationError=Io,e.GraphParameterValidator=Yt,e.GraphPinningDependencyResolver=_o,e.GraphPinningError=mt,e.GraphPinningPolicy=wo,e.GraphPinningService=go,e.GraphPortError=class extends pt{constructor(e,t){super(e,"GRAPH_PORT_ERROR",t)}},e.GraphPortSchemaResolver=class{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}}},e.GraphRunCancelledError=bt,e.GraphRunEventPublisher=On,e.GraphRunExecutor=An,e.GraphRunService=class{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 On(o,n.limits),this.executor=new An(e,t,this.publisher,{onRunCompleted:n.onRunCompleted},n.limits),this.options={...n,limits:{...S,...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.ValidationError("Graph run request must carry a workflow document with an id or a saved workflowId");if(e.workflowId&&!this.options.documentResolver)throw new a.ValidationError("Graph run requests by workflowId require a document resolver");const i=o??t??"anonymous",s=this.activeByCaller.get(i)??new Set;if(s.size>=this.options.limits.maxConcurrentRuns)throw new a.ValidationError(`Graph run rejected: the configured limit of ${this.options.limits.maxConcurrentRuns} concurrent runs per caller is exhausted`);const d=this.generateRunId(),l={runId:d,workflowId:r,ownerUser:t,status:"queued",createdAt:(new Date).toISOString()};this.executor.begin(d),await this.runStore.saveRun({...l},...n);const c=this.documentProviderFor(e,t);return s.add(d),this.activeByCaller.set(i,s),this.callerKeysByRun.set(d,i),this.executor.schedule(l,c,e.inputs??{},...n).catch(()=>{}).finally(()=>this.finishActiveRun(d)),l}async getRun(e,t,...o){const n=await this.runStore.readRun(e,...o);if(!n)throw new a.NotFoundError(`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 a.NotFoundError(`No graph run found for runId '${e}'`);return this.assertOwnership(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 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.ValidationError("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.ValidationError("Graph run request is ambiguous: supply either an unsaved workflow document or a saved workflowId, not both");if(!t&&!o)throw new a.ValidationError("Graph run request must supply either an unsaved workflow document or a saved workflowId");if(t&&!Pe(e.workflow))throw new a.ValidationError("Graph run request carries a payload that is not a canonical GraphWorkflowDocument");if(void 0!==e.inputs&&!ae(e.inputs))throw new a.ValidationError("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.ValidationError(`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:En(t)})}const o=e.workflowId;return async(...e)=>{const n=this.options.documentResolver;if(!n)throw new a.ValidationError("Graph run requests by workflowId require a document resolver");const r=await n.resolve(o,t,...e);return{document:r,fingerprint:En(r)}}}assertOwnership(e,t){Nn({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 yt("Cannot generate a graph run id: crypto.randomUUID is unavailable in this runtime",{runtime:typeof globalThis.crypto});return e.randomUUID()}},e.GraphStoreError=yt,e.GraphTopology=fo,e.GraphTopologyError=wt,e.GraphValueValidator=class{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 ft(`Missing required ${o} port '${n.name}'`);if(e&&!this.resolver.resolve(n).validate(t[n.name]))throw new ft(`Invalid value for ${o} port '${n.name}'`)}}},e.GraphWorkflowDocumentRejectedError=vt,e.GraphWorkflowDocumentValidator=lo,e.InMemoryGraphRunEventStore=class{constructor(e={}){this.events=new Map,this.listeners=new Map,this.limits={...S,...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=>!R(e.type));if(-1===t)break;e.splice(t,1)}}},e.InMemoryGraphRunStore=class{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)}},e.IsolatedVmCodeSandboxEvaluator=No,e.assertGraphResourceOwnership=Nn,e.buildGraphExecutionResult=Bt,e.builtInGraphNodeRegistrations=hn,e.checkGraphValueAgainstSchema=Ht,e.clampGraphCodeTimeoutMs=qo,e.collectLooseNodeIssues=Wt,e.composeGraphNamespace=Ot,e.createGraphValueRepository=ho,e.declaredGraphNodeMethods=e=>e.methods??[],e.decomposeGraphNamespace=Et,e.decomposeGraphNamespaces=Gt,e.defineGraphNode=Go,e.findMalformedGraphNamespaces=St,e.findUngrantedGraphNamespaces=Dt,e.graphAuthDataFromRecord=Tt,e.graphAuthDataOf=$t,e.graphNamespaceCovers=kt,e.graphNamespacePartsOf=xt,e.graphNodeConfig=Lo,e.graphRolesFromNamespaces=Pt,e.graphRunDocumentFingerprint=En,e.graphWorkflowOwnerOf=kn,e.isGraphCredentialReferenceLike=zt,e.isGraphNamespaceCacheEntryValid=At,e.isGraphResolvedWorkflow=io,e.isPinnable=yo,e.mergeGraphAuthData=Lt,e.registerBuiltInGraphNodes=(e,...t)=>{for(const o of hn())e.register(o,{},...t);return e},e.resolveGraphDynamicPorts=So,e.resolveGraphNodeManifest=Po,e.serializeGraphValueKey=co,e.validateGraphWorkflowDocumentAtBoundary=vn},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/logging"),require("@decaf-ts/ui-decorators"),require("@decaf-ts/decoration"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/db-decorators"),require("tslib"),require("@decaf-ts/core"),require("isolated-vm"),require("acorn"),require("acorn-walk"),require("typescript"),require("node:crypto")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/logging","@decaf-ts/ui-decorators","@decaf-ts/decoration","@decaf-ts/decorator-validation","@decaf-ts/db-decorators","tslib","@decaf-ts/core","isolated-vm","acorn","acorn-walk","typescript","node:crypto"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["as-graph"]={},e.decafTsLogging,e.decafTsUiDecorators,e.decafTsDecoration,e.decafTsDecoratorValidation,e.decafTsDbDecorators,e.tslib,e.decafTsCore,e.isolatedVm,e.acorn,e.acornWalk,e.typescript,e.node_crypto);
|
|
1
|
+
var e,t;e=this,t=function(e,t,o,n,r,a,i,s,d,l,c,u,p){"use strict";function h(e){var t=Object.create(null);return e&&Object.keys(e).forEach(o=>{if("default"!==o){var n=Object.getOwnPropertyDescriptor(e,o);Object.defineProperty(t,o,n.get?n:{enumerable:!0,get:()=>e[o]})}}),t.default=e,Object.freeze(t)}var f,g,m=h(l),y=h(c),w=h(u);r.ValidationKeys.REQUIRED,r.ValidationKeys.MIN,r.ValidationKeys.MIN_LENGTH,r.ValidationKeys.MAX,r.ValidationKeys.MAX_LENGTH,r.ValidationKeys.PATTERN,r.ValidationKeys.URL,r.ValidationKeys.STEP,r.ValidationKeys.DATE,r.ValidationKeys.EMAIL,r.ValidationKeys.PASSWORD,r.ValidationKeys.EQUALS,r.ValidationKeys.DIFF,r.ValidationKeys.LESS_THAN,r.ValidationKeys.LESS_THAN_OR_EQUAL,r.ValidationKeys.GREATER_THAN,r.ValidationKeys.GREATER_THAN_OR_EQUAL,(e=>{e.GRAPH="graph",e.NODE="graph.node",e.EDGE="graph.edge",e.PORT="graph.port",e.STATE="graph.state"})(f||(f={})),(e=>{e.INPUT="input",e.OUTPUT="output",e.CONNECTION="connection"})(g||(g={}));const b={};function _(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 v(e,t){b[e]=t}function N(e,t,o){const n=t?b[t]:void 0;return n?.color?n.color:e||"#64748b"}function I(e,t,o){const n=t?b[t]:void 0;return n?.icon?n.icon:e||"ti-pointer"}const E=["skip","passThroughFirstInput","emitDefaults"];function A(e){return E.includes(e)}var O,k,x,S;(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"})(O||(O={})),(e=>{e.IDLE="idle",e.RUNNING="running",e.BLOCKED="blocked",e.SUCCEEDED="succeeded",e.FAILED="failed",e.SKIPPED="skipped"})(k||(k={})),(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"})(x||(x={})),(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"})(S||(S={}));const D={maxRequestBytes:4e6,maxConcurrentRuns:32,maxEventsPerRun:1e4,maxEventPayloadBytes:256e3,executionTimeoutMs:6e5,eventReplayWindowMs:3e5},R=[S.WORKFLOW_COMPLETED,S.WORKFLOW_FAILED,S.WORKFLOW_CANCELLED];function P(e){return R.includes(e)}function C(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}function T(e){const t=n.Metadata.constr(e);if("function"==typeof t)return t;const o=e.constructor;return"function"==typeof o?o:e}function $(e){if(null!=e)return"string"==typeof e?e:e+""}function G(e,t,o){return $(e?.props?.label??e?.props?.name)??$(t?.name)??o??""}function L(e,t,o){const a=V(e,t);if(a?.model&&"function"==typeof a.model&&r.Model.isModel(a.model))return a.model;const i=n.Metadata.type(e,t);if("function"==typeof i&&r.Model.isModel(i))return i;const s=n.Metadata.getPropDesignTypes?.(e,t)?.designTypes||[];for(const e of s)if("function"==typeof e&&r.Model.isModel(e))return e;const d=o?.[r.ValidationKeys.TYPE]?.customTypes||[];for(const e of d)if("function"==typeof e&&r.Model.isModel(e))return e}function M(e,t){const o=[t,e.path??e.property].filter(Boolean).join(".");return{...e,path:o,children:e.children?.map(e=>M(e,o))}}function F(e){const t=T(e);return n.Metadata.get(t,f.NODE)}function V(e,t){const o=T(e);return n.Metadata.get(o,n.Metadata.key(f.PORT,t+""))}function j(e,t,o,r=new Set){const a=V(e,t);if(!a?.schema)return;const i=L(e,t,n.Metadata.validationFor(e,t));if(!i)return;if(r.has(i))return[];const s=new Set(r);return s.add(e),s.add(i),W(i,s).filter(e=>e.direction===o)}function U(e,t,o=new Set){const a=V(e,t);if(!a)return;const i=n.Metadata.validationFor(e,t),s=L(e,t,i);if(a.schema&&s)return;const d=r.Model.uiElementOf(e,t)||void 0,l=r.Model.uiDecorationOf(e,t,"uiprop"),c=n.Metadata.type(e,t),u=$(a.type??i?.[r.ValidationKeys.TYPE]?.customTypes?.[0]?.name??d?.props?.type??l?.type??c?.name),p=(a.expand||s&&!o.has(s))&&s?(()=>{const n=new Set(o);return n.add(e),n.add(s),W(s,n).map(e=>M(e,t))})():void 0;return{property:t,path:t,direction:a.direction,name:t,label:G(d,l,t),type:u?.toLowerCase(),required:!!i?.[r.ValidationKeys.REQUIRED],hidden:!!r.Model.uiIsHidden(e,t),designType:c?.name,element:d,prop:l,validation:i,graph:a,connectionRules:a.connectionRules,composite:!!p?.length,children:p,model:s?.name}}function B(e){return W(T(e))}function W(e,t=new Set){const o=n.Metadata.properties(e)||[],r=[];for(const n of o){const o=n+"",a=V(e,o);if(a?.schema){const n=j(e,o,a.direction,t);if(n){r.push(...n);continue}}const i=U(e,o,t);i&&r.push(i)}return r}function q(e){return e.flatMap(e=>e.children&&e.children.length?q(e.children):[e])}function H(e){const t=T(e),o=r.Model.uiModelOf(t),a=F(t)||{},i=o?.tag||t.name,s=B(t),d=((e,t)=>{const o=t.portGroups||[],r=new Map(o.map(e=>[e.property,e])),a=[],i=n.Metadata.properties(e)||[];for(const t of i){const o=t+"",i=V(e,o);if(!i?.schema)continue;if(!L(e,o,n.Metadata.validationFor(e,o)))continue;const s=r.get(o);a.push(s?{...s,toggle:s.toggle??"all"}:{property:o,toggle:"all"})}for(const e of o)a.some(t=>t.property===e.property)||a.push(e);return a.length?a:void 0})(t,a),l=a.namespaces?.length?a.namespaces:(e=>{if(null==e)return[];let t,o=e;try{o=n.Metadata.constr(e)}catch{o=e}try{t=n.Metadata.get(o,"auth-namespace")}catch{t=void 0}return C(t)??[]})(t),c=l.length?l:void 0;return{name:t.name,tag:i,kind:a.kind||i,category:a.category,color:a.color,effectiveColor:N(a.color,a.category),group:a.group,height:a.height,icon:a.icon,effectiveIcon:I(a.icon,a.category),labels:a.labels||[],maxChildren:a.maxChildren,minWidth:a.minWidth,width:a.width,shape:a.shape,cornerRadius:a.cornerRadius,sizeRules:a.sizeRules,props:o?.props,ui:o,graph:a,ports:s,portGroups:d,namespaces:c}}const K=new Set,z=new Set;function X(e,t,r){return n.Decoration.for(f.NODE).define({decorator:(e,t,r)=>{const a={kind:t?.kind||e,...t};return t=>{const i=n.apply(o.uimodel(e,r),n.metadata(f.NODE,a))(t);var s;return s=t,K.add(s),i}},args:[e,t,r]}).apply()}function J(e,t){return n.Decoration.for(f.PORT).define({decorator:(e,t)=>(o,r)=>{const a={direction:e,...t};return n.apply(n.propMetadata(n.Metadata.key(f.PORT,r),a))(o,r)},args:[e,t]}).apply()}function Y(e){return J(g.INPUT,{...e,schema:!0})}function Q(e){return J(g.OUTPUT,{...e,schema:!0})}function Z(e){return J(g.CONNECTION,e)}o.RenderingEngine.prototype.renderAsNode=(e,t,...o)=>H(e),n.Metadata.nodes=(()=>[...K]).bind(n.Metadata),n.Metadata.workflows=(()=>[...z]).bind(n.Metadata);const ee=["__proto__","prototype","constructor"];function te(e){return ee.includes(e)}function oe(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function ne(e){return null===e||"string"==typeof e||"number"==typeof e&&Number.isFinite(e)||"boolean"==typeof e}function re(e){return!!ne(e)||(Array.isArray(e)?e.every(e=>re(e)):!!oe(e)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&!te(t)&&re(e[t])))}function ae(e){if(void 0===e)return!1;if("number"==typeof e)return Number.isFinite(e);if("function"==typeof e)return!1;if(re(e))return!0;if(Array.isArray(e))return e.every(e=>ae(e));if(oe(e)){const t=Reflect.ownKeys(e);for(const o of t){if("string"!=typeof o)return!1;if(te(o))return!1;if(!ae(e[o]))return!1}return!0}return!1}function ie(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>ie(e));const t={};for(const[o,n]of Object.entries(e))t[o]=ie(n);return t}const se={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"},de={date:"date",datetime:"date-time","date-time":"date-time",duration:"duration"};function le(e){return e?se[e.toLowerCase()]??"any":"any"}function ce(e,t){const o=e[t];if(o&&"object"==typeof o)return o.value}function ue(e,t){const o=ce(e,t);return"number"==typeof o&&Number.isFinite(o)?o:void 0}function pe(e,t,o){const n=e??{},a=(e=>{const t=ce(e,r.ValidationKeys.ENUM);if(Array.isArray(t)&&t.every(ne))return t})(n);if(a)return{type:"enum",values:a};const i=(e=>{const t=e[r.ValidationKeys.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(le(e)){case"string":{const t=(e=>{if(e)return de[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=ue(t,r.ValidationKeys.MIN),a=ue(t,r.ValidationKeys.MAX);return void 0!==n&&(o.min=n),void 0!==a&&(o.max=a),o}case"boolean":return{type:"boolean"};case"array":return((e,t)=>{const o={type:"array",items:he(e,t)},n=ue(e,r.ValidationKeys.MIN),a=ue(e,r.ValidationKeys.MAX);return void 0!==n&&(o.minItems=n),void 0!==a&&(o.maxItems=a),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 he(e,t){if((e=>{const t=e[r.ValidationKeys.LIST];return!!t?.clazz?.length})(e))return{type:"model",name:fe(e)};const o=ce(e,r.ValidationKeys.TYPE);if("string"==typeof o){const e=le(o);return"model"===e?{type:"model",name:o}:{type:e}}if(t&&"array"!==t){const e=le(t);return"model"===e?{type:"model",name:t}:{type:e}}return{type:"any"}}function fe(e){const t=e[r.ValidationKeys.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 ge(e){return"workflow"===e.scope}function me(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 we(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&&re(t)}return"expression"===t&&2===Object.keys(e).length&&"string"==typeof e.expression}const be=["any","string","number","boolean","array","object","enum","model"];function _e(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&(e=>be.includes(e))(e.type)}function ve(e,t={seen:[]}){if(t.seen.includes(e))throw new a.ValidationError(`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.ValidationError("Document 'id' is required and must be a non-empty string");if("string"!=typeof e.name||!e.name)throw new a.ValidationError("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.ValidationError("Workflow port 'id' is required and must be a non-empty string");if(o.has(t.id))throw new a.ValidationError(`Workflow port '${t.id}' is declared more than once; workflow port ids must be unique`);if(void 0!==t.schema&&!_e(t.schema))throw new a.ValidationError(`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)Ne(t,r);for(const t of e.nodes)t.loop&&Ie(t,t.loop,n),t.errorBoundary&&Ee(t,t.errorBoundary,n);const i=new Set;for(const t of e.edges)Oe(t,i);for(const t of e.edges)ke(t.source,0,o,r,`Edge '${t.id}' source`),ke(t.target,0,o,r,`Edge '${t.id}' target`);if(void 0!==e.settings&&!ae(e.settings))throw new a.ValidationError("Document settings must be JSON-safe (a map of JSON-safe values)");if(void 0!==e.metadata&&!ae(e.metadata))throw new a.ValidationError("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&&!ae(e.ui))throw new a.ValidationError("Document ui must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed")}function Ne(e,t){if("string"!=typeof e.id||!e.id)throw new a.ValidationError("Node 'id' is required and must be a non-empty string");if(t.has(e.id))throw new a.ValidationError(`Node id '${e.id}' is declared more than once; node ids must be unique`);if("string"!=typeof e.kind||!e.kind)throw new a.ValidationError(`Node '${e.id}' must declare a non-empty string 'kind'`);if(void 0===e.parameters||null===e.parameters)throw new a.ValidationError(`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 a.ValidationError(`Node '${e.id}' input binding key '${t}' is not allowed (unsafe prototype-pollutant key)`);if(!we(o))throw new a.ValidationError(`Node '${e.id}' input binding for '${t}' must be a valid GraphInputBinding (edge, literal, or expression)`);if("literal"===o.mode&&!ae(o.value))throw new a.ValidationError(`Node '${e.id}' literal binding for '${t}' must contain JSON-safe values`);if("expression"===o.mode&&!o.expression)throw new a.ValidationError(`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 a.ValidationError(`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.ValidationError(`Node '${e.id}' output binding for '${t}' must be an object with enabled and alias settings`)}if(!ae(e.parameters))throw new a.ValidationError(`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.ValidationError(`Node '${e.id}' state must be an object when present`);if(!ae(e.state))throw new a.ValidationError(`Node '${e.id}' state must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed`)}}function Ie(e,t,o){if(!t.body||"object"!=typeof t.body)throw new a.ValidationError(`Node '${e.id}' loop configuration requires a body document`);if(ve(t.body,o),!(void 0===t.maxIterations||Number.isFinite(t.maxIterations)&&t.maxIterations>0))throw new a.ValidationError(`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.ValidationError(`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.ValidationError(`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 a.ValidationError(`Node '${e.id}' loop mapping key '${t}' is not allowed (unsafe prototype-pollutant key)`);Ae(n,e.id,t)}}function Ee(e,t,o){if(!t.try||"object"!=typeof t.try)throw new a.ValidationError(`Node '${e.id}' error-boundary configuration requires a try body document`);ve(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.ValidationError(`Node '${e.id}' error-boundary ${n} body must be a document`);ve(r,o)}}function Ae(e,t,o){if(!e||"object"!=typeof e)throw new a.ValidationError(`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.ValidationError(`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.ValidationError(`Node '${t}' loop mapping '${o}' referencing a node must reference a node id and a port`);break;case"literal":if(!ae(e.value))throw new a.ValidationError(`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.ValidationError(`Node '${t}' loop mapping '${o}' expression references must be non-empty expressions`);break;default:throw new a.ValidationError(`Node '${t}' loop mapping '${o}' must use a workflow, node, literal, or expression reference source`)}}function Oe(e,t){if("string"!=typeof e.id||!e.id)throw new a.ValidationError("Edge 'id' is required and must be a non-empty string");if(t.has(e.id))throw new a.ValidationError(`Edge id '${e.id}' is declared more than once; edge ids must be unique`);if(!ye(e.source))throw new a.ValidationError(`Edge '${e.id}' source endpoint is not a valid GraphEndpoint`);if(!ye(e.target))throw new a.ValidationError(`Edge '${e.id}' target endpoint is not a valid GraphEndpoint`);if("data"!==e.type&&"connection"!==e.type)throw new a.ValidationError(`Edge '${e.id}' type '${e.type+""}' is not a valid edge type (data or connection are allowed)`);if(t.add(e.id),!ae(e))throw new a.ValidationError(`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 ke(e,t,o,n,r){if(ge(e)){if(!o.has(e.port))throw new a.ValidationError(`${r} references workflow port '${e.port}' which is not declared on the document`)}else if(me(e)){if(!n.has(e.nodeId))throw new a.ValidationError(`${r} references node '${e.nodeId}' which is not part of the document`);if("string"!=typeof e.port||!e.port)throw new a.ValidationError(r+" node endpoints must reference a non-empty port identifier")}}const xe=["expression","template"],Se=["javascript","typescript","json","text"];function De(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return!(!(e=>xe.includes(e))(t.mode)||"string"!=typeof t.expression||!t.expression||void 0!==t.language&&!(e=>Se.includes(e))(t.language)||void 0!==t.metadata&&!re(t.metadata))}function Re(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 Pe(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 Ce=["trigger","loop","branching","stateful","retryable","cancellable","parallel","resource"];function Te(e){return Ce.includes(e)}function $e(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.ValidationError("Graph node manifest does not conform to the required shape");if(!ae(e))throw new a.ValidationError("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 Ge=["loadOptions","listSearch","resourceLocator","resourceMapping","validateParameter","action"];function Le(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.name&&(e=>Ge.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 Me(e){const t=e.element?.props?.value,o=t??e.prop?.value??e.validation?.defaultValue;if(void 0!==o&&"function"!=typeof o&&ae(o))try{return JSON.parse(JSON.stringify(o))}catch{return}}function Fe(e){if(e.type&&e.type in de)return{type:"string",format:de[e.type]};const t=(e=>{for(const t of[e.graph?.type,e.element?.props?.type,e.prop?.type])if("string"==typeof t&&"any"!==le(t))return t})(e);return t?pe((e=>{if(!e)return;const t=Object.entries(e).filter(([e])=>e!==r.ValidationKeys.TYPE);return Object.fromEntries(t)})(e.validation),t):pe(e.validation,e.type,e.model)}function Ve(e){const t={};for(const[o,n]of Object.entries(e.graph?.metadata??{}))ae(n)&&(t[o]=JSON.parse(JSON.stringify(n)));return Object.keys(t).length?t:void 0}function je(e){switch(e){case"output":return"output";case"connection":return"connection";default:return"input"}}function Ue(e){const t=e.graph?.handle;return"connection"!==e.direction&&"string"==typeof t&&t?t:e.path??e.property}function Be(e,t){const o={id:Ue(e),label:e.label,direction:je(e.direction),schema:Fe(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 a=Ze(e.graph?.connectionRules)??t;a&&(o.connectionPolicy=a);const i=(e=>{const t=e.element;if(!t||!ae(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)?ie(n):{}}})(e);i&&(o.element=i);const s=Ve(e);return s&&(o.metadata=s),o}function We(e){const t={type:"string",id:Ue(e),label:e.label,required:e.required};if(e.hidden)return((e,t)=>{const o={...t,type:"hidden"},n=Me(e);return void 0!==n&&(o.defaultValue=n),qe(o)})(e,t);const o=Me(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=Ve(e);if(r&&(t.metadata=r),(e=>{const t=ze(e);return"code"===t||"code-editor"===t})(e))return qe({...t,type:"code",language:Ye(e)});const a=Fe(e);switch(a.type){case"number":{const o={...t,type:"number",integer:a.integer,min:a.min,max:a.max},n=Ke(e.validation?.step);return void 0!==n&&(o.step=n),qe(o)}case"boolean":return qe({...t,type:"boolean"});case"enum":return qe({...t,type:"options",options:a.values.map(e=>({value:e,label:e+""}))});case"array":{const e={...t,type:"collection"};return void 0!==a.maxItems&&(e.maxItems=a.maxItems),qe(e)}case"object":case"model":return qe({...t,type:"object"});default:return qe({...t,type:"string",multiline:!!Xe(e)||void 0,pattern:He(e.validation?.pattern),minLength:Ke(e.validation?.minlength),maxLength:Ke(e.validation?.maxlength)})}}function qe(e){const t=e;for(const e of Object.keys(t))void 0===t[e]&&delete t[e];return e}function He(e){const t=e?.value;return"string"==typeof t?t:void 0}function Ke(e){const t=e?.value;return"number"==typeof t&&Number.isFinite(t)?t:void 0}function ze(e){const t=e.element?.tag;return"string"==typeof t&&t?t:void 0}function Xe(e){return"textarea"===ze(e)||"textarea"===(e=>{const t=e.element?.props?.type;return"string"==typeof t?t:void 0})(e)}const Je=["javascript","typescript","json","text"];function Ye(e){const t=e.element?.props?.language;return"string"==typeof t&&Je.includes(t)?t:"javascript"}function Qe(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 a=((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 a&&(o.icon=a),"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 Ze(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 a=t.maxConnections;return"number"==typeof a&&Number.isFinite(a)&&(o.maxConnections=a),Object.keys(o).length?o:void 0}function et(e,t={}){const o="function"==typeof e?e:e.constructor;if(!F(o))throw new a.ValidationError(`Node '${o?.name??e+""}' is not decorated with @node and cannot produce a manifest`);const n=H(o),r=q(B(o)),i=[],s=[],d=[],l=[],c=Ze(n.graph?.connectionRules);for(const e of r)("connection"===e.direction?d:"output"===e.direction?s:i).push(Be(e,c)),"input"===e.direction&&l.push(We(e));const u={kind:t.kind??n.kind??n.name,display:Qe(n,t),inputs:i,outputs:s,parameters:l};return d.length&&(u.connections=d),n.namespaces?.length&&(u.namespaces=n.namespaces.slice()),$e(u),u}var tt,ot;(e=>{e.READABILITY="readability",e.COMPACTNESS="compactness",e.BALANCED="balanced"})(tt||(tt={})),(e=>{e.TIGHT="tight",e.NORMAL="normal",e.COMFORTABLE="comfortable"})(ot||(ot={})),ot.TIGHT,ot.NORMAL,ot.COMFORTABLE,tt.READABILITY,ot.COMFORTABLE,tt.COMPACTNESS,ot.TIGHT,tt.BALANCED,ot.NORMAL;let nt=class extends s.BaseModel{constructor(e){super(e)}};i.__decorate([s.pk({type:String,generated:!1}),n.description("Unique graph run id"),o.uielement("ngx-decaf-crud-field",{label:"graph.run.id.label",readonly:!0}),i.__metadata("design:type",String)],nt.prototype,"runId",void 0),i.__decorate([s.column(),r.required(),s.index(),n.description("Workflow document id the run executes"),o.uilistprop("workflowId"),o.uielement("ngx-decaf-crud-field",{label:"graph.run.workflowId.label"}),i.__metadata("design:type",String)],nt.prototype,"workflowId",void 0),i.__decorate([s.column(),n.description("Owning user; absent for anonymous callers"),o.uielement("ngx-decaf-crud-field",{label:"graph.run.owner.label"}),i.__metadata("design:type",String)],nt.prototype,"owner",void 0),i.__decorate([s.column(),r.required(),r.type(String),s.index(),n.description("Current run lifecycle status"),o.uilistprop("status"),o.uielement("ngx-decaf-crud-field",{label:"graph.run.status.label",readonly:!0}),i.__metadata("design:type",String)],nt.prototype,"status",void 0),i.__decorate([s.column(),n.description("Fingerprint of the executed document"),o.uielement("ngx-decaf-crud-field",{label:"graph.run.fingerprint.label",readonly:!0}),i.__metadata("design:type",String)],nt.prototype,"documentFingerprint",void 0),i.__decorate([s.column(),n.prop(),n.description("Workflow input values keyed by input port id"),i.__metadata("design:type",Object)],nt.prototype,"inputs",void 0),i.__decorate([s.column(),n.prop(),n.description("Execution result, present on successful completion"),i.__metadata("design:type",Object)],nt.prototype,"result",void 0),i.__decorate([s.column(),n.prop(),n.description("Structured error payload, present on failure"),i.__metadata("design:type",Object)],nt.prototype,"error",void 0),i.__decorate([r.date(),s.column(),n.description("Run creation timestamp"),i.__metadata("design:type",Date)],nt.prototype,"createdAt",void 0),i.__decorate([r.date(),s.column(),n.description("Execution start timestamp, once it has started"),i.__metadata("design:type",Date)],nt.prototype,"startedAt",void 0),i.__decorate([r.date(),s.column(),n.description("Terminal-state timestamp, once the run has finished"),i.__metadata("design:type",Date)],nt.prototype,"finishedAt",void 0),nt=i.__decorate([o.uilistmodel("ngx-decaf-list-item",{icon:"ti-player-play"}),o.uimodel("ngx-decaf-crud-form"),n.description("Persistable graph run lifecycle record"),s.table("graph_run"),r.model(),i.__metadata("design:paramtypes",[Object])],nt);let rt=class extends s.BaseModel{constructor(e){super(e)}};i.__decorate([s.pk({type:String,generated:!1}),i.__metadata("design:type",String)],rt.prototype,"workflowId",void 0),i.__decorate([s.column(),i.__metadata("design:type",String)],rt.prototype,"name",void 0),i.__decorate([s.column(),i.__metadata("design:type",Object)],rt.prototype,"document",void 0),i.__decorate([s.column(),i.__metadata("design:type",String)],rt.prototype,"owner",void 0),i.__decorate([s.column(),i.__metadata("design:type",Object)],rt.prototype,"snapshot",void 0),rt=i.__decorate([s.table("graph_workflow"),r.model(),i.__metadata("design:paramtypes",[Object])],rt),v("Trigger",{color:"#3b82f6",icon:"ti-bolt"}),v("Flow Control",{color:"#f59e0b",icon:"ti-arrows-split-2"}),v("Utility",{color:"#0d9488",icon:"ti-tool"}),v("Loop",{color:"#eab308",icon:"ti-repeat"}),v("Workflow",{color:"#f97316",icon:"ti-sitemap"}),v("Pipeline",{color:"#0ea5e9",icon:"ti-git-merge"}),v("Node",{color:"#8b5cf6",icon:"ti-point-filled"}),v("Agent",{color:"#7c3aed",icon:"ti-robot"}),v("model",{color:"#3b82f6",icon:"ti-cpu"}),v("memory",{color:"#10b981",icon:"ti-database"}),v("workspace",{color:"#f59e0b",icon:"ti-folder"});const at=new Set;function it(e,t){return e.config[t]}function st(e){return Array.isArray(e)?e.map(e=>e+"").join(", "):e+""}(()=>{const e=[{key:x.NODE_ID,shouldInclude:e=>null!=it(e,x.NODE_ID),render:e=>it(e,x.NODE_ID)+""},{key:x.WORKFLOW_ID,shouldInclude:e=>null!=it(e,x.WORKFLOW_ID),render:e=>it(e,x.WORKFLOW_ID)+""},{key:x.RUN_ID,shouldInclude:e=>null!=it(e,x.RUN_ID),render:e=>it(e,x.RUN_ID)+""},{key:x.USER,shouldInclude:e=>null!=it(e,x.USER),render:e=>it(e,x.USER)+""},{key:x.ROLES,shouldInclude(e){const t=it(e,x.ROLES);return Array.isArray(t)&&t.length>0},render:e=>st(it(e,x.ROLES))},{key:x.NAMESPACES,shouldInclude(e){const t=it(e,x.NAMESPACES);return Array.isArray(t)&&t.length>0},render:e=>st(it(e,x.NAMESPACES))},{key:x.ORGANIZATION,shouldInclude:e=>null!=it(e,x.ORGANIZATION),render:e=>it(e,x.ORGANIZATION)+""},{key:x.IP,shouldInclude:e=>null!=it(e,x.IP),render:e=>it(e,x.IP)+""}];for(const o of e)at.has(o.key)||(t.logParameterRegistry.register(o),at.add(o.key))})();const dt="$workflow",lt="local",ct=1e3,ut=1e4,pt=3e4;var ht,ft;e.GraphPinningStrategy=void 0,(ht=e.GraphPinningStrategy||(e.GraphPinningStrategy={})).MANUAL="manual",ht.AUTOMATIC="automatic",ht.DISABLED="disabled",e.GraphConditionType=void 0,(ft=e.GraphConditionType||(e.GraphConditionType={})).TRUTHY="truthy",ft.FALSY="falsy",ft.EQUALS="equals",ft.NOT_EQUALS="notEquals",ft.GREATER_THAN="greaterThan",ft.GREATER_THAN_OR_EQUAL="greaterThanOrEqual",ft.LESS_THAN="lessThan",ft.LESS_THAN_OR_EQUAL="lessThanOrEqual",ft.EXISTS="exists",ft.CUSTOM="custom";class gt extends a.InternalError{constructor(e,t="GRAPH_EXECUTION_ERROR",o){super(e,gt.name,500),this.graphCode=t,this.details=o,this.name=this.constructor.name}}class mt extends gt{constructor(e){super("Graph workflow contains an unsupported cycle","GRAPH_CYCLE_ERROR",e)}}class yt extends gt{constructor(e,t){super(e,"GRAPH_INPUT_ERROR",t)}}class wt extends gt{constructor(e,t){super(e,"GRAPH_LOOP_LIMIT_ERROR",t)}}class bt extends gt{constructor(e,t){super(e,"GRAPH_PINNING_ERROR",t)}}class _t extends gt{constructor(e,t){super(e,"GRAPH_STORE_ERROR",t)}}class vt extends gt{constructor(e,t){super(e,"GRAPH_TOPOLOGY_ERROR",t)}}class Nt extends gt{constructor(e){super("Break signal","GRAPH_BREAK_SIGNAL",{value:e}),this.isBreakSignal=!0,this.name="GraphBreakSignal"}}class It extends gt{constructor(e){super(`Graph run '${e}' was cancelled`,"GRAPH_RUN_CANCELLED",{runId:e}),this.name=It.name}}class Et extends a.ValidationError{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=Et.name,this.issues=e}}class At{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 Ot{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 gt("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 kt(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(),a=o[1].split(",").map(e=>e.trim()).filter(e=>e.length>0);return n&&r&&0!==a.length?{organization:n,departments:a,role:r}:void 0}function xt(e){return`${e.organization}.${e.departments.join(",")}.${e.role}`}function St(e){if(!e||"string"!=typeof e.namespace||!e.parts)return!1;const t=kt(e.namespace);return!!t&&xt(t)===xt(e.parts)}function Dt(e,t){const o="string"==typeof e?e.trim():"";if(o){if(t)for(const e of t)if(e&&e.namespace===o&&St(e))return e.parts;return kt(o)}}function Rt(e,t,o={},n){const r=Dt(e,n),a=Dt(t,n);return!(!r||!a)&&r.organization===a.organization&&r.role===a.role&&("exact"===(o.mode??"inherit")?r.departments.length===a.departments.length&&r.departments.every((e,t)=>e===a.departments[t]):r.departments.length<=a.departments.length&&r.departments.every((e,t)=>e===a.departments[t]))}function Pt(e,t,o={},n){return e.filter(e=>!t.some(t=>Rt(t,e,o,n)))}function Ct(e){return e.filter(e=>void 0===kt(e))}function Tt(e,t){const o=new Set;for(const n of e){const e=Dt(n,t);e&&o.add(e.role)}return[...o]}function $t(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}function Gt(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 Lt(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 a=$t(e.roles);a&&(t.roles=a);const i=$t(e.namespaces);return i&&(t.namespaces=i,t.namespaceCache=Ft(i)),t}function Mt(e){return e?Lt({user:Gt(e,"user"),organization:Gt(e,"organization"),ip:Gt(e,"ip"),roles:Gt(e,"roles"),namespaces:Gt(e,"namespaces")}):{}}function Ft(e){const t=[];for(const o of e){const e=kt(o);e&&t.push({namespace:o,parts:e})}return t}function Vt(...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??Ft(o.namespaces):void 0!==o.namespaceCache&&(t.namespaceCache=o.namespaceCache));return t}class jt{constructor(e={}){this.options=e}get enabled(){return!0===this.options.enabled}validate(e,o,n,r){if(!this.enabled)return;const a=r??this.options.logger??t.Logging.for("GraphAuth"),i=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=C(e.namespaces),o=C(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 '${i}'`,s?.namespaces??[],n,s?.roles??[],a);for(const e of o.nodes)this.assertGranted(`node '${e.id}'`,e.manifest.namespaces??[],n,[],a)}assertGranted(e,t,o,n,r){const a=o.namespaces??[],i=Pt(t,a,this.options.match,o.namespaceCache),d=Tt(a,o.namespaceCache),l=n.filter(e=>!d.includes(e));if(0===i.length&&0===l.length)return;const c=[...new Set([...Ct(t),...Ct(a)])],u=[];throw i.length&&u.push("namespace(s) "+i.join(", ")),l.length&&u.push("role(s) "+l.join(", ")),r.warn(`Graph access denied for ${e} for user ${o.user??"anonymous"}: missing ${u.join(" and ")}${c.length?`; malformed namespace(s) ${c.join(", ")} failed closed`:""}`),new s.ForbiddenError(`Access to ${e} requires ${u.join(" and ")}`)}}class Ut{constructor(e){this.baseOptions=e,this.inner=t.Logging.for("GraphRun").for(this.attributeConfig(e))}attributeConfig(e){return{[x.NODE_ID]:e.nodeId,[x.WORKFLOW_ID]:e.workflowId,[x.RUN_ID]:e.runId,[x.USER]:e.user??null,[x.ROLES]:e.roles,[x.NAMESPACES]:e.namespaces,[x.ORGANIZATION]:e.organization,[x.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:S.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 Bt(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}class Wt extends s.Context{constructor(e,t,o,n,r,a,i,s,d={},l,c,u){super(),this.runId=e,this.parentRunId=t,this.workflowId=o,this.document=n,this.node=r,this.manifest=a,this.path=i,this.emitFn=s,this.metadata=d,this.engine=l,this.abortSignal=c,this.limits=u;const p=Lt(d);this.accumulate({...p,operation:"execute"});const h="string"==typeof d?.user?d.user:null;this.runLogger=new Ut({runId:e,workflowId:o,nodeId:r.id,user:h,roles:Bt(d?.roles),namespaces:Bt(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 Mt(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:S.NODE_OUTPUT,payload:e})}async log(e,t){await this.emit({type:S.NODE_OUTPUT,payload:{message:e,payload:t}})}}class qt{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 Ht(e,t,o,n,r){const a=e.valueStore.getWorkflowValues(),i={};for(const[t,o]of e.nodeResults)i[t]=o;const s=[...e.events];return{runId:e.runId,workflowId:t.id||t.name,status:n,document:t,inputs:{...o},outputs:a,nodeResults:i,events:s,startedAt:e.startedAt,finishedAt:e.finishedAt,metadata:r}}class Kt{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:S.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 zt(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 Xt{static{this._cache={}}static register(e,t){return Xt._cache[e]=t,t}static get(e){const t=e??Xt._currentFlavour;if(t)return Xt._cache[t]}static getOrFail(e){const t=Xt.get(e);if(!t)throw new gt(`No graph execution backend registered under '${e}'`,"GRAPH_EXECUTION_BACKEND_NOT_REGISTERED");return t}static get current(){return Xt.get()}static get currentFlavour(){return Xt._currentFlavour??lt}static setCurrent(e){Xt._currentFlavour=e}static list(){return Object.entries(Xt._cache).map(([e,t])=>({flavour:e,backend:t}))}static unregister(e){e&&(delete Xt._cache[e],Xt._currentFlavour===e&&(Xt._currentFlavour=void 0))}static clear(){for(const e of Object.keys(Xt._cache))delete Xt._cache[e];Xt._currentFlavour=void 0}}class Jt{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 gt(`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 gt("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 Yt(e){return"object"==typeof e&&null!==e&&"type"in e&&"code"===e.type}function Qt(e){return"object"==typeof e&&null!==e&&"op"in e&&"string"==typeof e.op}async function Zt(e,t,o){const n=o.engine?.codeSandboxEvaluator;if(!n)throw new gt("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 eo(e,t,o){if(Qt(e))return(new Jt).evaluate(e,t);throw((e,t)=>new gt(`Unknown ${t??"flow"} condition type \u2014 must be ConditionExpression (op) or CodeCondition (type: 'code')`,"GRAPH_UNKNOWN_CONDITION_TYPE",{condition:e}))(e,o)}async function to(e,t,o){return Yt(e)?Zt(e,t.input,o):eo(e,t.state,t.label)}function oo(e,t,o,n){if(e&&"object"==typeof e&&!n.has(e))if(n.add(e),Yt(e))o.push({nodeId:t,kind:"code-condition"});else if(De(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))ro(e,o,n);else if(Array.isArray(e))for(const r of e)oo(r,t,o,n);else for(const r of Object.keys(e))oo(e[r],t,o,n)}function no(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});oo(e.parameters,n,t,o),oo(e.metadata,n,t,o),oo(e.state,n,t,o),oo(e.loop,n,t,o)}function ro(e,t,o){for(const n of e.nodes??[])no(n,t,o)}function ao(e){const t=[];return ro(e,t,new Set),t}function io(e,t){if(!t)return{valid:!0};switch(t.type){case"any":default:return{valid:!0};case"string":return"string"!=typeof e?so("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}:so("number");case"boolean":return"boolean"!=typeof e?so("boolean"):{valid:!0};case"array":if(!Array.isArray(e))return so("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=io(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 so(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=io(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 so(e){return{valid:!1,message:`expected a ${e} value`}}function lo(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 co=new Set(["loop"]),uo=["secret","secrets","password","passwd","token","accessToken","refreshToken","apiKey","api_key","privateKey","credentials"];class po{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 a=!0===t.policies?.allowUndeclaredParameters,i=new Map(t.parameters.map(e=>[e.id,e]));for(const[r,s]of Object.entries(e.parameters??{})){const d=i.get(r);if(!d){a||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 a of t.parameters)void 0===(e.parameters??{})[a.id]&&(this.isParameterSatisfiedByInput(e,a.id,r)||(!0===a.required||(a.validation??[]).some(e=>"required"===e.kind))&&void 0===a.defaultValue&&o.push({code:"parameter.required-missing",path:`${n}.parameters.${a.id}`,message:`Node '${e.id}' is missing required parameter '${a.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(De(e))return{valid:!0};switch(t.type){case"string":case"code":case"expression":return"string"!=typeof e?so("string"):{valid:!0};case"number":return"number"==typeof e&&Number.isFinite(e)?{valid:!0}:so("number");case"boolean":return"boolean"!=typeof e?so("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}:so("array");case"object":case"resourceLocator":return null===e||"object"!=typeof e||Array.isArray(e)?so("object"):{valid:!0};case"credential":return lo(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 a of Object.keys(e.metadata??{}))co.has(a)?o.push({code:"metadata.key-not-allowed",path:`${n}.metadata.${a}`,message:`Node '${e.id}' metadata key '${a}' is reserved and must not be set directly`,nodeId:e.id}):Array.isArray(r)&&!r.includes(a)&&o.push({code:"metadata.key-not-allowed",path:`${n}.metadata.${a}`,message:`Node '${e.id}' metadata key '${a}' 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||A(n)||t.push({code:"disabled.invalid-behavior",path:o+".metadata.disabledBehavior",message:`Node '${e.id}' disabled behavior '${n+""}' is not one of: ${E.join(", ")}`,nodeId:e.id})}validateBindingShapes(e,t,o,n){for(const[r,a]of Object.entries(e.inputBindings??{})){if("literal"===a.mode){const i=t.inputs.find(e=>e.id===r);if(i?.schema){const t=io(a.value,i.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"!==a.mode||"string"==typeof a.expression&&a.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,a={}){const i=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 i){const o=(e.inputBindings??{})[t];o&&"literal"===o.mode&&!0!==a.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&&(i.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(A(o))return o;const n=t?.disabledBehavior;return A(n)?n:"skip"}}function ho(e){return[e.namespace??"default",e.workflowId,e.nodeId,e.version??"default",e.fingerprint].join(":")}function fo(t){return new e.GraphValueModel({id:ho(t.key),workflowId:t.key.workflowId,nodeId:t.key.nodeId,fingerprint:t.key.fingerprint,...void 0!==t.key.namespace?{namespace:t.key.namespace}:{},...void 0!==t.key.version?{version:t.key.version}:{},pinned:t.pinned,outputs:t.outputs,createdAt:new Date(t.createdAt),updatedAt:new Date(t.updatedAt),...t.expiresAt?{expiresAt:new Date(t.expiresAt)}:{},...t.metadata?{metadata:t.metadata}:{}})}function go(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}:{}}}function mo(t){return new(0,s.Repository.forModel(e.GraphValueModel,t.alias).constructor)(t)}e.GraphValueModel=class extends s.BaseModel{constructor(e){super(e)}},i.__decorate([s.pk({type:String,generated:!1}),i.__metadata("design:type",String)],e.GraphValueModel.prototype,"id",void 0),i.__decorate([s.column(),s.index(),i.__metadata("design:type",String)],e.GraphValueModel.prototype,"workflowId",void 0),i.__decorate([s.column(),s.index(),i.__metadata("design:type",String)],e.GraphValueModel.prototype,"nodeId",void 0),i.__decorate([s.column(),i.__metadata("design:type",String)],e.GraphValueModel.prototype,"fingerprint",void 0),i.__decorate([s.column(),i.__metadata("design:type",String)],e.GraphValueModel.prototype,"namespace",void 0),i.__decorate([s.column(),i.__metadata("design:type",String)],e.GraphValueModel.prototype,"version",void 0),i.__decorate([s.column(),i.__metadata("design:type",Boolean)],e.GraphValueModel.prototype,"pinned",void 0),i.__decorate([s.column(),i.__metadata("design:type",Object)],e.GraphValueModel.prototype,"outputs",void 0),i.__decorate([s.column(),i.__metadata("design:type",Date)],e.GraphValueModel.prototype,"createdAt",void 0),i.__decorate([s.column(),i.__metadata("design:type",Date)],e.GraphValueModel.prototype,"updatedAt",void 0),i.__decorate([s.column(),i.__metadata("design:type",Date)],e.GraphValueModel.prototype,"expiresAt",void 0),i.__decorate([s.column(),i.__metadata("design:type",Object)],e.GraphValueModel.prototype,"metadata",void 0),e.GraphValueModel=i.__decorate([s.table("graph_value"),r.model(),i.__metadata("design:paramtypes",[Object])],e.GraphValueModel),e.GraphValueRepository=class extends s.Repository{constructor(t){super(t,e.GraphValueModel,!0),this.runtimeValues=new Map}seedWorkflowInputs(e){this.runtimeValues.set(dt,{...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(dt)??{};o[e]=t,this.runtimeValues.set(dt,o)}getWorkflowValues(){return{...this.runtimeValues.get(dt)??{}}}snapshot(){return Object.fromEntries(this.runtimeValues.entries())}async readCached(e,...t){try{return go(await this.read(ho(e),...t))}catch{return}}async writeCached(e,t,...o){const n=ho(e);let r;try{r=await this.read(n,...o)}catch{r=void 0}r?await this.update(Object.assign(r,fo(t)),...o):await this.create(fo(t),...o)}async deleteCached(e,...t){try{await this.delete(ho(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=>go(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}},e.GraphValueRepository=i.__decorate([s.repository(e.GraphValueModel,n.DefaultFlavour),i.__metadata("design:paramtypes",[Function])],e.GraphValueRepository);class yo{static upstreamNodes(e,t,o=!1){const n=new Set,r=[e];for(;r.length;){const e=r.pop(),a=t.get(e)??[];for(const e of a)!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(),a=t.get(e)??[];for(const e of a)!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 wo{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 bt(`Node '${e}' not found in plan`);if(!this.policy.canPin(o))throw new bt(`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 bt(`Node '${o}' has no completed output to pin`);const a=r.inputs??{},i=this.dependencyFingerprints(t,o,e.result),s=this.createValueKey(e.document.id,n,a,i),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 a=this.createValueKey(e,t,o,n,r),i=await this.store.readCached(a);if(i&&i.pinned){if(i.expiresAt&&new Date(i.expiresAt)<new Date)return;return i}}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)},a=this.stableSerialize(r);return this.simpleHash(a)}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=a=>{if(n.has(a))return;n.add(a);const i=yo.upstreamNodes(a,e.incomingByNode,!1);for(const e of i)t.has(e)&&r(e);o.push(a)};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 a=o.nodeResults[t],i=a?.inputs??{},s=this.dependencyFingerprints(e,t,o);r[t]=this.computeFingerprint(e.workflowId,n,i,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 bo={enabled:!0,strategy:"manual",includeDependencies:!0};function _o(e){return!0===e?.enabled&&"disabled"!==e.strategy}class vo{canPin(e){return _o(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?{...bo,...t}:{...bo,enabled:!1}}}class No{getDependencies(e,t){return yo.upstreamNodes(t,e.incomingByNode,!1)}getPinSet(e,t){const o=this.getDependencies(e,t);return o.add(t),o}}class Io{constructor(){this.local=!0,this.codeMode="hostSide",Xt.register(lt,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 gt("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 gt("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:a}=e,i=a,s=i.frame;if(!s)throw new gt("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 i.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===O.FAILED);if(e?.error)throw new gt(e.error.message,e.error.code??"GRAPH_EXECUTION_ERROR",e.error.details);return s.finish(),await i.emit({type:S.WORKFLOW_COMPLETED,runId:l,parentRunId:r.parentRunId,workflowId:o.workflowId,path:c,status:O.SUCCEEDED,payload:{outputs:d.getWorkflowValues()}}),Ht(s,t,n,O.SUCCEEDED,r.metadata)}catch(e){if(e instanceof Nt)throw s.finish(),e;s.finish();const a=this.toErrorPayload(e);return e instanceof It||!0===r.abortSignal?.aborted?(await i.emit({type:S.WORKFLOW_CANCELLED,runId:l,parentRunId:r.parentRunId,workflowId:o.workflowId,path:c,status:O.CANCELLED,error:a}),Ht(s,t,n,O.CANCELLED,r.metadata)):(await i.emit({type:S.WORKFLOW_FAILED,runId:l,parentRunId:r.parentRunId,workflowId:o.workflowId,path:c,status:O.FAILED,error:a}),Ht(s,t,n,O.FAILED,r.metadata))}}async executeLayer(e,t,o,n,r){const a=Math.max(1,n.concurrency??4),i=[...o];for(;i.length>0;){const o=i.splice(0,a);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 a=new Date,i=[...n.path??[],o.id];await r({type:S.NODE_STARTED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:O.RUNNING}),this.emitNodeStateChanged(e,t,o,i,k.RUNNING,O.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:O.CACHED,inputs:s,outputs:n.outputs,startedAt:a,finishedAt:d,fromCache:!0,pinned:!0,events:[]};return e.recordNodeResult(l),await r({type:S.NODE_CACHE_HIT,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:O.CACHED,payload:{outputs:n.outputs}}),await r({type:S.NODE_COMPLETED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:O.SUCCEEDED,payload:{outputs:n.outputs,fromCache:!0}}),void this.emitNodeStateChanged(e,t,o,i,k.SUCCEEDED,O.SUCCEEDED,r)}}try{const d=new Wt(e.runId,n.parentRunId,t.workflowId,t.resolved.document,o.instance,o.manifest,i,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:O.SUCCEEDED,inputs:s,outputs:p,startedAt:a,finishedAt:h,events:[]};e.recordNodeResult(f),await r({type:S.NODE_COMPLETED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:O.SUCCEEDED,payload:{outputs:p}}),this.emitNodeStateChanged(e,t,o,i,k.SUCCEEDED,O.SUCCEEDED,r)}catch(d){if(d instanceof Nt)throw d;const l=new Date,c=this.toErrorPayload(d),u={nodeId:o.id,status:O.FAILED,inputs:s,error:c,startedAt:a,finishedAt:l,events:[]};if(e.recordNodeResult(u),await r({type:S.NODE_FAILED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:O.FAILED,error:c}),this.emitNodeStateChanged(e,t,o,i,k.FAILED,O.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===dt||e.isDataEdgeActive(t.id))}async skipInactiveNode(e,t,o,n,r){const a=new Date,i=[...n.path??[],o.id];await r({type:S.NODE_SKIPPED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:O.SKIPPED,payload:{reason:"branchNotSelected"}});const s={nodeId:o.id,status:O.SKIPPED,inputs:{},startedAt:a,finishedAt:new Date,events:[]};e.recordNodeResult(s),this.emitNodeStateChanged(e,t,o,i,k.SKIPPED,O.SKIPPED,r)}async executeDisabledNode(e,t,o,n,r){const a=new Date,i=[...n.path??[],o.id],s=po.disabledBehaviorOf(o.instance,t.resolved.document.settings);if(await r({type:S.NODE_SKIPPED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:O.SKIPPED,payload:{disabled:!0,behavior:s}}),"skip"===s){const n={nodeId:o.id,status:O.SKIPPED,inputs:{},startedAt:a,finishedAt:new Date,events:[]};return e.recordNodeResult(n),void this.emitNodeStateChanged(e,t,o,i,k.SKIPPED,O.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",a=n?e.valueStore.getPort(n.sourceNodeId,n.sourcePort):Object.values(d)[0];l={[r]:a}}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:O.SUCCEEDED,inputs:d,outputs:l,startedAt:a,finishedAt:new Date,events:[]};e.recordNodeResult(c),this.emitNodeStateChanged(e,t,o,i,k.SUCCEEDED,O.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 gt(`Node '${e.id}' of kind '${e.kind}' produced unknown output(s): ${r.join(", ")}`,"GRAPH_OUTPUT_VALIDATION_FAILED",{nodeId:e.id,unknownOutputs:r});const a=o.outputs.filter(e=>!0===e.required&&!(e.id in t)).map(e=>e.id);if(a.length>0)throw new gt(`Node '${e.id}' of kind '${e.kind}' did not produce required output(s): ${a.join(", ")}`,"GRAPH_OUTPUT_VALIDATION_FAILED",{nodeId:e.id,missingRequired:a});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??""}:lo(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:""}:lo(o)&&(t[e]={credentialId:o.credentialId,credentialType:o.credentialType})}return t}async resolveNodeInputs(e,t,o,n){const r={},a=(t.incomingByNode.get(o.id)??[]).filter(e=>"data"===e.type),i=new Map;for(const e of a){const t=i.get(e.targetPort)??[];t.push(e),i.set(e.targetPort,t)}for(const[t,o]of i)if(1===o.length)r[t]=e.valueStore.getPort(o[0].sourceNodeId,o[0].sourcePort);else{let n,a=!1;for(const t of o){const o=e.valueStore.getPort(t.sourceNodeId,t.sourcePort);r[t.sourcePort]=o,void 0!==o&&(n=o,a=!0)}a&&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[a,i]of Object.entries(n))r[a]=De(i)?await this.evaluateValueTemplate(i,e,t,o):i;return r}async evaluateValueTemplate(e,t,o,n){const r=this.codeSandboxEvaluator;if(!r)throw new gt(`Value template on node '${t.id}' requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator`,"GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{nodeId:t.id});const a=e.language??("expression"===e.mode?"javascript":"text"),i="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:i,language:"typescript"===a?"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 gt(`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 a=n.metadata;return await r.evaluate({code:t,language:"javascript",input:o,vars:a?.vars??void 0,item:a?.item,index:a?.index,abortSignal:n.abortSignal})}async tryPinnedValue(e,t,o,n){if(!(new vo).shouldUsePinnedValue(o))return;const r=this.createPinningService(e),a=this.computeDependencyFingerprints(e,t,o.id);return r.readPinnedValue(t.workflowId,o,n,a)}computeDependencyFingerprints(e,t,o){const n=this.createPinningService(e),r=(new No).getDependencies(t,o),a={};for(const o of r){const r=t.nodes.find(e=>e.id===o);if(r){const i=e.nodeResults.get(o),s=i?.inputs??{},d=this.computeDependencyFingerprints(e,t,o);a[o]=n.computeFingerprint(t.workflowId,r,s,d)}}return a}routeOutgoingEdges(e,t,o,n,r){const a=(t.outgoingByNode.get(o.id)??[]).filter(e=>"data"===e.type);for(const i of a){if(!Object.prototype.hasOwnProperty.call(n,i.sourcePort))continue;const a=n[i.sourcePort];e.activateDataEdge(i.id),i.targetNodeId===dt&&e.valueStore.setWorkflowOutput(i.targetPort,a),this.emitEdgeStateChanged(e,t,o,i,k.SUCCEEDED,O.SUCCEEDED,r),r({type:S.EDGE_VALUE_ROUTED,runId:e.runId,workflowId:t.workflowId,edgeId:i.id,nodeId:o.id,path:[],payload:{edge:i,value:a}}).catch(()=>{})}}emitNodeStateChanged(e,t,o,n,r,a,i){i({type:S.NODE_STATE_CHANGED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:n,status:a,payload:{nodeId:o.id,state:r,runId:e.runId,workflowId:t.workflowId,status:a}}).catch(()=>{})}emitEdgeStateChanged(e,t,o,n,r,a,i){i({type:S.EDGE_STATE_CHANGED,runId:e.runId,workflowId:t.workflowId,edgeId:n.id,nodeId:o.id,path:[],status:a,payload:{edgeId:n.id,state:r,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,status:a}}).catch(()=>{})}createPinningService(e){const t=mo(e.valueStore.getAdapter()??this.valueAdapter);return new wo(t,new vo,new No)}executionLimits(e){return{maxLoopIterations:e.maxLoopIterations??ct,maxForeachIterations:e.maxForeachIterations??ut}}assertNotAborted(e){if(!0===e.abortSignal?.aborted)throw new It(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 Eo{constructor(e){this.catalogue=e}async resolveNodes(e,t,o,...n){const r=new Map;for(const[a,i]of e.entries()){const e=`nodes[${a}]`;if(this.catalogue.has(i.kind,...n))try{const e=await this.catalogue.resolveManifest(i.kind,i,o,...n),t=this.catalogue.getExecutor(i.kind,...n);r.set(i.id,{instance:i,manifest:e,executor:t})}catch(o){t.push({code:"kind.resolution-failed",path:e+".kind",message:`Node '${i.id}' kind '${i.kind}' failed to resolve: ${o.message}`,nodeId:i.id,details:{kind:i.kind}})}else t.push({code:"kind.unknown",path:e+".kind",message:`Node '${i.id}' references kind '${i.kind}' which is not registered in the backend catalogue`,nodeId:i.id,details:{kind:i.kind}})}return r}validateEffectivePorts(e,t,o,n){const r=!0===t.policies?.allowUndeclaredParameters,a=new Set(t.inputs.map(e=>e.id)),i=new Set(t.outputs.map(e=>e.id));for(const i of Object.keys(e.inputBindings??{}))r||a.has(i)||o.push({code:"binding.unknown-port",path:`${n}.inputBindings.${i}`,message:`Node '${e.id}' input binding '${i}' does not refer to an effective input port of kind '${t.kind}'`,nodeId:e.id,details:{effectiveInputs:[...a]}});for(const a of Object.keys(e.outputBindings??{}))r||i.has(a)||o.push({code:"binding.unknown-port",path:`${n}.outputBindings.${a}`,message:`Node '${e.id}' output binding '${a}' does not refer to an effective output port of kind '${t.kind}'`,nodeId:e.id,details:{effectiveOutputs:[...i]}})}}function Ao(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&&Ao(e,t,`${o}.nodes[${r.id}].loop.body`)}}class Oo{resolveEdges(e,t,o){const n=new Set(e.inputs.map(e=>e.id)),r=new Set(e.outputs.map(e=>e.id)),a=[];for(const[i,s]of(e.edges??[]).entries()){const e=`edges[${i}]`,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),a.push(c)}return a}resolveEndpoint(e,t,o,n,r,a,i){const s=e[t];return ge(s)?("source"===t?n.has(s.port):r.has(s.port))?{nodeId:dt,port:s.port}:void a.push({code:"edge.unknown-port",path:`${i}.${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}}):me(s)?o.get(s.nodeId)?{nodeId:s.nodeId,port:s.port}:void a.push({code:"edge.unknown-node",path:`${i}.${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 a.push({code:"edge.invalid-endpoint",path:`${i}.${t}`,message:`Edge '${e.id}' ${t} endpoint is not a valid GraphEndpoint`,edgeId:e.id})}validateDirectionAndType(e,t,o,n,r,a){let i=!0;const s=t.nodeId===dt?void 0:n.get(t.nodeId),d=o.nodeId===dt?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,a),i=!1),!d||l(d)||this.hasPortDirection(d,o.port,"input")||(this.pushPortIssue(e,"target",o,d,r,a),i=!1);else{if(!s||!d)return r.push({code:"edge.boundary-routing",path:a,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:a,message:`Connection edge '${e.id}' endpoints must both be connection ports`,edgeId:e.id,details:{sourcePort:t.port,targetPort:o.port}}),!1}return i}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,a){const i="source"===t?"output":"input";r.push({code:"data"===e.type?"edge.invalid-direction":"edge.type-mismatch",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} port '${o.port}' on node '${o.nodeId}' is not an ${i} port of kind '${n.manifest.kind}'`,edgeId:e.id,nodeId:o.nodeId,details:{port:o.port,expected:i}})}}class ko{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(":"),a=n.slice(0,o),i=n.slice(o+1),s=e.nodeById.get(a),d=s?.manifest.connections?.find(e=>e.id===i)?.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 '${i}' on node '${a}' accepts at most ${l} connection(s) but has ${r.length}`,nodeId:a,edgeId:r[r.length-1].id,details:{port:i,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),a=r?.manifest.kind;if(!o.allowedNodeKinds?.length||a&&o.allowedNodeKinds.includes(a)||n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source kind '${a??"unknown"}' is not in the allowed node kinds of target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{allowedNodeKinds:o.allowedNodeKinds}}),a&&o.blockedNodeKinds?.includes(a)&&n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source kind '${a}' 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 xo{constructor(e){this.authorizer=e}async validate(e,t,o,n){const r=this.collectReferences(e,t);for(const a of t.credentials??[]){const i=r.find(e=>void 0===e.credentialType||e.credentialType===a.type);if(i){if(this.checkType(i,a))o.push({code:"credential.type-mismatch",path:n,message:`Node '${e.id}' credential '${i.credentialId}' has type '${i.credentialType}' but kind '${t.kind}' requires '${a.type}'`,nodeId:e.id,details:{credentialType:i.credentialType??"",requiredType:a.type}});else if(this.authorizer){if(!await this.authorizer.hasCredential(i)){o.push({code:"credential.not-found",path:n,message:`Node '${e.id}' references credential '${i.credentialId}' which does not exist`,nodeId:e.id,details:{credentialId:i.credentialId}});continue}await this.authorizer.authorize(i,a)||o.push({code:"credential.unauthorized",path:n,message:`Node '${e.id}' is not authorized to use credential '${i.credentialId}'`,nodeId:e.id,details:{credentialId:i.credentialId}})}}else!1!==a.required&&o.push({code:"credential.missing",path:n,message:`Node '${e.id}' does not provide the required credential of type '${a.type}'`,nodeId:e.id,details:{credentialType:a.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];lo(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))lo(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(uo);for(const[r,a]of Object.entries(e.parameters??{}))this.scanPlainSecretValue(a,[r],e,o+".parameters",n,t);for(const[r,a]of Object.entries(e.metadata??{}))this.scanPlainSecretValue(a,[r],e,o+".metadata",n,t)}scanPlainSecretValue(e,t,o,n,r,a,i=0){const s=t[t.length-1];if(r.has(s))a.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>i&&null!==e)if(Array.isArray(e))for(const s of e)this.scanPlainSecretValue(s,[...t,"[]"],o,n,r,a,i+1);else if("object"==typeof e)for(const[s,d]of Object.entries(e))this.scanPlainSecretValue(d,[...t,s],o,n,r,a,i+1)}}class So extends a.ValidationError{constructor(e,t=[]){super(e),this.issues=t,this.name=So.name}}class Do extends a.ValidationError{constructor(e,t){super(e),this.edgeId=t,this.name=Do.name}}class Ro extends s.AuthorizationError{constructor(e){super(e),this.name=Ro.name}}const Po={maxDocumentBytes:2e6,maxNestingDepth:10,maxNodes:500,maxEdges:1e3},Co=["node","definition","executor","execute","ports","component"];function To(e){if(!e||"object"!=typeof e)return!1;const t=e;return Re(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 $o(e,t){const o=[];for(const n of Object.keys(e))Co.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 Go{constructor(e){this.options=e,this.parameterValidator=new po,this.edgeValidator=new Oo,this.connectionPolicyValidator=new ko,this.nodeValidator=new Eo(e.catalogue),this.credentialValidator=new xo(e.credentialAuthorizer)}async validateOrThrow(e,...t){const o=await this.validate(e,0,...t);if(!o.valid||!o.resolved)throw new So(`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={...Po,...this.options.limits};if(!await this.validateStructure(e,r,t,n,...o))return{valid:!1,issues:n};const a=await this.nodeValidator.resolveNodes(e.nodes,n,this.options.resolutionContext,...o),i=e.nodes.filter(e=>a.has(e.id)).map(e=>a.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 i)this.parameterValidator.validate(e.instance,e.manifest,n,`nodes[${e.instance.id}]`,s.get(e.instance.id));for(const e of i)this.nodeValidator.validateEffectivePorts(e.instance,e.manifest,n,`nodes[${e.instance.id}]`);const d=this.edgeValidator.resolveEdges(e,a,n),l=new Map,c=new Map;for(const e of d){if(e.targetNodeId!==dt){const t=l.get(e.targetNodeId)??[];t.push(e),l.set(e.targetNodeId,t)}if(e.sourceNodeId!==dt){const t=c.get(e.sourceNodeId)??[];t.push(e),c.set(e.sourceNodeId,t)}}this.connectionPolicyValidator.validate({edges:d,nodeById:a},n),this.validateAcyclicity(i,d,e,n),Ao(e,n);for(const e of i)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 i)await this.credentialValidator.validate(e.instance,e.manifest,n,`nodes[${e.instance.id}]`);return this.validateCapabilities(i,n),n.length>0?{valid:!1,issues:n}:{valid:!0,issues:n,resolved:{document:e,nodes:i,edges:d,nodeById:a,incomingByNode:l,outgoingByNode:c}}}async validateStructure(e,t,o,n,...r){if(!Re(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"}),!ae(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(...$o(e,"$"));for(const t of[...e.inputs,...e.outputs])n.push(...$o(t,"ports"));for(const t of e.nodes)n.push(...$o(t,`nodes[${t.id}]`));for(const t of e.edges)n.push(...$o(t,`edges[${t.id}]`));this.validateUniqueIds(e,n),this.validateLimits(e,t,o,n);try{ve(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,a]of[["input",e.inputs],["output",e.outputs]]){const e="input"===r?o:n;for(const o of a)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 a=new Set;for(const o of e.edges)a.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}):a.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[a,i]of e){if(!i)continue;const e=await this.validate(i,t+1,...n);for(const t of e.issues)o.push({...t,path:`nodes[${r.id}].${a}.${t.path}`,nodeId:t.nodeId??r.id})}}}validateAcyclicity(e,t,o,n){const r=new Set(e.map(e=>e.instance.id)),a=new Map(e.map(e=>[e.instance.id,0]));for(const e of t)r.has(e.sourceNodeId)&&a.has(e.targetNodeId)&&a.set(e.targetNodeId,(a.get(e.targetNodeId)??0)+1);const i=[...a.entries()].filter(([,e])=>0===e).map(([e])=>e),s=[];for(;i.length>0;){const e=i.shift();s.push(e);for(const o of t){if(o.sourceNodeId!==e)continue;if(!a.has(o.targetNodeId))continue;const t=(a.get(o.targetNodeId)??1)-1;a.set(o.targetNodeId,t),0===t&&i.push(o.targetNodeId)}}if(s.length!==a.size){const e=[...a.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===dt&&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??[])Te(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}))}}}e.GraphExecutionPlanner=class extends s.Service{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"}'`),!To(e))throw new vt("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),a=this.buildPlanEdges(e),i=this.buildIncomingMap(a),s=this.buildOutgoingMap(a),d=this.topologicalLayers(r,a);return{resolved:e,workflowId:e.document.id||e.document.name,nodes:r,edges:a,layers:d,incomingByNode:i,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===dt)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===dt)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!==dt),n=new Set(o.map(e=>e.id)),r=t.filter(e=>n.has(e.sourceNodeId)&&n.has(e.targetNodeId)),a=new Map;for(const e of o)a.set(e.id,0);for(const e of r)a.set(e.targetNodeId,(a.get(e.targetNodeId)??0)+1);const i=[],s=new Set;let d=o.filter(e=>0===(a.get(e.id)??0)),l=0;for(;d.length>0;){const e={index:l++,nodes:d};i.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=(a.get(e.targetNodeId)??1)-1;if(a.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 mt({unplannedNodes:e,workflowId:o[0]?.manifest.kind})}return i}},e.GraphExecutionPlanner=i.__decorate([s.service(),i.__metadata("design:paramtypes",[])],e.GraphExecutionPlanner);const Lo=new Set(["engine","valueAdapter","codeSandboxEvaluator","workflowStore"]);function Mo(e,t){const o={};for(const[n,r]of Object.entries(e??{}))Lo.has(n)&&!t.has(n)||(o[n]=r);return o}class Fo extends s.ClientBasedService{constructor(){super()}async initialize(...t){const o=t[0];if(!o||"object"!=typeof o||!o.registry)return this._config=void 0,this._client=void 0,{config:void 0,client:void 0};const n=o.catalogue??o.registry.catalog,r=o.valueAdapter??s.Adapter.current;if(!r)throw new gt("GraphExecutionEngine requires a Decaf adapter for cached/pinned values: pass `valueAdapter` or configure one via `Adapter.setCurrent(...)`","GRAPH_VALUE_ADAPTER_MISSING");const a=o.backend??Xt.current??new Io,i={registry:o.registry,catalogue:n,planner:o.planner??new e.GraphExecutionPlanner,backend:a,valueAdapter:r,eventEmitter:o.eventEmitter??new At,documentValidator:o.documentValidator??new Go({catalogue:n,limits:o.documentLimits,credentialAuthorizer:o.credentialAuthorizer}),authValidator:new jt({enabled:!0===o.authEnabled,...o.authMatch?{match:o.authMatch}:{}}),...o.codeSandboxEvaluator?{codeSandboxEvaluator:o.codeSandboxEvaluator}:{}};this._config=o,this._client=i;const d=new Set(["engine","valueAdapter"]);o.codeSandboxEvaluator&&d.add("codeSandboxEvaluator"),o.workflowStore&&d.add("workflowStore");const l=Mo(a.config,d);return await a.initialize({...l,valueAdapter:r,...o.codeSandboxEvaluator?{codeSandboxEvaluator:o.codeSandboxEvaluator}:{},...o.workflowStore?{workflowStore:o.workflowStore}:{},engine:this}),await(o.onEngineCreated?.(this)),{config:o,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:a}=(await this.logCtx(n,"execute",!0)).for(this.execute);r.debug(`Executing workflow '${e.id||e.name}'`);const i=this.mergeOptions(o);this.assertNotAborted(i);const s=Vt(Mt(a),i.auth);i.auth=s,i.metadata={...i.metadata??{},...s};const d=i.runId??this.generateRunId();i.runId=d;const l=i.path??[],c=new Ot,u=mo(this.valueAdapter);u.seedWorkflowInputs(this.withWorkflowInputDefaults(e,t));const p=new Kt(this.emitter,c,{runId:d,parentRunId:i.parentRunId,workflowId:e.id||e.name,path:l,engine:this,...this.codeSandboxEvaluator?{codeSandboxEvaluator:this.codeSandboxEvaluator}:{}});await p.emit({type:S.VALIDATION_STARTED,status:O.PLANNING});const h=await this.documentValidator.validate(e,0,a);if(!h.valid||!h.resolved)throw await p.emit({type:S.VALIDATION_FAILED,status:O.FAILED,payload:{issues:h.issues}}),new So(`Graph workflow document '${e.id}' failed validation with ${h.issues.length} issue(s)`,h.issues);await p.emit({type:S.VALIDATION_COMPLETED,status:O.PLANNING,payload:{issues:h.issues.length}}),this.assertNotAborted(i);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 qt(d,f,u,c);return p.bindFrame(g),await p.emit({type:S.WORKFLOW_STARTED,runId:d,parentRunId:i.parentRunId,workflowId:f.workflowId,path:l,status:O.RUNNING,payload:{inputs:t}}),await p.emit({type:S.WORKFLOW_PLANNED,runId:d,parentRunId:i.parentRunId,workflowId:f.workflowId,path:l,status:O.PLANNING,payload:{layers:f.layers.length,nodes:f.nodes.length}}),await this.client.backend.execute({document:e,plan:f,inputs:t,options:i,events:p},...n)}get backend(){return this.client.backend}get backendCapabilities(){return zt(this.client.backend)}async listWorkflows(...e){const t=this.client.backend;if("supported"!==zt(t).workflows.list||"function"!=typeof t.listWorkflows)throw new gt(`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"!==zt(o).workflows.get||"function"!=typeof o.getWorkflow)throw new gt(`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=Xt.getOrFail(e);if("supported"!==zt(o).workflows.list||"function"!=typeof o.listWorkflows)throw new gt(`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=Xt.getOrFail(e);if("supported"!==zt(n).workflows.get||"function"!=typeof n.getWorkflow)throw new gt(`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=ao(e);if(0!==o.length){if("unsupported"===t.codeMode)throw new gt(`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 gt("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,S.NODE_PINNED)}async unpinNode(e){const t=this.createPinningService();await t.unpinNode(e),await this.emitPinningEvent(e.nodeId,S.NODE_UNPINNED)}createPinningService(){const e=mo(this.valueAdapter);return new wo(e,new vo,new No)}async emitPinningEvent(e,t){const o=(new Ot).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:ct,maxForeachIterations:ut,usePinnedValues:!0,writeThroughCache:!1,path:[],metadata:{},...this.defaultOptions,...e}}assertNotAborted(e){if(!0===e.abortSignal?.aborted)throw new It(e.runId??"unknown")}generateRunId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new gt("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 Vo=new Set(["process","require","module","exports","global","globalThis","Function","eval","fetch","XMLHttpRequest","WebSocket","Worker","Deno","Bun","__dispatch"]);class jo extends s.ClientBasedService{constructor(){super()}async initialize(...e){const t=e[0]??{},o=t&&"object"==typeof t?t:{};return this._config=o,this._client=d,{config:o,client:d}}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 gt("Code sandbox received empty code","GRAPH_CODE_SANDBOX_EMPTY_CODE");const n=((e,t)=>"javascript"===t?e:w.transpileModule(e,{compilerOptions:{target:w.ScriptTarget.ES2022,module:w.ModuleKind.None,strict:!0,noEmitHelpers:!0,importHelpers:!1}}).outputText.replace(/^"use strict";\s*/,""))(o,e.language??"javascript");(e=>{if(e.length>1e5)throw new gt("Code exceeds the maximum length of 100000 characters","GRAPH_CODE_SANDBOX_CODE_TOO_LONG",{length:e.length});let t;try{t=m.parse(`async function __validate() {\n${e}\n}`,{ecmaVersion:"latest",sourceType:"script"})}catch{try{t=m.parse(e,{ecmaVersion:"latest",sourceType:"module"})}catch(t){throw new gt("Code failed to parse: "+t.message,"GRAPH_CODE_SANDBOX_PARSE_ERROR",{code:e,error:t.message})}}y.full(t,e=>{const t=e;if("ImportDeclaration"===t.type)throw new gt("Imports are not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"import"});if("ExportNamedDeclaration"===t.type||"ExportDefaultDeclaration"===t.type)throw new gt("Exports are not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"export"});if("Identifier"===t.type&&"string"==typeof t.name&&Vo.has(t.name))throw new gt(`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 gt("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 gt("eval() is not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"eval"})})})(n);const r=!(e=>/\breturn\b[\s;]/.test(e))(n),a=r?n.replace(/[\s;]+$/,""):n,i={$input:e.input??{},$vars:e.vars??{},$item:e.item,$index:e.index,$node:e.nodes??{},$output:void 0},s=Object.keys(i),l=r?`return (${a});`:a,c=`"use strict";\nasync function __userFunction(${s.join(", ")}) {\n${l}\n}\n__userFunction(${s.join(", ")}).then(function(__r) { return JSON.stringify({ v: __r }); });`,u=new d.Isolate({memoryLimit:this.defaultMemoryMb}),p=await u.createContext();try{const t=p.global;e.logger&&await this.injectConsole(p,e.logger);for(const[e,o]of Object.entries(i))await t.set(e,new d.ExternalCopy(void 0===o?null:o).copyInto());let o;try{o=await u.compileScript(c,{filename:"graph-code-node.js"})}catch(e){if(!r)throw new gt("Code failed to compile: "+e.message,"GRAPH_CODE_SANDBOX_COMPILE_ERROR",{code:n,error:e.message});{const e=a,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 u.compileScript(t,{filename:"graph-code-node.js"})}catch(e){throw new gt("Code failed to compile: "+e.message,"GRAPH_CODE_SANDBOX_COMPILE_ERROR",{code:n,error:e.message})}}}const l=e.timeoutMs??this.defaultTimeoutMs;let h;try{h=await this.runBounded(o,p,l,e.abortSignal)}catch(e){if(e instanceof gt)throw e;const t=e.message;if(t.includes("timed out")||t.includes("timeout"))throw new gt(`Code execution timed out after ${l} ms`,"GRAPH_CODE_SANDBOX_TIMEOUT",{timeoutMs:l});if(t.includes("memory")||t.includes("heap"))throw new gt(`Code exceeded the memory limit of ${this.defaultMemoryMb} MB`,"GRAPH_CODE_SANDBOX_MEMORY_LIMIT",{memoryMb:this.defaultMemoryMb});throw new gt("Code execution failed: "+t,"GRAPH_CODE_SANDBOX_RUNTIME_ERROR",{code:n,error:t})}if("string"!=typeof h)throw new gt("Code sandbox returned an unexpected non-string result","GRAPH_CODE_SANDBOX_UNEXPECTED_RESULT",{result:h});return JSON.parse(h).v}finally{p.release(),u.dispose()}}async runBounded(e,t,o,n){const r=e.run(t,{timeout:o,promise:!0});r.catch(()=>{});const a=[r];let i,s;try{return a.push(new Promise((e,t)=>{i=setTimeout(()=>{t(new gt(`Code execution timed out after ${o} ms`,"GRAPH_CODE_SANDBOX_TIMEOUT",{timeoutMs:o}))},o+100)})),n&&a.push(new Promise((e,t)=>{const r=()=>{const e="timeout"===n.reason;t(new gt(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(a)}finally{i&&clearTimeout(i),s?.()}}async injectConsole(e,t){const o=new d.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(" "),a=1===n.length?n[0]:n;switch(e){case"log":case"info":default:t.info(r,a);break;case"warn":t.warn(r,a);break;case"error":t.error(r,a);break;case"debug":case"dir":case"dirxml":case"table":t.debug(r,a);break;case"trace":t.trace(r,a);break;case"group":case"groupCollapsed":t.debug("[group] "+r,a);break;case"groupEnd":t.debug("[groupEnd]",void 0);break;case"time":case"timeEnd":case"timeLog":case"count":case"countReset":t.debug(`[${e}] ${r}`,a);break;case"assert":n[0]||t.error("Assertion failed: "+r,a);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 Uo extends a.InternalError{constructor(e){super(e,Uo.name,500)}}class Bo extends a.NotFoundError{constructor(e){super(e),this.name=Bo.name}}class Wo extends a.NotFoundError{constructor(e){super(e),this.name=Wo.name}}class qo{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 Uo(`Method declaration for kind '${this.kind}' is missing a name`);if(this.declarations.has(e.name))throw new Uo(`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 Uo(`Method implementation '${e}' for kind '${this.kind}' is not a function`);if(!this.declarations.has(e))throw new Uo(`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 Uo(`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 Wo(`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 Ho(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 Ko(e,t,o){const n=Ho(t,e.itemIdPath),r=e.itemLabelPath?Ho(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 zo(e,t){switch(t){case"input":return e.inputs;case"output":return e.outputs;default:return e.connections}}function Xo(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 a=zo(o,n.direction);e.forEach((e,t)=>{const{id:o,label:i}=Ko(n,e,t),s=(d={id:o,index:t,label:i??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?ie(n.defaultPort):{id:s,label:i??s,direction:n.direction};l.id=s,l.direction=n.direction,i&&(l.label=i),a.push(l)})}else if("togglePort"===n.type){if(t[n.parameter]!==n.equals)continue;const e=ie(n.port);if(!r(e.direction,e.id))continue;zo(o,e.direction).push(e)}return o}function Jo(e,t){const o=Xo(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),ie(n)}class Yo{async resolve(e,t,o,n,r){if(o){const a=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)})(a))throw new Uo(`resolveManifest provider for kind '${e}' returned a value that does not conform to GraphResolvedNodeManifest`);if(!ae(a))throw new Uo(`resolveManifest provider for kind '${e}' returned a non-JSON-safe resolved manifest`);const i=ie(a);return!i.namespaces?.length&&t.namespaces?.length&&(i.namespaces=t.namespaces.slice()),i}return Jo(t,n.parameters??{})}}const Qo=["edge","literal","expression"];function Zo(e){return Qo.includes(e)}function en(e,t,o){if("string"!=typeof o||!o)throw new Uo(`Manifest for kind '${e}' has a ${t} with an empty port id`);if(te(o))throw new Uo(`Manifest for kind '${e}' has a ${t} with unsafe port id '${o}'`)}function tn(e){return e}function on(e){if(!e)return;const t={...e.metadata??{},...e.parameters??{},...e.state??{}};return e.loop&&(t.loop=e.loop),t}e.GraphNodeCatalogue=class extends s.Service{constructor(){super(),this.entries=new Map,this.resolver=new Yo,this.fallbackContext=new s.Context}withContext(e){return e[e.length-1]instanceof s.Context?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 Uo("Graph node registration is required");if(!e.manifest||"object"!=typeof e.manifest)throw new Uo("Graph node registration is missing a manifest");if(!e.executor||"function"!=typeof e.executor.execute)throw new Uo(`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 Uo("Graph node manifest kind is required and must be a non-empty string");const a=r.kind;if(this.entries.has(a)&&!t.replace)throw new Uo(`Graph node kind '${a}' is already registered; pass { replace: true } to replace it`);try{$e(r)}catch(e){throw new Uo(`Manifest for kind '${a}' 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(en(e,t+" port",r?.id),o.has(r.id))throw new Uo(`Manifest for kind '${e}' declares duplicate static ${t} port id '${r.id}'`);if(o.add(r.id),void 0!==r.defaultMode&&!Zo(r.defaultMode))throw new Uo(`Manifest for kind '${e}' declares invalid default binding mode '${r.defaultMode+""}' on ${t} port '${r.id}'`)}}})(a,r);const i=((e,t)=>{const o=new Set;for(const n of t.parameters){const t=n?.id;if("string"!=typeof t||!t)throw new Uo(`Manifest for kind '${e}' has a parameter with an empty id`);if(te(t))throw new Uo(`Manifest for kind '${e}' has a parameter with unsafe id '${t}'`);if(o.has(t))throw new Uo(`Manifest for kind '${e}' declares duplicate parameter id '${t}'`);o.add(t)}return o})(a,r);((e,t,o)=>{for(const n of t.dynamicPorts??[]){if(!n||"string"!=typeof n.parameter||!n.parameter)throw new Uo(`Manifest for kind '${e}' has a dynamic-port rule without a parameter reference`);if(!o.has(n.parameter))throw new Uo(`Manifest for kind '${e}' has a dynamic-port rule referencing missing parameter '${n.parameter}'`);if("togglePort"===n.type){if(!n.port)throw new Uo(`Manifest for kind '${e}' has a togglePort rule without a port`);en(e,"togglePort rule port",n.port.id)}if("repeatFromParameter"===n.type&&"string"!=typeof n.portIdTemplate)throw new Uo(`Manifest for kind '${e}' has a repeatFromParameter rule without a portIdTemplate`)}})(a,r,i),((e,t)=>{for(const o of t.credentials??[]){if(!Pe(o))throw new Uo(`Manifest for kind '${e}' has a malformed credential requirement`);if(!o.type)throw new Uo(`Manifest for kind '${e}' has a credential requirement with an empty type`)}})(a,r),((e,t)=>{for(const o of t.methods??[])if(!Le(o))throw new Uo(`Manifest for kind '${e}' has a malformed method declaration`)})(a,r);const s=new qo(a,r.methods??[],e.methods??{});return this.entries.set(a,{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 Uo("Graph executor kind is required");if(!t||"function"!=typeof t.execute)throw new Uo(`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 a={kind:e,display:{name:e},inputs:[],outputs:[],parameters:[],policies:{allowUndeclaredParameters:!0,allowUnknownOutputs:!0}};return this.entries.set(e,{registration:{manifest:a,executor:t},methods:new qo(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 Bo(`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),ie(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,a=[];for(const e of o){if(r&&!r.has(e))continue;const o=this.getManifest(e,...t);n&&!n.has(o.display.category??"")||a.push(o)}return a}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)}},e.GraphNodeCatalogue=i.__decorate([s.service(),i.__metadata("design:paramtypes",[])],e.GraphNodeCatalogue),e.GraphNodeExecutorRegistry=class extends s.Service{constructor(t=new e.GraphNodeCatalogue){super(),this.catalogue=t}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 gt("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 Bo)throw new gt(`No graph executor registered for kind '${e}'`,"GRAPH_EXECUTOR_NOT_FOUND",{kind:e});throw t}}},e.GraphNodeExecutorRegistry=i.__decorate([s.service(),i.__metadata("design:paramtypes",[e.GraphNodeCatalogue])],e.GraphNodeExecutorRegistry),e.GraphNodeExecutorResolver=class extends s.Service{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)}},e.GraphNodeExecutorResolver=i.__decorate([s.service(),i.__metadata("design:paramtypes",[Function,Object])],e.GraphNodeExecutorResolver);class nn extends r.Model{constructor(e){super(),r.Model.fromModel(this,e)}execute(e,t){throw new gt(`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)}}function rn(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+""}}e.BreakFlowNode=class extends nn{execute(e,t){throw new Nt(e.inputs.value)}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.break.fields.value.label",placeholder:"graph.node.flow_control.break.fields.value.placeholder",type:"textarea"}),Y({handle:"value"}),i.__metadata("design:type",Object)],e.BreakFlowNode.prototype,"value",void 0),e.BreakFlowNode=i.__decorate([X("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"}}),r.model()],e.BreakFlowNode),e.ErrorBoundaryFlowNode=class extends nn{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 gt("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"]}),a=Object.values(r.nodeResults).find(e=>e.status===O.FAILED);if(a)throw new gt(a.error?.message??"error boundary try body failed",a.error?.code??"GRAPH_ERROR_BOUNDARY",a.error?.details);return{result:r.outputs.result??r.outputs}}catch(r){let a=r;if(o.catch){const i=await n.execute(o.catch,{...e.inputs,error:rn(r)},{parentRunId:t.runId,path:[...t.path,"catch"]});a=i.outputs.error??i.outputs}return{error:a}}finally{o.finally&&await n.execute(o.finally,e.inputs,{parentRunId:t.runId,path:[...t.path,"finally"]})}}},i.__decorate([r.required(),o.uielement("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"}),Y({handle:"value"}),i.__metadata("design:type",Object)],e.ErrorBoundaryFlowNode.prototype,"value",void 0),i.__decorate([Q({handle:"result"}),i.__metadata("design:type",Object)],e.ErrorBoundaryFlowNode.prototype,"result",void 0),i.__decorate([Q({handle:"error"}),i.__metadata("design:type",Object)],e.ErrorBoundaryFlowNode.prototype,"error",void 0),e.ErrorBoundaryFlowNode=i.__decorate([X("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}}),r.model()],e.ErrorBoundaryFlowNode),e.HumanApprovalFlowNode=class extends nn{execute(e){const t=e.inputs.value??e.inputs;return!1===this.approved?{rejected:t}:{approved:t}}},i.__decorate([r.required(),Y({handle:"value"}),i.__metadata("design:type",Object)],e.HumanApprovalFlowNode.prototype,"value",void 0),i.__decorate([o.uielement("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"}),Y({handle:"message",userControlled:!0}),i.__metadata("design:type",String)],e.HumanApprovalFlowNode.prototype,"message",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.human_approval.fields.approved.label",type:"checkbox"}),Y({handle:"approved",userControlled:!0}),i.__metadata("design:type",Boolean)],e.HumanApprovalFlowNode.prototype,"approved",void 0),i.__decorate([Q({handle:"approved"}),i.__metadata("design:type",Object)],e.HumanApprovalFlowNode.prototype,"approvedOut",void 0),i.__decorate([Q({handle:"rejected"}),i.__metadata("design:type",Object)],e.HumanApprovalFlowNode.prototype,"rejectedOut",void 0),e.HumanApprovalFlowNode=i.__decorate([X("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}}),r.model()],e.HumanApprovalFlowNode),e.IfFlowNode=class extends nn{execute(e,t){const o=e.inputs,n=o.value??o;if(!this.condition)throw new gt("If node has no condition configured","GRAPH_IF_NO_CONDITION",{input:o});if(Yt(this.condition))return Zt(this.condition,o,t).then(e=>this.route(e,n));const r=eo(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 gt("If node condition evaluated to false and the else branch is disabled","GRAPH_IF_ELSE_DISABLED",{condition:this.condition})}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.value.label",placeholder:"graph.node.flow_control.if.fields.value.placeholder",type:"textarea"}),Y({handle:"value"}),i.__metadata("design:type",Object)],e.IfFlowNode.prototype,"value",void 0),i.__decorate([r.required(),Q({handle:"then"}),i.__metadata("design:type",Object)],e.IfFlowNode.prototype,"then",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.condition.label",placeholder:"graph.node.flow_control.if.fields.condition.placeholder",type:"code"}),Y({handle:"condition",userControlled:!0,type:"object"}),i.__metadata("design:type",Object)],e.IfFlowNode.prototype,"condition",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.else.label",type:"checkbox"}),Y({handle:"else",userControlled:!0}),i.__metadata("design:type",Boolean)],e.IfFlowNode.prototype,"else",void 0),e.IfFlowNode=i.__decorate([X("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"}}),r.model()],e.IfFlowNode),e.SwitchFlowNode=class extends nn{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,a=r.value??r,i=((e,t)=>t===e||"object"!=typeof t||null===t||Array.isArray(t)?e:{...t,...e})(r,a);for(const e of n)if(await to(e.condition,{input:r,state:i,label:"switch case"},t))return{[e.outputPort]:a};if(!0!==o.hasDefault)throw new gt("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]:a}}static applyMetadata(e){const t=H(this),o=e.defaultPort??"default",n=!0===e.hasDefault,r=t.ports.filter(t=>!e.cases.some(e=>e.outputPort===t.property)),a=r.filter(e=>e.property!==o),i=r.find(e=>e.property===o),s=[...a,...e.cases.map(e=>({property:e.outputPort,name:e.label,direction:g.OUTPUT,label:e.label,required:!1,hidden:!1,path:e.outputPort}))];return n&&i&&s.push(i),{ports:s,size:_(t,{cases:e.cases.length}),dataPatch:{switchMetadata:e}}}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.value.label",placeholder:"graph.node.flow_control.switch.fields.value.placeholder",type:"textarea"}),Y({handle:"value"}),i.__metadata("design:type",Object)],e.SwitchFlowNode.prototype,"value",void 0),i.__decorate([r.required(),Q({handle:"default"}),i.__metadata("design:type",Object)],e.SwitchFlowNode.prototype,"default",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.cases.label",type:"collection"}),i.__metadata("design:type",Object)],e.SwitchFlowNode.prototype,"cases",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.hasDefault.label",type:"checkbox"}),i.__metadata("design:type",Boolean)],e.SwitchFlowNode.prototype,"hasDefault",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.defaultPort.label",type:"text"}),i.__metadata("design:type",String)],e.SwitchFlowNode.prototype,"defaultPort",void 0),e.SwitchFlowNode=i.__decorate([X("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"}}),r.model()],e.SwitchFlowNode);const an={maxDocumentBytes:2e6,maxNestingDepth:10,maxNodes:500,maxEdges:1e3},sn=t.LoggedEnvironment.accumulate({graph:{workflows:{limits:{...an},allowAnonymousAccess:!1},execution:{maxCodeTimeoutMs:pt}}});function dn(e,t){const o="number"==typeof t?t:Number(t),n=Number.isFinite(o)&&o>0?o:pt,r="number"==typeof e?e:Number(e);return Number.isFinite(r)&&r>0?Math.min(Math.floor(r),n):1e3}const ln=["javascript","typescript"],cn="javascript";e.CodeInputSchema=class extends r.Model{constructor(){super(...arguments),this.language=cn}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.code.fields.language.label",type:"select"}),r.option([...ln]),r.type(String),i.__metadata("design:type",String)],e.CodeInputSchema.prototype,"language",void 0),i.__decorate([r.required(),o.uielement("code-editor",{label:"graph.node.utility.code.fields.code.label",placeholder:"graph.node.utility.code.fields.code.placeholder"}),Y({handle:"code"}),i.__metadata("design:type",String)],e.CodeInputSchema.prototype,"code",void 0),i.__decorate([o.hidden(),Y({handle:"data"}),i.__metadata("design:type",Object)],e.CodeInputSchema.prototype,"data",void 0),e.CodeInputSchema=i.__decorate([r.model()],e.CodeInputSchema),e.CodeNode=class extends nn{async execute(e,t){const o=e.inputs,n=this.input,r=o.code??e.parameters?.code??n?.code??this.defaultCode,a=n?.language??cn;if(!r||"string"!=typeof r||0===r.trim().length)throw new yt("Code node has no code to execute (input.code is empty)",{input:o});const i=t.engine?.codeSandboxEvaluator;if(!i)throw new gt("Code node execution requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator","GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{code:r});const s=sn.graph.execution?.maxCodeTimeoutMs,d="number"==typeof s&&Number.isFinite(s)&&s>0?s:pt,l=dn(this.timeoutMs,d),c=t.metadata,u={code:r,language:a,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:a,length:r.length,timeoutMs:l});const p=await i.evaluate(u);return await t.log("Code node executed",{hasResult:void 0!==p}),{result:p}}},i.__decorate([r.required(),Y({handle:"input",model:e.CodeInputSchema}),i.__metadata("design:type",e.CodeInputSchema)],e.CodeNode.prototype,"input",void 0),i.__decorate([r.min(1),r.max(pt),o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.code.fields.timeoutMs.label",type:"number"}),Y({handle:"timeoutMs"}),i.__metadata("design:type",Number)],e.CodeNode.prototype,"timeoutMs",void 0),i.__decorate([o.uielement("code-editor",{label:"graph.node.utility.code.fields.defaultCode.label",placeholder:"graph.node.utility.code.fields.defaultCode.placeholder"}),Y({handle:"defaultCode",userControlled:!0}),i.__metadata("design:type",String)],e.CodeNode.prototype,"defaultCode",void 0),i.__decorate([r.required(),Q({handle:"result"}),i.__metadata("design:type",Object)],e.CodeNode.prototype,"result",void 0),e.CodeNode=i.__decorate([X("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"}}),r.model()],e.CodeNode),e.DelayFlowNode=class extends nn{execute(e){return{value:e.inputs.value??e.inputs}}},i.__decorate([r.required(),Y({handle:"value"}),i.__metadata("design:type",Object)],e.DelayFlowNode.prototype,"value",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.delay.fields.timeoutMs.label",type:"number"}),Y({handle:"timeoutMs"}),i.__metadata("design:type",Number)],e.DelayFlowNode.prototype,"timeoutMs",void 0),i.__decorate([r.required(),Q({handle:"value"}),i.__metadata("design:type",Object)],e.DelayFlowNode.prototype,"valueOut",void 0),e.DelayFlowNode=i.__decorate([X("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"}}),r.model()],e.DelayFlowNode),e.LogFlowNode=class extends nn{execute(e,t){const o=e.inputs.value,n=this.level??"info";return t.logger[n](this.message??"Log node",{value:o}),{value:o}}},i.__decorate([r.required(),Y({handle:"value"}),i.__metadata("design:type",Object)],e.LogFlowNode.prototype,"value",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.log.fields.message.label",placeholder:"graph.node.utility.log.fields.message.placeholder",type:"textarea"}),Y({handle:"message"}),i.__metadata("design:type",String)],e.LogFlowNode.prototype,"message",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.log.fields.level.label",placeholder:"graph.node.utility.log.fields.level.placeholder",type:"text"}),Y({handle:"level",userControlled:!0}),i.__metadata("design:type",String)],e.LogFlowNode.prototype,"level",void 0),i.__decorate([r.required(),Q({handle:"value"}),i.__metadata("design:type",Object)],e.LogFlowNode.prototype,"valueOut",void 0),e.LogFlowNode=i.__decorate([X("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"}}),r.model()],e.LogFlowNode),e.MapNode=class extends nn{execute(e){return{result:{mapped:e.inputs.value??e.inputs}}}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.map.fields.value.label",placeholder:"graph.node.utility.map.fields.value.placeholder",type:"textarea"}),Y({handle:"value"}),i.__metadata("design:type",Object)],e.MapNode.prototype,"value",void 0),i.__decorate([r.required(),Q({handle:"result"}),i.__metadata("design:type",Object)],e.MapNode.prototype,"result",void 0),e.MapNode=i.__decorate([X("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:{}}}),r.model()],e.MapNode),e.UtilityLogNode=class extends nn{execute(e,t){const o=e.inputs.value,n=this.level??"info";return t.logger[n](this.message??"Log node",{value:o}),{value:o}}},i.__decorate([r.required(),Y({handle:"value"}),i.__metadata("design:type",Object)],e.UtilityLogNode.prototype,"value",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.utility_log.fields.message.label",placeholder:"graph.node.utility.utility_log.fields.message.placeholder",type:"textarea"}),Y({handle:"message"}),i.__metadata("design:type",String)],e.UtilityLogNode.prototype,"message",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.utility_log.fields.level.label",placeholder:"graph.node.utility.utility_log.fields.level.placeholder"}),Y({handle:"level",userControlled:!0,type:"string"}),i.__metadata("design:type",String)],e.UtilityLogNode.prototype,"level",void 0),i.__decorate([r.required(),Q({handle:"value"}),i.__metadata("design:type",Object)],e.UtilityLogNode.prototype,"valueOut",void 0),e.UtilityLogNode=i.__decorate([X("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"}}),r.model()],e.UtilityLogNode),e.ChatTriggerNode=class extends nn{execute(e){return{message:e.inputs.message??null,sessionId:e.inputs.sessionId??null,userId:e.inputs.userId??null}}},i.__decorate([r.required(),Q({handle:"message"}),i.__metadata("design:type",String)],e.ChatTriggerNode.prototype,"message",void 0),i.__decorate([r.required(),Q({handle:"sessionId"}),i.__metadata("design:type",String)],e.ChatTriggerNode.prototype,"sessionId",void 0),i.__decorate([r.required(),Q({handle:"userId"}),i.__metadata("design:type",String)],e.ChatTriggerNode.prototype,"userId",void 0),e.ChatTriggerNode=i.__decorate([X("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"}}}),r.model()],e.ChatTriggerNode),e.EventTriggerNode=class extends nn{execute(e){return{payload:e.inputs.payload??null}}},i.__decorate([r.required(),Q({handle:"payload"}),i.__metadata("design:type",Object)],e.EventTriggerNode.prototype,"payload",void 0),e.EventTriggerNode=i.__decorate([X("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"}}}),r.model()],e.EventTriggerNode),e.FormTriggerNode=class extends nn{execute(e){return{payload:e.inputs.payload??null}}},i.__decorate([r.required(),Y({handle:"schema"}),o.uielement("ngx-decaf-model-builder",{label:"graph.node.trigger.form.fields.schema.label",placeholder:"graph.node.trigger.form.fields.schema.placeholder"}),i.__metadata("design:type",Object)],e.FormTriggerNode.prototype,"schema",void 0),i.__decorate([r.required(),Q({handle:"payload"}),i.__metadata("design:type",Object)],e.FormTriggerNode.prototype,"payload",void 0),e.FormTriggerNode=i.__decorate([X("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:[]}}}),r.model()],e.FormTriggerNode),e.ManualTriggerNode=class extends nn{execute(e){return{payload:e.inputs.payload??null}}},i.__decorate([r.required(),Q({handle:"payload"}),i.__metadata("design:type",Object)],e.ManualTriggerNode.prototype,"payload",void 0),e.ManualTriggerNode=i.__decorate([X("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:{}}}}),r.model()],e.ManualTriggerNode),e.ScheduleTriggerNode=class extends nn{execute(e){return{payload:e.inputs.payload??null}}},i.__decorate([r.required(),Y({handle:"cron"}),o.uielement("app-cron-selector-field",{label:"graph.node.trigger.schedule.fields.cron.label",placeholder:"graph.node.trigger.schedule.fields.cron.placeholder"}),i.__metadata("design:type",String)],e.ScheduleTriggerNode.prototype,"cron",void 0),i.__decorate([r.required(),Q({handle:"payload"}),i.__metadata("design:type",Object)],e.ScheduleTriggerNode.prototype,"payload",void 0),e.ScheduleTriggerNode=i.__decorate([X("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"}}}),r.model()],e.ScheduleTriggerNode),e.WebhookTriggerNode=class extends nn{execute(e){return{payload:e.inputs.payload??null}}},i.__decorate([r.required(),Y({handle:"schema"}),o.uielement("ngx-decaf-model-builder",{label:"graph.node.trigger.webhook.fields.schema.label",placeholder:"graph.node.trigger.webhook.fields.schema.placeholder"}),i.__metadata("design:type",Object)],e.WebhookTriggerNode.prototype,"schema",void 0),i.__decorate([r.required(),Q({handle:"payload"}),i.__metadata("design:type",Object)],e.WebhookTriggerNode.prototype,"payload",void 0),e.WebhookTriggerNode=i.__decorate([X("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"}}}),r.model()],e.WebhookTriggerNode),e.AgentNode=class extends nn{execute(e){return{response:"[Agent response] "+(e.inputs.prompt??""),actions:[]}}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.agent.agent.fields.prompt.label",placeholder:"graph.node.agent.agent.fields.prompt.placeholder",type:"textarea"}),Y({handle:"prompt"}),i.__metadata("design:type",String)],e.AgentNode.prototype,"prompt",void 0),i.__decorate([r.required(),Q({handle:"response"}),i.__metadata("design:type",String)],e.AgentNode.prototype,"response",void 0),i.__decorate([r.required(),Q({handle:"actions"}),i.__metadata("design:type",Array)],e.AgentNode.prototype,"actions",void 0),i.__decorate([Z({category:"model",handle:"model"}),i.__metadata("design:type",Object)],e.AgentNode.prototype,"model",void 0),i.__decorate([Z({category:"memory",handle:"memory"}),i.__metadata("design:type",Object)],e.AgentNode.prototype,"memory",void 0),i.__decorate([Z({category:"workspace",handle:"workspace"}),i.__metadata("design:type",Object)],e.AgentNode.prototype,"workspace",void 0),e.AgentNode=i.__decorate([X("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"}}),r.model()],e.AgentNode);const un=[e.AgentNode];function pn(e,t,o,n){const r=t??o;if(null==e)return Math.min(o,r);const a=Number(e);if(!Number.isFinite(a)||0>=a)throw new yt(n+" loop maxIterations must be a positive finite number");return Math.min(Math.floor(a),r)}function hn(e,t,o){const n=t.node.loop,r=t.metadata?.loop;if(!n?.body&&!r?.body)throw new yt(o+" node is missing loop configuration (instance.loop.body)");const a=t=>{const o=e[t]??n?.[t]??r?.[t],a=Number(o);return void 0!==o&&Number.isFinite(a)?a:void 0},i=t=>{const o=e[t]??r?.[t];return"string"==typeof o?o:void 0};return{body:n?.body??r?.body,maxIterations:a("maxIterations"),timeoutMs:a("timeoutMs"),concurrency:a("concurrency"),condition:e.condition??r?.condition,inputPort:i("inputPort"),outputPort:i("outputPort"),itemPort:i("itemPort"),resultPort:i("resultPort"),statePort:i("statePort"),slice:a("slice")}}e.GraphForeachLoopNode=class extends nn{async execute(e,t){const o=hn(this,t,"foreach"),n=e.inputs,r=n.items,a=pn(o.maxIterations,t.limits?.maxForeachIterations,1e3,"foreach");if(!Array.isArray(r))throw new yt("foreach input 'items' must be an array");const i=t.engine;if(!i)throw new gt("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>a)throw new wt(`foreach exceeded max iterations (${l} > ${a})`);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:S.LOOP_STARTED});for(let e=0;l>e;e++){await t.emit({type:S.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 i.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 Nt){const n=o.details?.value;void 0!==n&&f.push(n),m=!0,await t.emit({type:S.LOOP_ITERATION_COMPLETED,iteration:e,metadata:{broken:!0}});break}throw o}await t.emit({type:S.LOOP_ITERATION_COMPLETED,iteration:e})}await t.emit({type:S.LOOP_COMPLETED,metadata:{broken:m}});const y={results:f,completed:f,iterations:f.length,broken:m};return void 0!==g&&(y[p]=g),y}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.items.label",placeholder:"graph.node.loop.foreach.fields.items.placeholder",type:"textarea"}),Y({handle:"items"}),i.__metadata("design:type",Array)],e.GraphForeachLoopNode.prototype,"items",void 0),i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.slice.label",placeholder:"graph.node.loop.foreach.fields.slice.placeholder",type:"number"}),Y({handle:"slice"}),i.__metadata("design:type",Number)],e.GraphForeachLoopNode.prototype,"slice",void 0),i.__decorate([r.required(),Q({handle:"item"}),i.__metadata("design:type",Object)],e.GraphForeachLoopNode.prototype,"item",void 0),i.__decorate([r.required(),Z({handle:"loop",connectionRules:{allowSelf:!0,maxConnections:1}}),i.__metadata("design:type",Object)],e.GraphForeachLoopNode.prototype,"loop",void 0),i.__decorate([r.required(),Q({handle:"completed"}),i.__metadata("design:type",Array)],e.GraphForeachLoopNode.prototype,"completed",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.maxIterations.label",type:"number"}),Y({handle:"maxIterations",userControlled:!0}),i.__metadata("design:type",Number)],e.GraphForeachLoopNode.prototype,"maxIterations",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.condition.label",type:"code"}),Y({handle:"condition",userControlled:!0}),i.__metadata("design:type",Object)],e.GraphForeachLoopNode.prototype,"condition",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.itemPort.label",type:"text"}),Y({handle:"itemPort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphForeachLoopNode.prototype,"itemPort",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.resultPort.label",type:"text"}),Y({handle:"resultPort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphForeachLoopNode.prototype,"resultPort",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.statePort.label",type:"text"}),Y({handle:"statePort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphForeachLoopNode.prototype,"statePort",void 0),e.GraphForeachLoopNode=i.__decorate([X("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}}}),r.model()],e.GraphForeachLoopNode);class fn{constructor(){this.expressionEvaluator=new Jt}evaluate(t,o){if(this.isConditionExpression(t))return this.expressionEvaluator.evaluate(t,o);const n=this.resolveValue(t.left,o),r=t.right;switch(t.type){case e.GraphConditionType.TRUTHY:return!!n;case e.GraphConditionType.FALSY:return!n;case e.GraphConditionType.EQUALS:return n===r;case e.GraphConditionType.NOT_EQUALS:return n!==r;case e.GraphConditionType.GREATER_THAN:return Number(n)>Number(r);case e.GraphConditionType.GREATER_THAN_OR_EQUAL:return Number(n)>=Number(r);case e.GraphConditionType.LESS_THAN:return Number(r)>Number(n);case e.GraphConditionType.LESS_THAN_OR_EQUAL:return Number(r)>=Number(n);case e.GraphConditionType.EXISTS:return null!=n;case e.GraphConditionType.CUSTOM:throw new gt("Custom condition evaluators are not supported in v1","GRAPH_CUSTOM_CONDITION_UNSUPPORTED");default:throw new gt(`Unknown condition type '${t.type}'`,"GRAPH_UNKNOWN_CONDITION_TYPE",{condition:t})}}async evaluateAsync(e,t,o,n){return Yt(e)?Zt(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}}function gn(e,t,o,n={}){return{id:e,label:t,direction:o,...n}}function mn(e){const t=e,o=F(t),n=o?.metadata?.title;return et(t,n?{name:n}:{})}e.GraphUntilLoopNode=class extends nn{async execute(e,t){const o=hn(this,t,"until"),n=e.inputs,r=pn(o.maxIterations,t.limits?.maxLoopIterations,100,"until"),a=o.condition;if(!a)throw new yt("until node is missing a condition");const i=o.statePort??"state",s=o.inputPort??i,d=o.outputPort??i,l=o.body,c=t.engine;if(!c)throw new gt("until node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");let u=n.state,p=0;await t.emit({type:S.LOOP_STARTED});let h=!1;do{if(p>=r)throw await t.emit({type:S.LOOP_LIMIT_REACHED,iteration:p}),new wt(`until loop exceeded max iterations (${r})`);await t.emit({type:S.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:S.LOOP_ITERATION_COMPLETED,iteration:p});const e=await(new fn).evaluateAsync(a,u,t,{...n,state:u});await t.emit({type:S.LOOP_CONDITION_EVALUATED,iteration:p,payload:{result:e}}),p++,h=e}while(!h);return await t.emit({type:S.LOOP_COMPLETED}),{state:u,iterations:p}}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.state.label",placeholder:"graph.node.loop.until.fields.state.placeholder",type:"textarea"}),Y({handle:"state"}),i.__metadata("design:type",Object)],e.GraphUntilLoopNode.prototype,"state",void 0),i.__decorate([r.required(),Q({handle:"state"}),i.__metadata("design:type",Object)],e.GraphUntilLoopNode.prototype,"stateOut",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.maxIterations.label",type:"number"}),Y({handle:"maxIterations",userControlled:!0}),i.__metadata("design:type",Number)],e.GraphUntilLoopNode.prototype,"maxIterations",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.condition.label",type:"code"}),Y({handle:"condition",userControlled:!0}),i.__metadata("design:type",Object)],e.GraphUntilLoopNode.prototype,"condition",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.statePort.label",type:"text"}),Y({handle:"statePort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphUntilLoopNode.prototype,"statePort",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.inputPort.label",type:"text"}),Y({handle:"inputPort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphUntilLoopNode.prototype,"inputPort",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.outputPort.label",type:"text"}),Y({handle:"outputPort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphUntilLoopNode.prototype,"outputPort",void 0),e.GraphUntilLoopNode=i.__decorate([X("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}}}}),r.model()],e.GraphUntilLoopNode),e.GraphWhileLoopNode=class extends nn{async execute(e,t){const o=hn(this,t,"while"),n=e.inputs,r=pn(o.maxIterations,t.limits?.maxLoopIterations,100,"while"),a=o.condition;if(!a)throw new yt("while node is missing a condition");const i=o.statePort??"state",s=o.inputPort??i,d=o.outputPort??i,l=o.body,c=t.engine;if(!c)throw new gt("while node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");let u=n.state,p=0;for(await t.emit({type:S.LOOP_STARTED});await(new fn).evaluateAsync(a,u,t,{...n,state:u});){if(p>=r)throw await t.emit({type:S.LOOP_LIMIT_REACHED,iteration:p}),new wt(`while loop exceeded max iterations (${r})`);await t.emit({type:S.LOOP_CONDITION_EVALUATED,iteration:p,payload:{result:!0}}),await t.emit({type:S.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:S.LOOP_ITERATION_COMPLETED,iteration:p}),p++}return await t.emit({type:S.LOOP_COMPLETED}),{state:u,iterations:p}}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.state.label",placeholder:"graph.node.loop.while.fields.state.placeholder",type:"textarea"}),Y({handle:"state"}),i.__metadata("design:type",Object)],e.GraphWhileLoopNode.prototype,"state",void 0),i.__decorate([r.required(),Q({handle:"state"}),i.__metadata("design:type",Object)],e.GraphWhileLoopNode.prototype,"stateOut",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.maxIterations.label",type:"number"}),Y({handle:"maxIterations",userControlled:!0}),i.__metadata("design:type",Number)],e.GraphWhileLoopNode.prototype,"maxIterations",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.condition.label",type:"code"}),Y({handle:"condition",userControlled:!0}),i.__metadata("design:type",Object)],e.GraphWhileLoopNode.prototype,"condition",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.statePort.label",type:"text"}),Y({handle:"statePort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphWhileLoopNode.prototype,"statePort",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.inputPort.label",type:"text"}),Y({handle:"inputPort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphWhileLoopNode.prototype,"inputPort",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.outputPort.label",type:"text"}),Y({handle:"outputPort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphWhileLoopNode.prototype,"outputPort",void 0),e.GraphWhileLoopNode=i.__decorate([X("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}}}}),r.model()],e.GraphWhileLoopNode),e.GraphInputValueNode=class extends nn{execute(e){const t=e.inputs;return{value:t?.value??null}}},i.__decorate([Q({handle:"value",connectionRules:{allowMultiple:!0}}),i.__metadata("design:type",Object)],e.GraphInputValueNode.prototype,"value",void 0),e.GraphInputValueNode=i.__decorate([X("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"}}),r.model()],e.GraphInputValueNode),e.GraphOutputValueNode=class extends nn{execute(e){return{}}},i.__decorate([r.required(),Y({handle:"value"}),i.__metadata("design:type",Object)],e.GraphOutputValueNode.prototype,"value",void 0),e.GraphOutputValueNode=i.__decorate([X("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"}}),r.model()],e.GraphOutputValueNode);const yn={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:[gn("items","graph.node.loop.foreach.ports.input.items.label","input",{required:!0,schema:{type:"array",items:{type:"any"}}}),gn("slice","graph.node.loop.foreach.ports.input.slice.label","input",{schema:{type:"number",integer:!0,min:1}}),gn("state","graph.node.loop.foreach.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[gn("results","graph.node.loop.foreach.ports.output.results.label","output",{schema:{type:"array",items:{type:"any"}}}),gn("completed","graph.node.loop.foreach.ports.output.completed.label","output",{schema:{type:"array",items:{type:"any"}}}),gn("iterations","graph.node.loop.foreach.ports.output.iterations.label","output",{schema:{type:"number",integer:!0,min:0}}),gn("broken","graph.node.loop.foreach.ports.output.broken.label","output",{schema:{type:"boolean"}}),gn("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}]},wn={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:[gn("state","graph.node.loop.while.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[gn("state","graph.node.loop.while.ports.output.state.label","output",{schema:{type:"any"}}),gn("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"}]},bn={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:[gn("state","graph.node.loop.until.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[gn("state","graph.node.loop.until.ports.output.state.label","output",{schema:{type:"any"}}),gn("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"}]},_n=[mn(e.GraphInputValueNode),mn(e.GraphOutputValueNode),mn(e.ManualTriggerNode),mn(e.WebhookTriggerNode),mn(e.ScheduleTriggerNode),mn(e.EventTriggerNode),mn(e.FormTriggerNode),mn(e.ChatTriggerNode),(vn=mn(e.IfFlowNode),{...vn,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"}}}]}))(mn(e.SwitchFlowNode)),mn(e.MapNode),mn(e.DelayFlowNode),mn(e.ErrorBoundaryFlowNode),mn(e.HumanApprovalFlowNode),mn(e.CodeNode),mn(e.LogFlowNode),mn(e.UtilityLogNode),mn(e.BreakFlowNode),mn(e.AgentNode),yn,wn,bn];var vn;const Nn=Object.fromEntries(_n.map(e=>[e.kind,e])),In=[e.ManualTriggerNode,e.WebhookTriggerNode,e.ScheduleTriggerNode,e.EventTriggerNode,e.FormTriggerNode,e.ChatTriggerNode],En=[e.IfFlowNode,e.SwitchFlowNode,e.DelayFlowNode,e.ErrorBoundaryFlowNode,e.HumanApprovalFlowNode,e.LogFlowNode,e.BreakFlowNode],An=[e.CodeNode,e.MapNode,e.UtilityLogNode],On=[e.GraphForeachLoopNode,e.GraphWhileLoopNode,e.GraphUntilLoopNode],kn=[e.GraphInputValueNode,e.GraphOutputValueNode],xn={value:e.GraphInputValueNode,result:e.GraphOutputValueNode,"core.trigger.manual":e.ManualTriggerNode,"core.trigger.webhook":e.WebhookTriggerNode,"core.trigger.schedule":e.ScheduleTriggerNode,"core.trigger.event":e.EventTriggerNode,"core.trigger.form":e.FormTriggerNode,"core.trigger.chat":e.ChatTriggerNode,"core.flow.if":e.IfFlowNode,"core.flow.switch":e.SwitchFlowNode,"core.utility.map":e.MapNode,"core.flow.delay":e.DelayFlowNode,"core.flow.errorBoundary":e.ErrorBoundaryFlowNode,"core.flow.humanApproval":e.HumanApprovalFlowNode,"core.utility.code":e.CodeNode,"core.flow.log":e.LogFlowNode,"core.utility.log":e.UtilityLogNode,"core.flow.break":e.BreakFlowNode,"core.agent":e.AgentNode,"core.loop.foreach":e.GraphForeachLoopNode,"core.loop.while":e.GraphWhileLoopNode,"core.loop.until":e.GraphUntilLoopNode};function Sn(e){return{execute:(t,o)=>e.instantiate({...on(o.node),...t.parameters,...o.node.state??{}}).execute(t,o)}}function Dn(){const e=[];for(const[t,o]of Object.entries(Nn)){const n=xn[t];n&&e.push(tn({manifest:o,executor:Sn(n)}))}return e}const Rn=["node","definition","executor","execute","ports","component"];function Pn(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 Cn(e,t){const o=[];for(const n of Object.keys(e))Rn.includes(n)&&o.push(Pn("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 Tn(e,t){t.push(...Cn(e,"$")),e.inputs.forEach((e,o)=>t.push(...Cn(e,`inputs[${o}]`))),e.outputs.forEach((e,o)=>t.push(...Cn(e,`outputs[${o}]`)));for(const o of e.nodes)t.push(...Cn(o,`nodes[${o.id}]`)),o.loop&&(t.push(...Cn(o.loop,`nodes[${o.id}].loop`)),Tn(o.loop.body,t));for(const o of e.edges)t.push(...Cn(o,`edges[${o.id}]`))}function $n(e,t){const o=[];e.nodes.length>t.maxNodes&&o.push(Pn("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(Pn("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=Gn(e);n>t.maxNestingDepth&&o.push(Pn("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(Pn("document.limit.size","$",`Document serializes to ${r} bytes; at most ${t.maxDocumentBytes} bytes are allowed`,{details:{bytes:r,limit:t.maxDocumentBytes}})),o}function Gn(e,t=0){let o=t;for(const n of e.nodes)n.loop?.body&&(o=Math.max(o,Gn(n.loop.body,t+1)));return o}async function Ln(e,t,...o){const n=[];for(const r of e.nodes)t.has(r.kind,...o)||n.push(Pn("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 Ln(r.loop.body,t,...o));return n}async function Mn(e,t={},...o){const n={...an,...t.limits},r=[];if(!Re(e))return r.push(Pn("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(!ae(e))return r.push(Pn("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};Tn(e,r),r.push(...(e=>{const t=[],o=new Set;for(const n of[...e.inputs,...e.outputs])o.has(n.id)?t.push(Pn("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(Pn("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(Pn("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(...$n(e,n)),Ao(e,r);try{ve(e)}catch(e){const t=e instanceof a.ValidationError?e.message:e+"";r.push(Pn("document.structure","$",t))}return t.catalogue&&r.push(...await Ln(e,t.catalogue,...o)),{valid:0===r.length,issues:r}}function Fn(e,t,o={}){const n=e?.owner??null;return!n||n===t||(null==t||""===t)&&!0===o.allowAnonymousAccess}function Vn(e,t){return(e?.owner??null)===(t??null)}function jn(e,t,o){if(!Vn(e,t))throw new s.ForbiddenError(`${o.resourceKind} '${o.resourceId}' is owned by another user`)}function Un(e,t,o){if(!Fn(e,t,o))throw new s.ForbiddenError(`${o.resourceKind} '${o.resourceId}' is owned by another user`)}function Bn(e){if(null===e||"object"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(e=>Bn(e)).join(",")}]`;const t=e;return`{${Object.keys(t).filter(e=>void 0!==t[e]).sort().map(e=>`${JSON.stringify(e)}:${Bn(t[e])}`).join(",")}}`}function Wn(e){return p.createHash("sha256").update(Bn(e)).digest("hex")}function qn(e){return new nt({runId:e.runId,workflowId:e.workflowId,...e.ownerUser?{owner:e.ownerUser}:{},status:e.status,...e.documentFingerprint?{documentFingerprint:e.documentFingerprint}:{},...void 0!==e.result?{result:Hn(e.result)}:{},...e.error?{error:Hn(e.error)}:{},createdAt:new Date(e.createdAt),...e.startedAt?{startedAt:new Date(e.startedAt)}:{},...e.finishedAt?{finishedAt:new Date(e.finishedAt)}:{}})}function Hn(e){if(null!=e)return JSON.parse(JSON.stringify(e))}class Kn{constructor(e,t={}){this.sequences=new Map,this.chains=new Map,this.store=e,this.limits={...D,...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 zn{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={...D,...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 a=this.runExecution({...e},t,o,...n).catch(async t=>{const o=Xn(t);try{await this.emitTerminal({...e},S.WORKFLOW_FAILED,o)}catch{}return await this.finalize({...e},"failed",void 0,o,...n)});return this.completions.set(e.runId,a),a}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 a,i,s=!1;const d=this.engine.observe({refresh:async t=>{t.runId===r&&(t.error&&(a=t.error),P((await this.publisher.publish(this.envelopeOf(e,t))).type)?s=!0:t.type===S.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 a=t,await this.emitTerminal(e,S.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=Xn(t);return a=o,s||(await this.emitTerminal(e,S.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 a=t,s||(await this.emitTerminal(e,S.WORKFLOW_CANCELLED,t),s=!0),await this.finalize(e,"cancelled",void 0,t,...n)}try{i=await this.engine.execute(d,o,{runId:r,abortSignal:this.controllers.get(r)?.signal,metadata:{documentFingerprint:l}},...n)}catch(e){a=Xn(e)}const c=this.abortReason(r);let u,p;return"timeout"===c?(u="failed",p=a??{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=a):i?.status===O.SUCCEEDED?u="succeeded":i?.status===O.CANCELLED?(u="cancelled",p=a):(u="failed",p=a??Xn(new gt(i?`Graph run '${r}' failed`:`Graph run '${r}' failed without a result`,"GRAPH_RUN_FAILED",{runId:r}))),s||await this.emitTerminal(e,"succeeded"===u?S.WORKFLOW_COMPLETED:"cancelled"===u?S.WORKFLOW_CANCELLED:S.WORKFLOW_FAILED,p),await this.finalize(e,u,i,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:re(t.payload)?t.payload:{nonSerializable:!0},error:t.error,parentRunId:t.parentRunId,path:t.path}}}function Xn(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+""}}function Jn(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 Yn(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&Re(e.document)&&!Re(e)}function Qn(e){return JSON.parse(JSON.stringify(e))}function Zn(e){if(null==e)return 0;let t;try{t=e.getTime()}catch{return 0}return Number.isFinite(t)?t:0}e.GraphWorkflowService=class extends s.ModelService{constructor(e){super(rt),this.catalogue=e}get limits(){return{...an,...sn.graph.workflows.limits??{}}}get allowAnonymousAccess(){return!0===sn.graph.workflows.allowAnonymousAccess}async saveDocument(e,t,...o){const{ctx:n,ctxArgs:r}=(await this.logCtx(o,"saveDocument",!0)).for(this.saveDocument);if(!Re(t))throw new a.ValidationError("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.ValidationError(`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 Et(i.issues);const s=Jn(n),d=await this.readExistingForWrite(e,r);d&&this.assertWriteOwnership(e,d,s);const l=new Date;if(d)return d.name=t.name,d.document=Qn(t),d.updatedAt=l,this.update(d,...r);const c=new rt({workflowId:e,name:t.name,document:Qn(t),...s?{owner:s}:{},updatedAt:l});return this.create(c,...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 a.NotFoundError(`No graph workflow found for workflowId '${e}'`);if(this.assertOwnership(e,r,Jn(o)),r.document)return Qn(r.document);throw new a.NotFoundError(`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",s.OrderDirection.ASC,...o),r=Jn(t);return n.filter(e=>Fn(e,r,{allowAnonymousAccess:this.allowAnonymousAccess})).sort((e,t)=>Zn(t.updatedAt)-Zn(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 a.NotFoundError(`No graph workflow found for workflowId '${e}'`);return this.assertOwnership(e,r,Jn(o)),r}async validateDocument(e,...t){const{ctx:o}=(await this.logCtx(t,"validateDocument",!0)).for(this.validateDocument);return await Mn(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(!ae(t))throw new a.ValidationError("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(!Yn(t))throw new a.ValidationError("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=Jn(n),s=await this.readExistingForWrite(e,r);s&&this.assertWriteOwnership(e,s,i);const d=new Date;if(s)return s.snapshot=t,await this.applyCanonicalWrapper(s,t,n),s.updatedAt=d,this.update(s,...r);const l=new rt({workflowId:e,snapshot:t,...i?{owner:i}:{},updatedAt:d});return await this.applyCanonicalWrapper(l,t,n),this.create(l,...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,Jn(o)),t}catch{return null}}async readExistingForWrite(e,t){try{return await this.read(e,...t)}catch(e){if(e instanceof a.NotFoundError)return null;throw e}}assertOwnership(e,t,o){Un(t??null,o??null,{allowAnonymousAccess:this.allowAnonymousAccess,resourceKind:"Graph workflow",resourceId:e})}assertWriteOwnership(e,t,o){jn(t??null,o??null,{resourceKind:"Graph workflow",resourceId:e})}async applyCanonicalWrapper(e,t,o){if(!Yn(t))return;if(t.document.id!==e.workflowId)throw new a.ValidationError(`Document id '${t.document.id}' does not match the workflow id '${e.workflowId}' from the request path`);const n=await Mn(t.document,{limits:this.limits,...this.catalogue?{catalogue:this.catalogue}:{}},o);if(!n.valid)throw new Et(n.issues);e.document=Qn(t.document),e.name=t.document.name}},e.GraphWorkflowService=i.__decorate([s.service(rt),i.__metadata("design:paramtypes",[Function])],e.GraphWorkflowService),e.GraphRunModelService=class extends s.ModelService{constructor(){super(nt)}async saveRun(e,...t){const{ctxArgs:o}=(await this.logCtx(t,"saveRun",!0)).for(this.saveRun),n=qn(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)}},e.GraphRunModelService=i.__decorate([s.service(nt),i.__metadata("design:paramtypes",[])],e.GraphRunModelService),e.ConditionExpressionEvaluator=Jt,e.DEFAULT_GRAPH_WORKFLOW_DOCUMENT_LIMITS=an,e.DEFAULT_GRAPH_WORKFLOW_VALIDATION_LIMITS=Po,e.DEFAULT_PINNING_METADATA=bo,e.GRAPH_AGENT_NODES=un,e.GRAPH_BOUNDARY_NODES=kn,e.GRAPH_BUILT_IN_NODE_CLASSES_BY_KIND=xn,e.GRAPH_BUILT_IN_NODE_MANIFESTS=_n,e.GRAPH_BUILT_IN_NODE_MANIFESTS_BY_KIND=Nn,e.GRAPH_CODE_DEFAULT_LANGUAGE=cn,e.GRAPH_CODE_DEFAULT_TIMEOUT_MS=1e3,e.GRAPH_CODE_LANGUAGES=ln,e.GRAPH_CODE_MAX_TIMEOUT_MS=pt,e.GRAPH_DEFAULT_CONCURRENCY=4,e.GRAPH_DEFAULT_MAX_FOREACH_ITERATIONS=1e3,e.GRAPH_DEFAULT_MAX_LOOP_ITERATIONS=100,e.GRAPH_DOCUMENT_FORBIDDEN_FIELD_KEYS=Co,e.GRAPH_FLOW_CONTROL_NODES=En,e.GRAPH_LOCAL_EXECUTION_BACKEND=lt,e.GRAPH_LOOP_KIND={FOREACH:"core.loop.foreach",WHILE:"core.loop.while",UNTIL:"core.loop.until"},e.GRAPH_LOOP_NODES=On,e.GRAPH_MAX_FOREACH_ITERATIONS=ut,e.GRAPH_MAX_LOOP_ITERATIONS=ct,e.GRAPH_PINNING_METADATA_KEY="graph.pinnable",e.GRAPH_PLAIN_SECRET_KEYS=uo,e.GRAPH_TRIGGER_NODES=In,e.GRAPH_UTILITY_NODES=An,e.GRAPH_WORKFLOW_BOUNDARY=dt,e.GRAPH_WORKFLOW_FORBIDDEN_FIELD_KEYS=Rn,e.GraphAuthValidator=jt,e.GraphBreakSignal=Nt,e.GraphConditionEvaluator=fn,e.GraphConnectionPolicyValidator=ko,e.GraphConnectionValidationError=Do,e.GraphCredentialAuthorizationError=Ro,e.GraphCredentialReferenceValidator=xo,e.GraphCycleError=mt,e.GraphDocumentValidationError=So,e.GraphEdgeInstanceValidator=Oo,e.GraphEngineEventSink=Kt,e.GraphEnvironment=sn,e.GraphExecutionBackendRegistry=Xt,e.GraphExecutionContext=Wt,e.GraphExecutionEngine=Fo,e.GraphExecutionError=gt,e.GraphExecutionEventEmitter=At,e.GraphExecutionEventFactory=Ot,e.GraphExecutionFrame=qt,e.GraphExecutionSnapshotMapper=class{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:O.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}}},e.GraphInputError=yt,e.GraphLoopExecutionContext=class{constructor(e,t){this.iteration=e,this.metadata=t}},e.GraphLoopLimitError=wt,e.GraphNode=nn,e.GraphNodeInstanceValidator=Eo,e.GraphNodeManifestResolver=Yo,e.GraphNodeMethodNotFoundError=Wo,e.GraphNodeMethodRegistry=qo,e.GraphNodeNotFoundError=Bo,e.GraphNodeRegistrationError=Uo,e.GraphParameterValidator=po,e.GraphPinningDependencyResolver=No,e.GraphPinningError=bt,e.GraphPinningPolicy=vo,e.GraphPinningService=wo,e.GraphPortError=class extends gt{constructor(e,t){super(e,"GRAPH_PORT_ERROR",t)}},e.GraphPortSchemaResolver=class{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}}},e.GraphRunCancelledError=It,e.GraphRunEventPublisher=Kn,e.GraphRunExecutor=zn,e.GraphRunService=class{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 Kn(o,n.limits),this.executor=new zn(e,t,this.publisher,{onRunCompleted:n.onRunCompleted},n.limits),this.options={...n,limits:{...D,...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.ValidationError("Graph run request must carry a workflow document with an id or a saved workflowId");if(e.workflowId&&!this.options.documentResolver)throw new a.ValidationError("Graph run requests by workflowId require a document resolver");const i=o??t??"anonymous",s=this.activeByCaller.get(i)??new Set;if(s.size>=this.options.limits.maxConcurrentRuns)throw new a.ValidationError(`Graph run rejected: the configured limit of ${this.options.limits.maxConcurrentRuns} concurrent runs per caller is exhausted`);const d=this.generateRunId(),l={runId:d,workflowId:r,ownerUser:t,status:"queued",createdAt:(new Date).toISOString()};this.executor.begin(d),await this.runStore.saveRun({...l},...n);const c=this.documentProviderFor(e,t);return s.add(d),this.activeByCaller.set(i,s),this.callerKeysByRun.set(d,i),this.executor.schedule(l,c,e.inputs??{},...n).catch(()=>{}).finally(()=>this.finishActiveRun(d)),l}async getRun(e,t,...o){const n=await this.runStore.readRun(e,...o);if(!n)throw new a.NotFoundError(`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=>Fn({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 a.NotFoundError(`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 a.NotFoundError(`No graph run found for runId '${e}'`);this.assertWriteOwnership(r,o);const i=this.engine.backend,s=i.resume;if("function"!=typeof s)throw new gt(`Graph execution backend '${i.constructor?.name??"GraphExecutionBackend"}' does not support resume`,"GRAPH_RESUME_UNSUPPORTED_BACKEND",{runId:e});let d;try{d=await s.call(i,e,t,...n)}catch(e){throw(l=e)instanceof gt?new gt(l.message,l.graphCode):l}var l;const c={...d,runId:e,caller:o};return await this.publisher.publish({runId:e,workflowId:r.workflowId,type:S.WORKFLOW_RESUMED,payload:c}),c}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.ValidationError("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.ValidationError("Graph run request is ambiguous: supply either an unsaved workflow document or a saved workflowId, not both");if(!t&&!o)throw new a.ValidationError("Graph run request must supply either an unsaved workflow document or a saved workflowId");if(t&&!Re(e.workflow))throw new a.ValidationError("Graph run request carries a payload that is not a canonical GraphWorkflowDocument");if(void 0!==e.inputs&&!ae(e.inputs))throw new a.ValidationError("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.ValidationError(`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:Wn(t)})}const o=e.workflowId;return async(...e)=>{const n=this.options.documentResolver;if(!n)throw new a.ValidationError("Graph run requests by workflowId require a document resolver");const r=await n.resolve(o,t,...e);return{document:r,fingerprint:Wn(r)}}}assertOwnership(e,t){Un({owner:e.ownerUser},t,{allowAnonymousAccess:!0===this.options.allowAnonymousAccess,resourceKind:"Graph run",resourceId:e.runId})}assertWriteOwnership(e,t){jn({owner:e.ownerUser},t,{resourceKind:"Graph run",resourceId:e.runId})}generateRunId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new _t("Cannot generate a graph run id: crypto.randomUUID is unavailable in this runtime",{runtime:typeof globalThis.crypto});return e.randomUUID()}},e.GraphStoreError=_t,e.GraphTopology=yo,e.GraphTopologyError=vt,e.GraphValueValidator=class{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 yt(`Missing required ${o} port '${n.name}'`);if(e&&!this.resolver.resolve(n).validate(t[n.name]))throw new yt(`Invalid value for ${o} port '${n.name}'`)}}},e.GraphWorkflowDocumentRejectedError=Et,e.GraphWorkflowDocumentValidator=Go,e.InMemoryGraphRunEventStore=class{constructor(e={}){this.events=new Map,this.listeners=new Map,this.limits={...D,...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=>!P(e.type));if(-1===t)break;e.splice(t,1)}}},e.InMemoryGraphRunStore=class{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=>qn(e))}release(e){this.runs.delete(e)}},e.IsolatedVmCodeSandboxEvaluator=jo,e.LocalGraphExecutionBackend=Io,e.assertGraphResourceOwnership=Un,e.assertGraphResourceWriteOwnership=jn,e.buildGraphExecutionResult=Ht,e.builtInGraphNodeRegistrations=Dn,e.canAccessGraphResource=Fn,e.canAccessGraphResourcePayload=Vn,e.checkGraphValueAgainstSchema=io,e.clampGraphCodeTimeoutMs=dn,e.collectLooseNodeIssues=Ao,e.composeGraphNamespace=xt,e.createGraphValueRepository=mo,e.declaredGraphNodeMethods=e=>e.methods??[],e.decomposeGraphNamespace=kt,e.decomposeGraphNamespaces=Ft,e.defineGraphNode=tn,e.detectGraphCodeModeSurfaces=ao,e.evaluateCodeCondition=Zt,e.evaluateCondition=to,e.evaluateConditionSync=eo,e.findMalformedGraphNamespaces=Ct,e.findUngrantedGraphNamespaces=Pt,e.graphAuthDataFromRecord=Lt,e.graphAuthDataOf=Mt,e.graphDocumentHasCodeMode=e=>ao(e).length>0,e.graphNamespaceCovers=Rt,e.graphNamespacePartsOf=Dt,e.graphNodeConfig=on,e.graphRolesFromNamespaces=Tt,e.graphRunDocumentFingerprint=Wn,e.graphWorkflowOwnerOf=Jn,e.isCodeCondition=Yt,e.isConditionExpression=Qt,e.isGraphCredentialReferenceLike=lo,e.isGraphNamespaceCacheEntryValid=St,e.isGraphResolvedWorkflow=To,e.isPinnable=_o,e.mergeGraphAuthData=Vt,e.registerBuiltInGraphNodes=(e,...t)=>{for(const o of Dn())e.register(o,{},...t);return e},e.resolveGraphBackendCapabilities=zt,e.resolveGraphDynamicPorts=Xo,e.resolveGraphNodeManifest=Jo,e.serializeGraphValueKey=ho,e.stripFacadeOwnedBackendConfig=Mo,e.validateGraphWorkflowDocumentAtBoundary=Mn},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/logging"),require("@decaf-ts/ui-decorators"),require("@decaf-ts/decoration"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/db-decorators"),require("tslib"),require("@decaf-ts/core"),require("isolated-vm"),require("acorn"),require("acorn-walk"),require("typescript"),require("node:crypto")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/logging","@decaf-ts/ui-decorators","@decaf-ts/decoration","@decaf-ts/decorator-validation","@decaf-ts/db-decorators","tslib","@decaf-ts/core","isolated-vm","acorn","acorn-walk","typescript","node:crypto"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["as-graph"]={},e.decafTsLogging,e.decafTsUiDecorators,e.decafTsDecoration,e.decafTsDecoratorValidation,e.decafTsDbDecorators,e.tslib,e.decafTsCore,e.isolatedVm,e.acorn,e.acornWalk,e.typescript,e.node_crypto);
|
|
2
2
|
//# sourceMappingURL=as-graph.cjs.map
|