@decaf-ts/as-graph 0.2.1 → 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.
Files changed (285) hide show
  1. package/README.md +158 -2
  2. package/dist/as-graph.cjs +1 -1
  3. package/dist/as-graph.cjs.map +1 -1
  4. package/dist/as-graph.js +1 -1
  5. package/dist/as-graph.js.map +1 -1
  6. package/lib/cjs/dagster/DagsterGraphEventBridge.cjs +344 -0
  7. package/lib/cjs/dagster/DagsterGraphEventBridge.cjs.map +1 -0
  8. package/lib/cjs/dagster/DagsterGraphExecutionBackend.cjs +789 -0
  9. package/lib/cjs/dagster/DagsterGraphExecutionBackend.cjs.map +1 -0
  10. package/lib/cjs/dagster/DagsterResultMapper.cjs +56 -0
  11. package/lib/cjs/dagster/DagsterResultMapper.cjs.map +1 -0
  12. package/lib/cjs/dagster/DagsterTypes.cjs +4 -0
  13. package/lib/cjs/dagster/DagsterTypes.cjs.map +1 -0
  14. package/lib/cjs/dagster/capabilities.cjs +102 -0
  15. package/lib/cjs/dagster/capabilities.cjs.map +1 -0
  16. package/lib/cjs/dagster/constants.cjs +92 -0
  17. package/lib/cjs/dagster/constants.cjs.map +1 -0
  18. package/lib/cjs/dagster/index.cjs +32 -0
  19. package/lib/cjs/dagster/index.cjs.map +1 -0
  20. package/lib/cjs/engine/constants.cjs +6 -1
  21. package/lib/cjs/engine/constants.cjs.map +1 -1
  22. package/lib/cjs/engine/execution/GraphCodeMode.cjs +137 -0
  23. package/lib/cjs/engine/execution/GraphCodeMode.cjs.map +1 -0
  24. package/lib/cjs/engine/execution/GraphExecutionBackend.cjs +89 -0
  25. package/lib/cjs/engine/execution/GraphExecutionBackend.cjs.map +1 -0
  26. package/lib/cjs/engine/execution/GraphExecutionBackendRegistry.cjs +107 -0
  27. package/lib/cjs/engine/execution/GraphExecutionBackendRegistry.cjs.map +1 -0
  28. package/lib/cjs/engine/execution/GraphExecutionEngine.cjs +250 -733
  29. package/lib/cjs/engine/execution/GraphExecutionEngine.cjs.map +1 -1
  30. package/lib/cjs/engine/execution/LocalGraphExecutionBackend.cjs +804 -0
  31. package/lib/cjs/engine/execution/LocalGraphExecutionBackend.cjs.map +1 -0
  32. package/lib/cjs/engine/execution/index.cjs +4 -0
  33. package/lib/cjs/engine/execution/index.cjs.map +1 -1
  34. package/lib/cjs/engine/index.cjs +4 -0
  35. package/lib/cjs/engine/index.cjs.map +1 -1
  36. package/lib/cjs/engine/runs/GraphRunService.cjs +61 -0
  37. package/lib/cjs/engine/runs/GraphRunService.cjs.map +1 -1
  38. package/lib/cjs/engine/services/GraphWorkflowService.cjs +33 -14
  39. package/lib/cjs/engine/services/GraphWorkflowService.cjs.map +1 -1
  40. package/lib/cjs/mastra/MastraCapabilities.cjs +171 -0
  41. package/lib/cjs/mastra/MastraCapabilities.cjs.map +1 -0
  42. package/lib/cjs/mastra/MastraConditionBridge.cjs +39 -0
  43. package/lib/cjs/mastra/MastraConditionBridge.cjs.map +1 -0
  44. package/lib/cjs/mastra/MastraEventBridge.cjs +486 -0
  45. package/lib/cjs/mastra/MastraEventBridge.cjs.map +1 -0
  46. package/lib/cjs/mastra/MastraGraphExecutionBackend.cjs +351 -0
  47. package/lib/cjs/mastra/MastraGraphExecutionBackend.cjs.map +1 -0
  48. package/lib/cjs/mastra/MastraResumeGuard.cjs +127 -0
  49. package/lib/cjs/mastra/MastraResumeGuard.cjs.map +1 -0
  50. package/lib/cjs/mastra/MastraSchemaConverter.cjs +124 -0
  51. package/lib/cjs/mastra/MastraSchemaConverter.cjs.map +1 -0
  52. package/lib/cjs/mastra/MastraWorkflowCompiler.cjs +461 -0
  53. package/lib/cjs/mastra/MastraWorkflowCompiler.cjs.map +1 -0
  54. package/lib/cjs/mastra/MastraWorkflowManager.cjs +401 -0
  55. package/lib/cjs/mastra/MastraWorkflowManager.cjs.map +1 -0
  56. package/lib/cjs/mastra/index.cjs +35 -0
  57. package/lib/cjs/mastra/index.cjs.map +1 -0
  58. package/lib/cjs/mastra/types.cjs +34 -0
  59. package/lib/cjs/mastra/types.cjs.map +1 -0
  60. package/lib/cjs/nest/graph/GraphEngineCapabilityManifest.cjs +136 -0
  61. package/lib/cjs/nest/graph/GraphEngineCapabilityManifest.cjs.map +1 -0
  62. package/lib/cjs/nest/graph/GraphEngineCapabilityService.cjs +140 -0
  63. package/lib/cjs/nest/graph/GraphEngineCapabilityService.cjs.map +1 -0
  64. package/lib/cjs/nest/graph/GraphEngineController.cjs +227 -0
  65. package/lib/cjs/nest/graph/GraphEngineController.cjs.map +1 -0
  66. package/lib/cjs/nest/graph/GraphExecutionModule.cjs +30 -2
  67. package/lib/cjs/nest/graph/GraphExecutionModule.cjs.map +1 -1
  68. package/lib/cjs/nest/graph/index.cjs +3 -0
  69. package/lib/cjs/nest/graph/index.cjs.map +1 -1
  70. package/lib/cjs/nest/graph/main.cjs +54 -0
  71. package/lib/cjs/nest/graph/main.cjs.map +1 -0
  72. package/lib/cjs/nest/graph/servingErrors.cjs +3 -0
  73. package/lib/cjs/nest/graph/servingErrors.cjs.map +1 -1
  74. package/lib/cjs/node/utility/code/node.cjs +11 -3
  75. package/lib/cjs/node/utility/code/node.cjs.map +1 -1
  76. package/lib/cjs/shared/graph/catalog/GraphManifestCompiler.cjs +2 -3
  77. package/lib/cjs/shared/graph/catalog/GraphManifestCompiler.cjs.map +1 -1
  78. package/lib/cjs/shared/graph/constants.cjs +8 -0
  79. package/lib/cjs/shared/graph/constants.cjs.map +1 -1
  80. package/lib/cjs/shared/graph/index.cjs +2 -1
  81. package/lib/cjs/shared/graph/index.cjs.map +1 -1
  82. package/lib/cjs/shared/graph/layout/GraphWorkflowLayout.cjs +146 -0
  83. package/lib/cjs/shared/graph/layout/GraphWorkflowLayout.cjs.map +1 -0
  84. package/lib/cjs/shared/graph/layout/index.cjs +23 -0
  85. package/lib/cjs/shared/graph/layout/index.cjs.map +1 -0
  86. package/lib/cjs/shared/graph/layout/layout-options.cjs +93 -0
  87. package/lib/cjs/shared/graph/layout/layout-options.cjs.map +1 -0
  88. package/lib/cjs/shared/ui/index.cjs +8 -10
  89. package/lib/cjs/shared/ui/index.cjs.map +1 -1
  90. package/lib/esm/dagster/DagsterGraphEventBridge.js +339 -0
  91. package/lib/esm/dagster/DagsterGraphEventBridge.js.map +1 -0
  92. package/lib/esm/dagster/DagsterGraphExecutionBackend.js +781 -0
  93. package/lib/esm/dagster/DagsterGraphExecutionBackend.js.map +1 -0
  94. package/lib/esm/dagster/DagsterResultMapper.js +51 -0
  95. package/lib/esm/dagster/DagsterResultMapper.js.map +1 -0
  96. package/lib/esm/dagster/DagsterTypes.js +2 -0
  97. package/lib/esm/dagster/DagsterTypes.js.map +1 -0
  98. package/lib/esm/dagster/capabilities.js +97 -0
  99. package/lib/esm/dagster/capabilities.js.map +1 -0
  100. package/lib/esm/dagster/constants.js +88 -0
  101. package/lib/esm/dagster/constants.js.map +1 -0
  102. package/lib/esm/dagster/index.js +15 -0
  103. package/lib/esm/dagster/index.js.map +1 -0
  104. package/lib/esm/engine/constants.js +5 -0
  105. package/lib/esm/engine/constants.js.map +1 -1
  106. package/lib/esm/engine/execution/GraphCodeMode.js +132 -0
  107. package/lib/esm/engine/execution/GraphCodeMode.js.map +1 -0
  108. package/lib/esm/engine/execution/GraphExecutionBackend.js +83 -0
  109. package/lib/esm/engine/execution/GraphExecutionBackend.js.map +1 -0
  110. package/lib/esm/engine/execution/GraphExecutionBackendRegistry.js +102 -0
  111. package/lib/esm/engine/execution/GraphExecutionBackendRegistry.js.map +1 -0
  112. package/lib/esm/engine/execution/GraphExecutionEngine.js +232 -716
  113. package/lib/esm/engine/execution/GraphExecutionEngine.js.map +1 -1
  114. package/lib/esm/engine/execution/LocalGraphExecutionBackend.js +799 -0
  115. package/lib/esm/engine/execution/LocalGraphExecutionBackend.js.map +1 -0
  116. package/lib/esm/engine/execution/index.js +4 -0
  117. package/lib/esm/engine/execution/index.js.map +1 -1
  118. package/lib/esm/engine/index.js +4 -0
  119. package/lib/esm/engine/index.js.map +1 -1
  120. package/lib/esm/engine/runs/GraphRunService.js +62 -1
  121. package/lib/esm/engine/runs/GraphRunService.js.map +1 -1
  122. package/lib/esm/engine/services/GraphWorkflowService.js +33 -14
  123. package/lib/esm/engine/services/GraphWorkflowService.js.map +1 -1
  124. package/lib/esm/mastra/MastraCapabilities.js +164 -0
  125. package/lib/esm/mastra/MastraCapabilities.js.map +1 -0
  126. package/lib/esm/mastra/MastraConditionBridge.js +34 -0
  127. package/lib/esm/mastra/MastraConditionBridge.js.map +1 -0
  128. package/lib/esm/mastra/MastraEventBridge.js +481 -0
  129. package/lib/esm/mastra/MastraEventBridge.js.map +1 -0
  130. package/lib/esm/mastra/MastraGraphExecutionBackend.js +346 -0
  131. package/lib/esm/mastra/MastraGraphExecutionBackend.js.map +1 -0
  132. package/lib/esm/mastra/MastraResumeGuard.js +123 -0
  133. package/lib/esm/mastra/MastraResumeGuard.js.map +1 -0
  134. package/lib/esm/mastra/MastraSchemaConverter.js +119 -0
  135. package/lib/esm/mastra/MastraSchemaConverter.js.map +1 -0
  136. package/lib/esm/mastra/MastraWorkflowCompiler.js +456 -0
  137. package/lib/esm/mastra/MastraWorkflowCompiler.js.map +1 -0
  138. package/lib/esm/mastra/MastraWorkflowManager.js +396 -0
  139. package/lib/esm/mastra/MastraWorkflowManager.js.map +1 -0
  140. package/lib/esm/mastra/index.js +18 -0
  141. package/lib/esm/mastra/index.js.map +1 -0
  142. package/lib/esm/mastra/types.js +30 -0
  143. package/lib/esm/mastra/types.js.map +1 -0
  144. package/lib/esm/nest/graph/GraphEngineCapabilityManifest.js +129 -0
  145. package/lib/esm/nest/graph/GraphEngineCapabilityManifest.js.map +1 -0
  146. package/lib/esm/nest/graph/GraphEngineCapabilityService.js +131 -0
  147. package/lib/esm/nest/graph/GraphEngineCapabilityService.js.map +1 -0
  148. package/lib/esm/nest/graph/GraphEngineController.js +218 -0
  149. package/lib/esm/nest/graph/GraphEngineController.js.map +1 -0
  150. package/lib/esm/nest/graph/GraphExecutionModule.js +30 -2
  151. package/lib/esm/nest/graph/GraphExecutionModule.js.map +1 -1
  152. package/lib/esm/nest/graph/index.js +3 -0
  153. package/lib/esm/nest/graph/index.js.map +1 -1
  154. package/lib/esm/nest/graph/main.js +51 -0
  155. package/lib/esm/nest/graph/main.js.map +1 -0
  156. package/lib/esm/nest/graph/servingErrors.js +3 -0
  157. package/lib/esm/nest/graph/servingErrors.js.map +1 -1
  158. package/lib/esm/node/utility/code/node.js +11 -3
  159. package/lib/esm/node/utility/code/node.js.map +1 -1
  160. package/lib/esm/shared/graph/GraphExecutionStateMapper.js.map +1 -1
  161. package/lib/esm/shared/graph/catalog/GraphManifestCompiler.js +2 -3
  162. package/lib/esm/shared/graph/catalog/GraphManifestCompiler.js.map +1 -1
  163. package/lib/esm/shared/graph/constants.js +8 -0
  164. package/lib/esm/shared/graph/constants.js.map +1 -1
  165. package/lib/esm/shared/graph/index.js +2 -1
  166. package/lib/esm/shared/graph/index.js.map +1 -1
  167. package/lib/esm/shared/graph/layout/GraphWorkflowLayout.js +107 -0
  168. package/lib/esm/shared/graph/layout/GraphWorkflowLayout.js.map +1 -0
  169. package/lib/esm/shared/graph/layout/index.js +6 -0
  170. package/lib/esm/shared/graph/layout/index.js.map +1 -0
  171. package/lib/esm/shared/graph/layout/layout-options.js +96 -0
  172. package/lib/esm/shared/graph/layout/layout-options.js.map +1 -0
  173. package/lib/esm/shared/ui/index.js +8 -10
  174. package/lib/esm/shared/ui/index.js.map +1 -1
  175. package/lib/types/dagster/DagsterGraphEventBridge.d.cts +142 -0
  176. package/lib/types/dagster/DagsterGraphEventBridge.d.mts +142 -0
  177. package/lib/types/dagster/DagsterGraphExecutionBackend.d.cts +323 -0
  178. package/lib/types/dagster/DagsterGraphExecutionBackend.d.mts +323 -0
  179. package/lib/types/dagster/DagsterResultMapper.d.cts +50 -0
  180. package/lib/types/dagster/DagsterResultMapper.d.mts +50 -0
  181. package/lib/types/dagster/DagsterTypes.d.cts +355 -0
  182. package/lib/types/dagster/DagsterTypes.d.mts +355 -0
  183. package/lib/types/dagster/capabilities.d.cts +34 -0
  184. package/lib/types/dagster/capabilities.d.mts +34 -0
  185. package/lib/types/dagster/constants.d.cts +87 -0
  186. package/lib/types/dagster/constants.d.mts +87 -0
  187. package/lib/types/dagster/index.d.cts +14 -0
  188. package/lib/types/dagster/index.d.mts +14 -0
  189. package/lib/types/engine/constants.d.cts +5 -0
  190. package/lib/types/engine/constants.d.mts +5 -0
  191. package/lib/types/engine/execution/GraphCodeMode.d.cts +52 -0
  192. package/lib/types/engine/execution/GraphCodeMode.d.mts +52 -0
  193. package/lib/types/engine/execution/GraphExecutionBackend.d.cts +306 -0
  194. package/lib/types/engine/execution/GraphExecutionBackend.d.mts +306 -0
  195. package/lib/types/engine/execution/GraphExecutionBackendRegistry.d.cts +59 -0
  196. package/lib/types/engine/execution/GraphExecutionBackendRegistry.d.mts +59 -0
  197. package/lib/types/engine/execution/GraphExecutionEngine.d.cts +116 -135
  198. package/lib/types/engine/execution/GraphExecutionEngine.d.mts +116 -135
  199. package/lib/types/engine/execution/LocalGraphExecutionBackend.d.cts +232 -0
  200. package/lib/types/engine/execution/LocalGraphExecutionBackend.d.mts +232 -0
  201. package/lib/types/engine/execution/index.d.cts +4 -0
  202. package/lib/types/engine/execution/index.d.mts +4 -0
  203. package/lib/types/engine/index.d.cts +4 -0
  204. package/lib/types/engine/index.d.mts +4 -0
  205. package/lib/types/engine/runs/GraphRunService.d.cts +19 -0
  206. package/lib/types/engine/runs/GraphRunService.d.mts +19 -0
  207. package/lib/types/engine/services/GraphWorkflowService.d.cts +22 -0
  208. package/lib/types/engine/services/GraphWorkflowService.d.mts +22 -0
  209. package/lib/types/mastra/MastraCapabilities.d.cts +91 -0
  210. package/lib/types/mastra/MastraCapabilities.d.mts +91 -0
  211. package/lib/types/mastra/MastraConditionBridge.d.cts +38 -0
  212. package/lib/types/mastra/MastraConditionBridge.d.mts +38 -0
  213. package/lib/types/mastra/MastraEventBridge.d.cts +189 -0
  214. package/lib/types/mastra/MastraEventBridge.d.mts +189 -0
  215. package/lib/types/mastra/MastraGraphExecutionBackend.d.cts +119 -0
  216. package/lib/types/mastra/MastraGraphExecutionBackend.d.mts +119 -0
  217. package/lib/types/mastra/MastraResumeGuard.d.cts +58 -0
  218. package/lib/types/mastra/MastraResumeGuard.d.mts +58 -0
  219. package/lib/types/mastra/MastraSchemaConverter.d.cts +39 -0
  220. package/lib/types/mastra/MastraSchemaConverter.d.mts +39 -0
  221. package/lib/types/mastra/MastraWorkflowCompiler.d.cts +218 -0
  222. package/lib/types/mastra/MastraWorkflowCompiler.d.mts +218 -0
  223. package/lib/types/mastra/MastraWorkflowManager.d.cts +220 -0
  224. package/lib/types/mastra/MastraWorkflowManager.d.mts +220 -0
  225. package/lib/types/mastra/index.d.cts +17 -0
  226. package/lib/types/mastra/index.d.mts +17 -0
  227. package/lib/types/mastra/types.d.cts +222 -0
  228. package/lib/types/mastra/types.d.mts +222 -0
  229. package/lib/types/nest/graph/GraphEngineCapabilityManifest.d.cts +87 -0
  230. package/lib/types/nest/graph/GraphEngineCapabilityManifest.d.mts +87 -0
  231. package/lib/types/nest/graph/GraphEngineCapabilityService.d.cts +98 -0
  232. package/lib/types/nest/graph/GraphEngineCapabilityService.d.mts +98 -0
  233. package/lib/types/nest/graph/GraphEngineController.d.cts +74 -0
  234. package/lib/types/nest/graph/GraphEngineController.d.mts +74 -0
  235. package/lib/types/nest/graph/GraphExecutionModule.d.cts +8 -0
  236. package/lib/types/nest/graph/GraphExecutionModule.d.mts +8 -0
  237. package/lib/types/nest/graph/index.d.cts +3 -0
  238. package/lib/types/nest/graph/index.d.mts +3 -0
  239. package/lib/types/nest/graph/main.d.cts +1 -0
  240. package/lib/types/nest/graph/main.d.mts +1 -0
  241. package/lib/types/nest/graph/servingErrors.d.cts +3 -1
  242. package/lib/types/nest/graph/servingErrors.d.mts +3 -1
  243. package/lib/types/node/utility/code/node.d.cts +1 -1
  244. package/lib/types/node/utility/code/node.d.mts +1 -1
  245. package/lib/types/shared/graph/GraphExecutionStateMapper.d.cts +5 -5
  246. package/lib/types/shared/graph/GraphExecutionStateMapper.d.mts +5 -5
  247. package/lib/types/shared/graph/constants.d.cts +8 -0
  248. package/lib/types/shared/graph/constants.d.mts +8 -0
  249. package/lib/types/shared/graph/index.d.cts +2 -1
  250. package/lib/types/shared/graph/index.d.mts +2 -1
  251. package/lib/types/shared/graph/layout/GraphWorkflowLayout.d.cts +49 -0
  252. package/lib/types/shared/graph/layout/GraphWorkflowLayout.d.mts +49 -0
  253. package/lib/types/shared/graph/layout/index.d.cts +5 -0
  254. package/lib/types/shared/graph/layout/index.d.mts +5 -0
  255. package/lib/types/shared/graph/layout/layout-options.d.cts +46 -0
  256. package/lib/types/shared/graph/layout/layout-options.d.mts +46 -0
  257. package/lib/types/shared/graph/types.d.cts +4 -3
  258. package/lib/types/shared/graph/types.d.mts +4 -3
  259. package/lib/types/shared/ui/index.d.cts +8 -10
  260. package/lib/types/shared/ui/index.d.mts +8 -10
  261. package/package.json +49 -6
  262. package/lib/cjs/shared/ui/GraphNodeView.cjs +0 -114
  263. package/lib/cjs/shared/ui/GraphNodeView.cjs.map +0 -1
  264. package/lib/cjs/shared/ui/GraphRunView.cjs +0 -96
  265. package/lib/cjs/shared/ui/GraphRunView.cjs.map +0 -1
  266. package/lib/cjs/shared/ui/GraphWorkflowView.cjs +0 -78
  267. package/lib/cjs/shared/ui/GraphWorkflowView.cjs.map +0 -1
  268. package/lib/cjs/shared/ui/types.cjs +0 -4
  269. package/lib/cjs/shared/ui/types.cjs.map +0 -1
  270. package/lib/esm/shared/ui/GraphNodeView.js +0 -107
  271. package/lib/esm/shared/ui/GraphNodeView.js.map +0 -1
  272. package/lib/esm/shared/ui/GraphRunView.js +0 -90
  273. package/lib/esm/shared/ui/GraphRunView.js.map +0 -1
  274. package/lib/esm/shared/ui/GraphWorkflowView.js +0 -72
  275. package/lib/esm/shared/ui/GraphWorkflowView.js.map +0 -1
  276. package/lib/esm/shared/ui/types.js +0 -2
  277. package/lib/esm/shared/ui/types.js.map +0 -1
  278. package/lib/types/shared/ui/GraphNodeView.d.cts +0 -48
  279. package/lib/types/shared/ui/GraphNodeView.d.mts +0 -48
  280. package/lib/types/shared/ui/GraphRunView.d.cts +0 -88
  281. package/lib/types/shared/ui/GraphRunView.d.mts +0 -88
  282. package/lib/types/shared/ui/GraphWorkflowView.d.cts +0 -18
  283. package/lib/types/shared/ui/GraphWorkflowView.d.mts +0 -18
  284. package/lib/types/shared/ui/types.d.cts +0 -200
  285. package/lib/types/shared/ui/types.d.mts +0 -200
package/dist/as-graph.js CHANGED
@@ -1,2 +1,2 @@
1
- import{logParameterRegistry as e,Logging as t,LoggedEnvironment as o}from"@decaf-ts/logging";import{RenderingEngine as n,uimodel as r,uielement as i,uilistprop as a,uilistmodel as s,hidden as d}from"@decaf-ts/ui-decorators";import{Metadata as l,Decoration as c,apply as u,metadata as p,propMetadata as h,description as f,prop as g,DefaultFlavour as m}from"@decaf-ts/decoration";import{ValidationKeys as y,Model as w,required as b,type as v,date as I,model as E,option as N,min as O,max as A}from"@decaf-ts/decorator-validation";import{ValidationError as x,InternalError as k,NotFoundError as _}from"@decaf-ts/db-decorators";import{__decorate as D,__metadata as $}from"tslib";import{pk as P,column as S,index as R,table as C,BaseModel as T,ForbiddenError as L,Context as j,AuthorizationError as M,service as G,Service as U,repository as F,Repository as B,ClientBasedService as q,Adapter as W,ModelService as V,OrderDirection as H}from"@decaf-ts/core";import K from"isolated-vm";import*as z from"acorn";import*as J from"acorn-walk";import*as X from"typescript";import{createHash as Y}from"node:crypto";var Q,Z;y.REQUIRED,y.MIN,y.MIN_LENGTH,y.MAX,y.MAX_LENGTH,y.PATTERN,y.URL,y.STEP,y.DATE,y.EMAIL,y.PASSWORD,y.EQUALS,y.DIFF,y.LESS_THAN,y.LESS_THAN_OR_EQUAL,y.GREATER_THAN,y.GREATER_THAN_OR_EQUAL,(e=>{e.GRAPH="graph",e.NODE="graph.node",e.EDGE="graph.edge",e.PORT="graph.port",e.STATE="graph.state"})(Q||(Q={})),(e=>{e.INPUT="input",e.OUTPUT="output",e.CONNECTION="connection"})(Z||(Z={}));const ee={};function te(e,t={}){let o=e.width??96,n=e.height??96;for(const r of e.sizeRules??[]){if("parameterCount"!==r.type)continue;const e=t[r.parameter]??0;e>0&&("width"===r.dimension?o+=e*r.perItem:n+=e*r.perItem)}return{width:o,height:n}}function oe(e,t){ee[e]=t}function ne(e,t,o){const n=t?ee[t]:void 0;return n?.color?n.color:e||"#64748b"}function re(e,t,o){const n=t?ee[t]:void 0;return n?.icon?n.icon:e||"ti-pointer"}const ie=["skip","passThroughFirstInput","emitDefaults"];function ae(e){return ie.includes(e)}var se,de,le,ce;(e=>{e.PENDING="pending",e.PLANNING="planning",e.RUNNING="running",e.SUCCEEDED="succeeded",e.FAILED="failed",e.SKIPPED="skipped",e.CANCELLED="cancelled",e.CACHED="cached"})(se||(se={})),(e=>{e.IDLE="idle",e.RUNNING="running",e.BLOCKED="blocked",e.SUCCEEDED="succeeded",e.FAILED="failed",e.SKIPPED="skipped"})(de||(de={})),(e=>{e.NODE_ID="nodeId",e.WORKFLOW_ID="workflowId",e.RUN_ID="runId",e.USER="user",e.ROLES="roles",e.NAMESPACES="namespaces",e.ORGANIZATION="organization",e.IP="ip"})(le||(le={})),(e=>{e.WORKFLOW_STARTED="workflow.started",e.WORKFLOW_PLANNED="workflow.planned",e.WORKFLOW_COMPLETED="workflow.completed",e.WORKFLOW_FAILED="workflow.failed",e.WORKFLOW_CANCELLED="workflow.cancelled",e.NODE_QUEUED="node.queued",e.NODE_STARTED="node.started",e.NODE_OUTPUT="node.output",e.NODE_COMPLETED="node.completed",e.NODE_FAILED="node.failed",e.NODE_SKIPPED="node.skipped",e.NODE_CACHE_HIT="node.cacheHit",e.NODE_PINNED="node.pinned",e.NODE_UNPINNED="node.unpinned",e.NODE_STATE_CHANGED="node.stateChanged",e.EDGE_VALUE_ROUTED="edge.valueRouted",e.EDGE_STATE_CHANGED="edge.stateChanged",e.GRAPH_RUN_LOG="graph.run.log",e.LOOP_STARTED="loop.started",e.LOOP_ITERATION_STARTED="loop.iteration.started",e.LOOP_ITERATION_COMPLETED="loop.iteration.completed",e.LOOP_CONDITION_EVALUATED="loop.condition.evaluated",e.LOOP_COMPLETED="loop.completed",e.LOOP_LIMIT_REACHED="loop.limitReached",e.VALIDATION_STARTED="validation.started",e.VALIDATION_FAILED="validation.failed",e.VALIDATION_COMPLETED="validation.completed",e.STORE_READ="store.read",e.STORE_WRITE="store.write",e.STORE_DELETE="store.delete"})(ce||(ce={}));const ue={maxRequestBytes:4e6,maxConcurrentRuns:32,maxEventsPerRun:1e4,maxEventPayloadBytes:256e3,executionTimeoutMs:6e5,eventReplayWindowMs:3e5},pe=[ce.WORKFLOW_COMPLETED,ce.WORKFLOW_FAILED,ce.WORKFLOW_CANCELLED];function he(e){return pe.includes(e)}function fe(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}function ge(e){const t=l.constr(e);if("function"==typeof t)return t;const o=e.constructor;return"function"==typeof o?o:e}function me(e){if(null!=e)return"string"==typeof e?e:e+""}function ye(e,t,o){return me(e?.props?.label??e?.props?.name)??me(t?.name)??o??""}function we(e,t,o){const n=Ie(e,t);if(n?.model&&"function"==typeof n.model&&w.isModel(n.model))return n.model;const r=l.type(e,t);if("function"==typeof r&&w.isModel(r))return r;const i=l.getPropDesignTypes?.(e,t)?.designTypes||[];for(const e of i)if("function"==typeof e&&w.isModel(e))return e;const a=o?.[y.TYPE]?.customTypes||[];for(const e of a)if("function"==typeof e&&w.isModel(e))return e}function be(e,t){const o=[t,e.path??e.property].filter(Boolean).join(".");return{...e,path:o,children:e.children?.map(e=>be(e,o))}}function ve(e){const t=ge(e);return l.get(t,Q.NODE)}function Ie(e,t){const o=ge(e);return l.get(o,l.key(Q.PORT,t+""))}function Ee(e,t,o,n=new Set){const r=Ie(e,t);if(!r?.schema)return;const i=we(e,t,l.validationFor(e,t));if(!i)return;if(n.has(i))return[];const a=new Set(n);return a.add(e),a.add(i),Ae(i,a).filter(e=>e.direction===o)}function Ne(e,t,o=new Set){const n=Ie(e,t);if(!n)return;const r=l.validationFor(e,t),i=we(e,t,r);if(n.schema&&i)return;const a=w.uiElementOf(e,t)||void 0,s=w.uiDecorationOf(e,t,"uiprop"),d=l.type(e,t),c=me(n.type??r?.[y.TYPE]?.customTypes?.[0]?.name??a?.props?.type??s?.type??d?.name),u=(n.expand||i&&!o.has(i))&&i?(()=>{const n=new Set(o);return n.add(e),n.add(i),Ae(i,n).map(e=>be(e,t))})():void 0;return{property:t,path:t,direction:n.direction,name:t,label:ye(a,s,t),type:c?.toLowerCase(),required:!!r?.[y.REQUIRED],hidden:!!w.uiIsHidden(e,t),designType:d?.name,element:a,prop:s,validation:r,graph:n,connectionRules:n.connectionRules,composite:!!u?.length,children:u,model:i?.name}}function Oe(e){return Ae(ge(e))}function Ae(e,t=new Set){const o=l.properties(e)||[],n=[];for(const r of o){const o=r+"",i=Ie(e,o);if(i?.schema){const r=Ee(e,o,i.direction,t);if(r){n.push(...r);continue}}const a=Ne(e,o,t);a&&n.push(a)}return n}function xe(e){return e.flatMap(e=>e.children&&e.children.length?xe(e.children):[e])}function ke(e){const t=ge(e),o=w.uiModelOf(t),n=ve(t)||{},r=o?.tag||t.name,i=Oe(t),a=((e,t)=>{const o=t.portGroups||[],n=new Map(o.map(e=>[e.property,e])),r=[],i=l.properties(e)||[];for(const t of i){const o=t+"",i=Ie(e,o);if(!i?.schema)continue;if(!we(e,o,l.validationFor(e,o)))continue;const a=n.get(o);r.push(a?{...a,toggle:a.toggle??"all"}:{property:o,toggle:"all"})}for(const e of o)r.some(t=>t.property===e.property)||r.push(e);return r.length?r:void 0})(t,n),s=n.namespaces?.length?n.namespaces:(e=>{if(null==e)return[];let t,o=e;try{o=l.constr(e)}catch{o=e}try{t=l.get(o,"auth-namespace")}catch{t=void 0}return fe(t)??[]})(t),d=s.length?s:void 0;return{name:t.name,tag:r,kind:n.kind||r,category:n.category,color:n.color,effectiveColor:ne(n.color,n.category),group:n.group,height:n.height,icon:n.icon,effectiveIcon:re(n.icon,n.category),labels:n.labels||[],maxChildren:n.maxChildren,minWidth:n.minWidth,width:n.width,shape:n.shape,cornerRadius:n.cornerRadius,sizeRules:n.sizeRules,props:o?.props,ui:o,graph:n,ports:i,portGroups:a,namespaces:d}}const _e=new Set,De=new Set;function $e(e,t,o){return c.for(Q.NODE).define({decorator:(e,t,o)=>{const n={kind:t?.kind||e,...t};return t=>{const i=u(r(e,o),p(Q.NODE,n))(t);var a;return a=t,_e.add(a),i}},args:[e,t,o]}).apply()}function Pe(e,t){return c.for(Q.PORT).define({decorator:(e,t)=>(o,n)=>{const r={direction:e,...t};return u(h(l.key(Q.PORT,n),r))(o,n)},args:[e,t]}).apply()}function Se(e){return Pe(Z.INPUT,{...e,schema:!0})}function Re(e){return Pe(Z.OUTPUT,{...e,schema:!0})}function Ce(e){return Pe(Z.CONNECTION,e)}n.prototype.renderAsNode=(e,t,...o)=>ke(e),l.nodes=(()=>[..._e]).bind(l),l.workflows=(()=>[...De]).bind(l);const Te=["__proto__","prototype","constructor"];function Le(e){return Te.includes(e)}function je(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function Me(e){return null===e||"string"==typeof e||"number"==typeof e&&Number.isFinite(e)||"boolean"==typeof e}function Ge(e){return!!Me(e)||(Array.isArray(e)?e.every(e=>Ge(e)):!!je(e)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&!Le(t)&&Ge(e[t])))}function Ue(e){if(void 0===e)return!1;if("number"==typeof e)return Number.isFinite(e);if("function"==typeof e)return!1;if(Ge(e))return!0;if(Array.isArray(e))return e.every(e=>Ue(e));if(je(e)){const t=Reflect.ownKeys(e);for(const o of t){if("string"!=typeof o)return!1;if(Le(o))return!1;if(!Ue(e[o]))return!1}return!0}return!1}function Fe(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>Fe(e));const t={};for(const[o,n]of Object.entries(e))t[o]=Fe(n);return t}const Be={string:"string",char:"string",text:"string",textarea:"string",radio:"string",select:"string",number:"number",integer:"number",float:"number",double:"number",decimal:"number",boolean:"boolean",bool:"boolean",checkbox:"boolean",array:"array",list:"array",set:"array",object:"object",model:"model",any:"any",unknown:"any",enum:"enum"},qe={date:"date",datetime:"date-time","date-time":"date-time",duration:"duration"};function We(e){return e?Be[e.toLowerCase()]??"any":"any"}function Ve(e,t){const o=e[t];if(o&&"object"==typeof o)return o.value}function He(e,t){const o=Ve(e,t);return"number"==typeof o&&Number.isFinite(o)?o:void 0}function Ke(e,t,o){const n=e??{},r=(e=>{const t=Ve(e,y.ENUM);if(Array.isArray(t)&&t.every(Me))return t})(n);if(r)return{type:"enum",values:r};const i=(e=>{const t=e[y.TYPE],o=t?.customTypes?.[0],n="function"==typeof o?o.name:o?.name;if(n)return n})(n)??o;return i?{type:"model",name:i}:((e,t)=>{switch(We(e)){case"string":{const t=(e=>{if(e)return qe[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=He(t,y.MIN),r=He(t,y.MAX);return void 0!==n&&(o.min=n),void 0!==r&&(o.max=r),o}case"boolean":return{type:"boolean"};case"array":return((e,t)=>{const o={type:"array",items:ze(e,t)},n=He(e,y.MIN),r=He(e,y.MAX);return void 0!==n&&(o.minItems=n),void 0!==r&&(o.maxItems=r),o})(t,e);case"object":return{type:"object",properties:{}};case"enum":return{type:"enum",values:[]};case"model":return{type:"model",name:e??"any"};default:return{type:"any"}}})(t,n)}function ze(e,t){if((e=>{const t=e[y.LIST];return!!t?.clazz?.length})(e))return{type:"model",name:Je(e)};const o=Ve(e,y.TYPE);if("string"==typeof o){const e=We(o);return"model"===e?{type:"model",name:o}:{type:e}}if(t&&"array"!==t){const e=We(t);return"model"===e?{type:"model",name:t}:{type:e}}return{type:"any"}}function Je(e){const t=e[y.LIST],o=t?.clazz?.[0];if("function"!=typeof o)return"any";if(o.name)return o.name;try{const e=o();if("function"==typeof e&&e.name)return e.name}catch{return"any"}return"any"}function Xe(e){return"workflow"===e.scope}function Ye(e){return"node"===e.scope}function Qe(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"workflow"===t.scope?"string"==typeof t.port&&2===Reflect.ownKeys(t).length:"node"===t.scope&&"string"==typeof t.nodeId&&"string"==typeof t.port&&3===Reflect.ownKeys(t).length}function Ze(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e.mode;if("edge"===t)return 1===Reflect.ownKeys(e).length;if("literal"===t){const t=e.value;return 2===Object.keys(e).length&&Ge(t)}return"expression"===t&&2===Object.keys(e).length&&"string"==typeof e.expression}const et=["any","string","number","boolean","array","object","enum","model"];function tt(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&(e=>et.includes(e))(e.type)}function ot(e,t={seen:[]}){if(t.seen.includes(e))throw new x(`Document '${(e=>{const t=e?.id;return"string"==typeof t?t:"<unnamed document>"})(e)}' contains a loop body that references itself (cyclic document)`);if("string"!=typeof e.id||!e.id)throw new x("Document 'id' is required and must be a non-empty string");if("string"!=typeof e.name||!e.name)throw new x("Document 'name' is required and must be a non-empty string");const o=new Set;for(const t of[...e.inputs,...e.outputs]){if("string"!=typeof t.id||!t.id)throw new x("Workflow port 'id' is required and must be a non-empty string");if(o.has(t.id))throw new x(`Workflow port '${t.id}' is declared more than once; workflow port ids must be unique`);if(void 0!==t.schema&&!tt(t.schema))throw new x(`Workflow port '${t.id}' schema must be a valid GraphValueSchema`);o.add(t.id)}const n={seen:[...t.seen,e]},r=new Set;for(const t of e.nodes)nt(t,r);for(const t of e.nodes)t.loop&&rt(t,t.loop,n),t.errorBoundary&&it(t,t.errorBoundary,n);const i=new Set;for(const t of e.edges)st(t,i);for(const t of e.edges)dt(t.source,0,o,r,`Edge '${t.id}' source`),dt(t.target,0,o,r,`Edge '${t.id}' target`);if(void 0!==e.settings&&!Ue(e.settings))throw new x("Document settings must be JSON-safe (a map of JSON-safe values)");if(void 0!==e.metadata&&!Ue(e.metadata))throw new x("Document metadata must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed");if(void 0!==e.ui&&!Ue(e.ui))throw new x("Document ui must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed")}function nt(e,t){if("string"!=typeof e.id||!e.id)throw new x("Node 'id' is required and must be a non-empty string");if(t.has(e.id))throw new x(`Node id '${e.id}' is declared more than once; node ids must be unique`);if("string"!=typeof e.kind||!e.kind)throw new x(`Node '${e.id}' must declare a non-empty string 'kind'`);if(void 0===e.parameters||null===e.parameters)throw new x(`Node '${e.id}' parameters must be present (an empty object when there are none)`);if(t.add(e.id),e.inputBindings)for(const[t,o]of Object.entries(e.inputBindings)){if(Le(t))throw new x(`Node '${e.id}' input binding key '${t}' is not allowed (unsafe prototype-pollutant key)`);if(!Ze(o))throw new x(`Node '${e.id}' input binding for '${t}' must be a valid GraphInputBinding (edge, literal, or expression)`);if("literal"===o.mode&&!Ue(o.value))throw new x(`Node '${e.id}' literal binding for '${t}' must contain JSON-safe values`);if("expression"===o.mode&&!o.expression)throw new x(`Node '${e.id}' expression binding for '${t}' must contain a non-empty expression`)}if(e.outputBindings)for(const[t,o]of Object.entries(e.outputBindings)){if(Le(t))throw new x(`Node '${e.id}' output binding key '${t}' is not allowed (unsafe prototype-pollutant key)`);if(!o||"object"!=typeof o||Array.isArray(o))throw new x(`Node '${e.id}' output binding for '${t}' must be an object with enabled and alias settings`)}if(!Ue(e.parameters))throw new x(`Node '${e.id}' parameters must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed`);if(void 0!==e.state){if(!e.state||"object"!=typeof e.state||Array.isArray(e.state))throw new x(`Node '${e.id}' state must be an object when present`);if(!Ue(e.state))throw new x(`Node '${e.id}' state must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed`)}}function rt(e,t,o){if(!t.body||"object"!=typeof t.body)throw new x(`Node '${e.id}' loop configuration requires a body document`);if(ot(t.body,o),!(void 0===t.maxIterations||Number.isFinite(t.maxIterations)&&t.maxIterations>0))throw new x(`Node '${e.id}' loop maxIterations must be a positive number`);if(void 0!==t.timeoutMs&&("number"!=typeof t.timeoutMs||0>=t.timeoutMs))throw new x(`Node '${e.id}' loop timeoutMs must be a positive number in milliseconds`);if(void 0!==t.concurrency&&("number"!=typeof t.concurrency||0>=t.concurrency))throw new x(`Node '${e.id}' loop concurrency must be a positive number`);for(const o of[t.inputMappings,t.outputMappings])if(o)for(const[t,n]of Object.entries(o)){if(Le(t))throw new x(`Node '${e.id}' loop mapping key '${t}' is not allowed (unsafe prototype-pollutant key)`);at(n,e.id,t)}}function it(e,t,o){if(!t.try||"object"!=typeof t.try)throw new x(`Node '${e.id}' error-boundary configuration requires a try body document`);ot(t.try,o);for(const[n,r]of[["catch",t.catch],["finally",t.finally]])if(void 0!==r){if(!r||"object"!=typeof r)throw new x(`Node '${e.id}' error-boundary ${n} body must be a document`);ot(r,o)}}function at(e,t,o){if(!e||"object"!=typeof e)throw new x(`Node '${t}' loop mapping '${o}' must reference a workflow port, node port, literal, or expression`);switch(e.source){case"workflow":if("string"!=typeof e.port||!e.port)throw new x(`Node '${t}' loop mapping '${o}' referencing a workflow must reference a port identifier`);break;case"node":if("string"!=typeof e.nodeId||!e.nodeId||"string"!=typeof e.port||!e.port)throw new x(`Node '${t}' loop mapping '${o}' referencing a node must reference a node id and a port`);break;case"literal":if(!Ue(e.value))throw new x(`Node '${t}' loop mapping '${o}' literal references must be JSON-safe values`);break;case"expression":if("string"!=typeof e.expression||!e.expression)throw new x(`Node '${t}' loop mapping '${o}' expression references must be non-empty expressions`);break;default:throw new x(`Node '${t}' loop mapping '${o}' must use a workflow, node, literal, or expression reference source`)}}function st(e,t){if("string"!=typeof e.id||!e.id)throw new x("Edge 'id' is required and must be a non-empty string");if(t.has(e.id))throw new x(`Edge id '${e.id}' is declared more than once; edge ids must be unique`);if(!Qe(e.source))throw new x(`Edge '${e.id}' source endpoint is not a valid GraphEndpoint`);if(!Qe(e.target))throw new x(`Edge '${e.id}' target endpoint is not a valid GraphEndpoint`);if("data"!==e.type&&"connection"!==e.type)throw new x(`Edge '${e.id}' type '${e.type+""}' is not a valid edge type (data or connection are allowed)`);if(t.add(e.id),!Ue(e))throw new x(`Edge '${e.id}' contains values that are not JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed`)}function dt(e,t,o,n,r){if(Xe(e)){if(!o.has(e.port))throw new x(`${r} references workflow port '${e.port}' which is not declared on the document`)}else if(Ye(e)){if(!n.has(e.nodeId))throw new x(`${r} references node '${e.nodeId}' which is not part of the document`);if("string"!=typeof e.port||!e.port)throw new x(r+" node endpoints must reference a non-empty port identifier")}}const lt=["expression","template"],ct=["javascript","typescript","json","text"];function ut(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return!(!(e=>lt.includes(e))(t.mode)||"string"!=typeof t.expression||!t.expression||void 0!==t.language&&!(e=>ct.includes(e))(t.language)||void 0!==t.metadata&&!Ge(t.metadata))}function pt(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.name&&Array.isArray(t.inputs)&&Array.isArray(t.outputs)&&Array.isArray(t.nodes)&&Array.isArray(t.edges)}function ht(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.type&&(void 0===t.required||"boolean"==typeof t.required)&&(void 0===t.displayName||"string"==typeof t.displayName)&&(void 0===t.allowedOperations||Array.isArray(t.allowedOperations)&&t.allowedOperations.every(e=>"string"==typeof e))}const ft=["trigger","loop","branching","stateful","retryable","cancellable","parallel","resource"];function gt(e){return ft.includes(e)}function mt(e){if(!(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.kind&&"object"==typeof t.display&&Array.isArray(t.inputs)&&Array.isArray(t.outputs)&&Array.isArray(t.parameters)})(e))throw new x("Graph node manifest does not conform to the required shape");if(!Ue(e))throw new x("Graph node manifest contains values that are not JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys or unsafe prototype keys are not allowed on manifests")}const yt=["loadOptions","listSearch","resourceLocator","resourceMapping","validateParameter","action"];function wt(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.name&&(e=>yt.includes(e))(t.type)&&(void 0===t.parameter||"string"==typeof t.parameter)&&(void 0===t.dependencies||Array.isArray(t.dependencies)&&t.dependencies.every(e=>"string"==typeof e))}function bt(e){const t=e.element?.props?.value,o=t??e.prop?.value??e.validation?.defaultValue;if(void 0!==o&&"function"!=typeof o&&Ue(o))try{return JSON.parse(JSON.stringify(o))}catch{return}}function vt(e){if(e.type&&e.type in qe)return{type:"string",format:qe[e.type]};const t=(e=>{for(const t of[e.graph?.type,e.element?.props?.type,e.prop?.type])if("string"==typeof t&&"any"!==We(t))return t})(e);return t?Ke((e=>{if(!e)return;const t=Object.entries(e).filter(([e])=>e!==y.TYPE);return Object.fromEntries(t)})(e.validation),t):Ke(e.validation,e.type,e.model)}function It(e){const t={};for(const[o,n]of Object.entries(e.graph?.metadata??{}))Ue(n)&&(t[o]=JSON.parse(JSON.stringify(n)));return Object.keys(t).length?t:void 0}function Et(e){switch(e){case"output":return"output";case"connection":return"connection";default:return"input"}}function Nt(e){const t=e.graph?.handle;return"connection"!==e.direction&&"string"==typeof t&&t?t:e.path??e.property}function Ot(e,t){const o={id:Nt(e),label:e.label,direction:Et(e.direction),schema:vt(e)};e.required&&(o.required=!0),e.hidden&&(o.hidden=!0);const n=e.graph?.category;"string"==typeof n&&(o.category=n),!0===e.graph?.userControlled&&(o.configurable=!0);const r=e.graph?.handle;"string"==typeof r&&(o.handle=r);const i=Ct(e.graph?.connectionRules)??t;i&&(o.connectionPolicy=i);const a=(e=>{const t=e.element;if(!t||!Ue(t))return;const o=t.tag;if("string"!=typeof o)return;const n=t.props;return{tag:o,serialize:!0===t.serialize,props:n&&"object"==typeof n&&!Array.isArray(n)?Fe(n):{}}})(e);a&&(o.element=a);const s=It(e);return s&&(o.metadata=s),o}function At(e){const t={type:"string",id:Nt(e),label:e.label,required:e.required};if(e.hidden)return((e,t)=>{const o={...t,type:"hidden"},n=bt(e);return void 0!==n&&(o.defaultValue=n),xt(o)})(e,t);const o=bt(e);void 0!==o&&(t.defaultValue=o);const n=(e=>{const t=e.element?.props?.placeholder??e.prop?.placeholder;return"string"==typeof t?t:void 0})(e);n&&(t.placeholder=n);const r=It(e);if(r&&(t.metadata=r),(e=>{const t=Dt(e);return"code"===t||"code-editor"===t})(e))return xt({...t,type:"code",language:St(e)});const i=vt(e);switch(i.type){case"number":{const o={...t,type:"number",integer:i.integer,min:i.min,max:i.max},n=_t(e.validation?.step);return void 0!==n&&(o.step=n),xt(o)}case"boolean":return xt({...t,type:"boolean"});case"enum":return xt({...t,type:"options",options:i.values.map(e=>({value:e,label:e+""}))});case"array":{const e={...t,type:"collection"};return void 0!==i.maxItems&&(e.maxItems=i.maxItems),xt(e)}case"object":case"model":return xt({...t,type:"object"});default:return xt({...t,type:"string",multiline:!!$t(e)||void 0,pattern:kt(e.validation?.pattern),minLength:_t(e.validation?.minlength),maxLength:_t(e.validation?.maxlength)})}}function xt(e){const t=e;for(const e of Object.keys(t))void 0===t[e]&&delete t[e];return e}function kt(e){const t=e?.value;return"string"==typeof t?t:void 0}function _t(e){const t=e?.value;return"number"==typeof t&&Number.isFinite(t)?t:void 0}function Dt(e){const t=e.element?.tag;return"string"==typeof t&&t?t:void 0}function $t(e){return"textarea"===Dt(e)||"textarea"===(e=>{const t=e.element?.props?.type;return"string"==typeof t?t:void 0})(e)}const Pt=["javascript","typescript","json","text"];function St(e){const t=e.element?.props?.language;return"string"==typeof t&&Pt.includes(t)?t:"javascript"}function Rt(e,t){const o={name:t.name??e.name},n=e.graph?.metadata?.description??void 0;"string"==typeof n&&n&&(o.description=n);const r=t.category??e.category;"string"==typeof r&&r&&(o.category=r),"string"==typeof e.group&&e.group&&(o.group=e.group),Array.isArray(e.labels)&&(o.labels=e.labels.slice());const i=((e,t)=>{if(t.icon)return t.icon;const o=e.effectiveIcon??e.icon;return"string"==typeof o?{type:"catalogue",name:o}:{type:"catalogue",name:"ph:circuitry"}})(e,t);return i&&(o.icon=i),"string"==typeof e.color&&e.color&&(o.color=e.color),"number"==typeof e.width&&Number.isFinite(e.width)&&(o.width=e.width),"number"==typeof e.minWidth&&Number.isFinite(e.minWidth)&&(o.minWidth=e.minWidth),"number"==typeof e.height&&Number.isFinite(e.height)&&(o.height=e.height),"string"==typeof e.shape&&(o.shape=e.shape),"number"==typeof e.cornerRadius&&Number.isFinite(e.cornerRadius)&&(o.cornerRadius=e.cornerRadius),Array.isArray(e.sizeRules)&&(o.sizeRules=e.sizeRules),o}function Ct(e){if(!e)return;const t=e,o={};"boolean"==typeof t.allowSelf&&(o.allowSelf=t.allowSelf),"boolean"==typeof t.allowMultiple&&(o.allowMultiple=t.allowMultiple);const n=t.allowedKinds;Array.isArray(n)&&n.every(e=>"string"==typeof e)&&(o.allowedNodeKinds=n);const r=t.blockedKinds;Array.isArray(r)&&r.every(e=>"string"==typeof e)&&(o.blockedNodeKinds=r);const i=t.maxConnections;return"number"==typeof i&&Number.isFinite(i)&&(o.maxConnections=i),Object.keys(o).length?o:void 0}function Tt(e,t={}){const o="function"==typeof e?e:e.constructor;if(!ve(o))throw new x(`Node '${o?.name??e+""}' is not decorated with @node and cannot produce a manifest`);const n=ke(o),r=xe(Oe(o)),i=[],a=[],s=[],d=[],l=Ct(n.graph?.connectionRules);for(const e of r)("connection"===e.direction?s:"output"===e.direction?a:i).push(Ot(e,l)),"input"===e.direction&&d.push(At(e));const c={kind:t.kind??n.kind??n.name,display:Rt(n,t),inputs:i,outputs:a,parameters:d};return s.length&&(c.connections=s),n.namespaces?.length&&(c.namespaces=n.namespaces.slice()),mt(c),c}let Lt=class extends T{constructor(e){super(e)}};D([P({type:String,generated:!1}),f("Unique graph run id"),i("ngx-decaf-crud-field",{label:"graph.run.id.label",readonly:!0}),$("design:type",String)],Lt.prototype,"runId",void 0),D([S(),b(),R(),f("Workflow document id the run executes"),a("workflowId"),i("ngx-decaf-crud-field",{label:"graph.run.workflowId.label"}),$("design:type",String)],Lt.prototype,"workflowId",void 0),D([S(),f("Owning user; absent for anonymous callers"),i("ngx-decaf-crud-field",{label:"graph.run.owner.label"}),$("design:type",String)],Lt.prototype,"owner",void 0),D([S(),b(),v(String),R(),f("Current run lifecycle status"),a("status"),i("ngx-decaf-crud-field",{label:"graph.run.status.label",readonly:!0}),$("design:type",String)],Lt.prototype,"status",void 0),D([S(),f("Fingerprint of the executed document"),i("ngx-decaf-crud-field",{label:"graph.run.fingerprint.label",readonly:!0}),$("design:type",String)],Lt.prototype,"documentFingerprint",void 0),D([S(),g(),f("Workflow input values keyed by input port id"),$("design:type",Object)],Lt.prototype,"inputs",void 0),D([S(),g(),f("Execution result, present on successful completion"),$("design:type",Object)],Lt.prototype,"result",void 0),D([S(),g(),f("Structured error payload, present on failure"),$("design:type",Object)],Lt.prototype,"error",void 0),D([I(),S(),f("Run creation timestamp"),$("design:type",Date)],Lt.prototype,"createdAt",void 0),D([I(),S(),f("Execution start timestamp, once it has started"),$("design:type",Date)],Lt.prototype,"startedAt",void 0),D([I(),S(),f("Terminal-state timestamp, once the run has finished"),$("design:type",Date)],Lt.prototype,"finishedAt",void 0),Lt=D([s("ngx-decaf-list-item",{icon:"ti-player-play"}),r("ngx-decaf-crud-form"),f("Persistable graph run lifecycle record"),C("graph_run"),E(),$("design:paramtypes",[Object])],Lt);let jt=class extends T{constructor(e){super(e)}};D([P({type:String,generated:!1}),$("design:type",String)],jt.prototype,"workflowId",void 0),D([S(),$("design:type",String)],jt.prototype,"name",void 0),D([S(),$("design:type",Object)],jt.prototype,"document",void 0),D([S(),$("design:type",String)],jt.prototype,"owner",void 0),D([S(),$("design:type",Object)],jt.prototype,"snapshot",void 0),jt=D([C("graph_workflow"),E(),$("design:paramtypes",[Object])],jt),oe("Trigger",{color:"#3b82f6",icon:"ti-bolt"}),oe("Flow Control",{color:"#f59e0b",icon:"ti-arrows-split-2"}),oe("Utility",{color:"#0d9488",icon:"ti-tool"}),oe("Loop",{color:"#eab308",icon:"ti-repeat"}),oe("Workflow",{color:"#f97316",icon:"ti-sitemap"}),oe("Pipeline",{color:"#0ea5e9",icon:"ti-git-merge"}),oe("Node",{color:"#8b5cf6",icon:"ti-point-filled"}),oe("Agent",{color:"#7c3aed",icon:"ti-robot"}),oe("model",{color:"#3b82f6",icon:"ti-cpu"}),oe("memory",{color:"#10b981",icon:"ti-database"}),oe("workspace",{color:"#f59e0b",icon:"ti-folder"});const Mt=new Set;function Gt(e,t){return e.config[t]}function Ut(e){return Array.isArray(e)?e.map(e=>e+"").join(", "):e+""}(()=>{const t=[{key:le.NODE_ID,shouldInclude:e=>null!=Gt(e,le.NODE_ID),render:e=>Gt(e,le.NODE_ID)+""},{key:le.WORKFLOW_ID,shouldInclude:e=>null!=Gt(e,le.WORKFLOW_ID),render:e=>Gt(e,le.WORKFLOW_ID)+""},{key:le.RUN_ID,shouldInclude:e=>null!=Gt(e,le.RUN_ID),render:e=>Gt(e,le.RUN_ID)+""},{key:le.USER,shouldInclude:e=>null!=Gt(e,le.USER),render:e=>Gt(e,le.USER)+""},{key:le.ROLES,shouldInclude(e){const t=Gt(e,le.ROLES);return Array.isArray(t)&&t.length>0},render:e=>Ut(Gt(e,le.ROLES))},{key:le.NAMESPACES,shouldInclude(e){const t=Gt(e,le.NAMESPACES);return Array.isArray(t)&&t.length>0},render:e=>Ut(Gt(e,le.NAMESPACES))},{key:le.ORGANIZATION,shouldInclude:e=>null!=Gt(e,le.ORGANIZATION),render:e=>Gt(e,le.ORGANIZATION)+""},{key:le.IP,shouldInclude:e=>null!=Gt(e,le.IP),render:e=>Gt(e,le.IP)+""}];for(const o of t)Mt.has(o.key)||(e.register(o),Mt.add(o.key))})();const Ft="$workflow",Bt=4,qt=100,Wt=1e3,Vt=1e3,Ht=1e4,Kt=3e4,zt="graph.pinnable";var Jt,Xt;(e=>{e.MANUAL="manual",e.AUTOMATIC="automatic",e.DISABLED="disabled"})(Jt||(Jt={})),(e=>{e.TRUTHY="truthy",e.FALSY="falsy",e.EQUALS="equals",e.NOT_EQUALS="notEquals",e.GREATER_THAN="greaterThan",e.GREATER_THAN_OR_EQUAL="greaterThanOrEqual",e.LESS_THAN="lessThan",e.LESS_THAN_OR_EQUAL="lessThanOrEqual",e.EXISTS="exists",e.CUSTOM="custom"})(Xt||(Xt={}));const Yt={FOREACH:"core.loop.foreach",WHILE:"core.loop.while",UNTIL:"core.loop.until"};class Qt extends k{constructor(e,t="GRAPH_EXECUTION_ERROR",o){super(e,Qt.name,500),this.graphCode=t,this.details=o,this.name=this.constructor.name}}class Zt extends Qt{constructor(e){super("Graph workflow contains an unsupported cycle","GRAPH_CYCLE_ERROR",e)}}class eo extends Qt{constructor(e,t){super(e,"GRAPH_INPUT_ERROR",t)}}class to extends Qt{constructor(e,t){super(e,"GRAPH_LOOP_LIMIT_ERROR",t)}}class oo extends Qt{constructor(e,t){super(e,"GRAPH_PINNING_ERROR",t)}}class no extends Qt{constructor(e,t){super(e,"GRAPH_PORT_ERROR",t)}}class ro extends Qt{constructor(e,t){super(e,"GRAPH_STORE_ERROR",t)}}class io extends Qt{constructor(e,t){super(e,"GRAPH_TOPOLOGY_ERROR",t)}}class ao extends Qt{constructor(e){super("Break signal","GRAPH_BREAK_SIGNAL",{value:e}),this.isBreakSignal=!0,this.name="GraphBreakSignal"}}class so extends Qt{constructor(e){super(`Graph run '${e}' was cancelled`,"GRAPH_RUN_CANCELLED",{runId:e}),this.name=so.name}}class lo extends x{constructor(e){super(`Graph workflow document rejected with ${e.length} issue(s): ${e.map(e=>`${e.code} at ${e.path} (${e.message})`).join("; ")}`),this.name=lo.name,this.issues=e}}class co{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 uo{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 Qt("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 po(e){if("string"!=typeof e)return;const t=e.trim();if(!t)return;const o=t.split(".");if(3!==o.length)return;const n=o[0].trim(),r=o[2].trim(),i=o[1].split(",").map(e=>e.trim()).filter(e=>e.length>0);return n&&r&&0!==i.length?{organization:n,departments:i,role:r}:void 0}function ho(e){return`${e.organization}.${e.departments.join(",")}.${e.role}`}function fo(e){if(!e||"string"!=typeof e.namespace||!e.parts)return!1;const t=po(e.namespace);return!!t&&ho(t)===ho(e.parts)}function go(e,t){const o="string"==typeof e?e.trim():"";if(o){if(t)for(const e of t)if(e&&e.namespace===o&&fo(e))return e.parts;return po(o)}}function mo(e,t,o={},n){const r=go(e,n),i=go(t,n);return!(!r||!i)&&r.organization===i.organization&&r.role===i.role&&("exact"===(o.mode??"inherit")?r.departments.length===i.departments.length&&r.departments.every((e,t)=>e===i.departments[t]):r.departments.length<=i.departments.length&&r.departments.every((e,t)=>e===i.departments[t]))}function yo(e,t,o={},n){return e.filter(e=>!t.some(t=>mo(t,e,o,n)))}function wo(e){return e.filter(e=>void 0===po(e))}function bo(e,t){const o=new Set;for(const n of e){const e=go(n,t);e&&o.add(e.role)}return[...o]}function vo(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}function Io(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 Eo(e){if(!e)return{};const t={},o=e.user;"string"==typeof o&&o&&(t.user=o);const n=e.organization;"string"==typeof n&&n&&(t.organization=n);const r=e.ip;"string"==typeof r&&r&&(t.ip=r);const i=vo(e.roles);i&&(t.roles=i);const a=vo(e.namespaces);return a&&(t.namespaces=a,t.namespaceCache=Oo(a)),t}function No(e){return e?Eo({user:Io(e,"user"),organization:Io(e,"organization"),ip:Io(e,"ip"),roles:Io(e,"roles"),namespaces:Io(e,"namespaces")}):{}}function Oo(e){const t=[];for(const o of e){const e=po(o);e&&t.push({namespace:o,parts:e})}return t}function Ao(...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??Oo(o.namespaces):void 0!==o.namespaceCache&&(t.namespaceCache=o.namespaceCache));return t}class xo{constructor(e={}){this.options=e}get enabled(){return!0===this.options.enabled}validate(e,o,n,r){if(!this.enabled)return;const i=r??this.options.logger??t.for("GraphAuth"),a=e.id||e.name||o.workflowId,s=(e=>{if(!e||"object"!=typeof e)return;const t=e.auth;return t&&"object"==typeof t&&!Array.isArray(t)?(e=>{if(!e)return;const t=fe(e.namespaces),o=fe(e.roles);if(!t&&!o)return;const n={};return t&&(n.namespaces=t),o&&(n.roles=o),n})(t):void 0})(e.metadata);this.assertGranted(`workflow '${a}'`,s?.namespaces??[],n,s?.roles??[],i);for(const e of o.nodes)this.assertGranted(`node '${e.id}'`,e.manifest.namespaces??[],n,[],i)}assertGranted(e,t,o,n,r){const i=o.namespaces??[],a=yo(t,i,this.options.match,o.namespaceCache),s=bo(i,o.namespaceCache),d=n.filter(e=>!s.includes(e));if(0===a.length&&0===d.length)return;const l=[...new Set([...wo(t),...wo(i)])],c=[];throw a.length&&c.push("namespace(s) "+a.join(", ")),d.length&&c.push("role(s) "+d.join(", ")),r.warn(`Graph access denied for ${e} for user ${o.user??"anonymous"}: missing ${c.join(" and ")}${l.length?`; malformed namespace(s) ${l.join(", ")} failed closed`:""}`),new L(`Access to ${e} requires ${c.join(" and ")}`)}}class ko{constructor(e){this.baseOptions=e,this.inner=t.for("GraphRun").for(this.attributeConfig(e))}attributeConfig(e){return{[le.NODE_ID]:e.nodeId,[le.WORKFLOW_ID]:e.workflowId,[le.RUN_ID]:e.runId,[le.USER]:e.user??null,[le.ROLES]:e.roles,[le.NAMESPACES]:e.namespaces,[le.ORGANIZATION]:e.organization,[le.IP]:e.ip}}emit(e,t,o){const n="string"==typeof t?t:t instanceof Error?t.message:t+"",r={level:e,message:n,timestamp:(new Date).toISOString(),runId:this.baseOptions.runId,workflowId:this.baseOptions.workflowId,nodeId:this.baseOptions.nodeId,user:this.baseOptions.user??null};void 0!==this.baseOptions.roles&&(r.roles=this.baseOptions.roles),void 0!==this.baseOptions.namespaces&&(r.namespaces=this.baseOptions.namespaces),void 0!==this.baseOptions.organization&&(r.organization=this.baseOptions.organization),void 0!==this.baseOptions.ip&&(r.ip=this.baseOptions.ip),void 0!==o&&(r.payload=o),this.baseOptions.forward({type:ce.GRAPH_RUN_LOG,payload:r}).catch(()=>{}),{benchmark:(e,t)=>this.inner.benchmark(e,t),fatal:(e,t)=>this.inner.fatal(e,t),critical:(e,t)=>this.inner.critical(e,t),silly:(e,t)=>this.inner.silly(e,t),trace:(e,t)=>this.inner.trace(e,t),verbose:(e,t)=>this.inner.verbose(e,t),info:(e,t)=>this.inner.info(e,t),warn:(e,t)=>this.inner.warn(e,t),error:(e,t)=>this.inner.error(e,t),debug:(e,t)=>this.inner.debug(e,t)}[e](n,o)}benchmark(e,t){this.emit("benchmark",e,t)}fatal(e,t,o){this.emit("fatal",e,t??o)}critical(e,t,o){this.emit("critical",e,t??o)}silly(e,t,o){this.emit("silly",e,"object"==typeof t?t:o)}trace(e,t){this.emit("trace",e,t)}verbose(e,t,o){this.emit("verbose",e,"object"==typeof t?t:o)}info(e,t){this.emit("info",e,t)}error(e,t,o){this.emit("error",e,t??o)}warn(e,t){this.emit("warn",e,t)}debug(e,t){this.emit("debug",e,t)}action(e,t,o){this.inner.action(e,t,o)}setConfig(){}for(e,t,...o){return this}clear(){return this}get root(){return this.inner.root}}function _o(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}class Do extends j{constructor(e,t,o,n,r,i,a,s,d={},l,c,u){super(),this.runId=e,this.parentRunId=t,this.workflowId=o,this.document=n,this.node=r,this.manifest=i,this.path=a,this.emitFn=s,this.metadata=d,this.engine=l,this.abortSignal=c,this.limits=u;const p=Eo(d);this.accumulate({...p,operation:"execute"});const h="string"==typeof d?.user?d.user:null;this.runLogger=new ko({runId:e,workflowId:o,nodeId:r.id,user:h,roles:_o(d?.roles),namespaces:_o(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 No(this)}async emit(e){await this.emitFn({...e,runId:this.runId,parentRunId:this.parentRunId,workflowId:this.workflowId,nodeId:this.node.id,path:e.path??this.path})}async progress(e){await this.emit({type:ce.NODE_OUTPUT,payload:e})}async log(e,t){await this.emit({type:ce.NODE_OUTPUT,payload:{message:e,payload:t}})}}class $o{constructor(e,t,o,n){this.nodeResults=new Map,this.events=[],this.activeDataEdges=new Set,this.runId=e,this.plan=t,this.valueStore=o,this.eventFactory=n,this.startedAt=new Date}recordNodeResult(e){this.nodeResults.set(e.nodeId,e)}activateDataEdge(e){this.activeDataEdges.add(e)}isDataEdgeActive(e){return this.activeDataEdges.has(e)}appendEvent(e){this.events.push(e)}finish(){this.finishedAt=new Date}}function Po(e,t,o,n,r){const i=e.valueStore.getWorkflowValues(),a={};for(const[t,o]of e.nodeResults)a[t]=o;const s=[...e.events];return{runId:e.runId,workflowId:t.id||t.name,status:n,document:t,inputs:{...o},outputs:i,nodeResults:a,events:s,startedAt:e.startedAt,finishedAt:e.finishedAt,metadata:r}}class So{constructor(e){this.catalogue=e}async resolveNodes(e,t,o,...n){const r=new Map;for(const[i,a]of e.entries()){const e=`nodes[${i}]`;if(this.catalogue.has(a.kind,...n))try{const e=await this.catalogue.resolveManifest(a.kind,a,o,...n),t=this.catalogue.getExecutor(a.kind,...n);r.set(a.id,{instance:a,manifest:e,executor:t})}catch(o){t.push({code:"kind.resolution-failed",path:e+".kind",message:`Node '${a.id}' kind '${a.kind}' failed to resolve: ${o.message}`,nodeId:a.id,details:{kind:a.kind}})}else t.push({code:"kind.unknown",path:e+".kind",message:`Node '${a.id}' references kind '${a.kind}' which is not registered in the backend catalogue`,nodeId:a.id,details:{kind:a.kind}})}return r}validateEffectivePorts(e,t,o,n){const r=!0===t.policies?.allowUndeclaredParameters,i=new Set(t.inputs.map(e=>e.id)),a=new Set(t.outputs.map(e=>e.id));for(const a of Object.keys(e.inputBindings??{}))r||i.has(a)||o.push({code:"binding.unknown-port",path:`${n}.inputBindings.${a}`,message:`Node '${e.id}' input binding '${a}' does not refer to an effective input port of kind '${t.kind}'`,nodeId:e.id,details:{effectiveInputs:[...i]}});for(const i of Object.keys(e.outputBindings??{}))r||a.has(i)||o.push({code:"binding.unknown-port",path:`${n}.outputBindings.${i}`,message:`Node '${e.id}' output binding '${i}' does not refer to an effective output port of kind '${t.kind}'`,nodeId:e.id,details:{effectiveOutputs:[...a]}})}}function Ro(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&&Ro(e,t,`${o}.nodes[${r.id}].loop.body`)}}function Co(e,t){if(!t)return{valid:!0};switch(t.type){case"any":default:return{valid:!0};case"string":return"string"!=typeof e?To("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}:To("number");case"boolean":return"boolean"!=typeof e?To("boolean"):{valid:!0};case"array":if(!Array.isArray(e))return To("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=Co(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 To(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=Co(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 To(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 jo=new Set(["loop"]),Mo=["secret","secrets","password","passwd","token","accessToken","refreshToken","apiKey","api_key","privateKey","credentials"];class Go{validate(e,t,o,n,r){this.validateParameters(e,t,o,n,r),this.validateMetadataKeys(e,t,o,n),this.validateDisabledBehavior(e,o,n),this.validateBindingShapes(e,t,o,n)}validateParameters(e,t,o,n,r){const i=!0===t.policies?.allowUndeclaredParameters,a=new Map(t.parameters.map(e=>[e.id,e]));for(const[r,s]of Object.entries(e.parameters??{})){const d=a.get(r);if(!d){i||o.push({code:"parameter.undeclared",path:`${n}.parameters.${r}`,message:`Node '${e.id}' sets parameter '${r}' which is not declared by kind '${t.kind}'`,nodeId:e.id,details:{kind:t.kind}});continue}if(void 0===s){o.push({code:"parameter.invalid",path:`${n}.parameters.${r}`,message:`Node '${e.id}' parameter '${r}' must not be undefined`,nodeId:e.id});continue}const l=this.checkParameterValue(s,d);l.valid||o.push({code:"parameter.type-mismatch",path:`${n}.parameters.${r}`,message:`Node '${e.id}' parameter '${r}' is invalid: ${l.message}`,nodeId:e.id,details:{expectedType:d.type}})}for(const i of t.parameters)void 0===(e.parameters??{})[i.id]&&(this.isParameterSatisfiedByInput(e,i.id,r)||(!0===i.required||(i.validation??[]).some(e=>"required"===e.kind))&&void 0===i.defaultValue&&o.push({code:"parameter.required-missing",path:`${n}.parameters.${i.id}`,message:`Node '${e.id}' is missing required parameter '${i.id}' declared by kind '${t.kind}'`,nodeId:e.id}))}isParameterSatisfiedByInput(e,t,o){return void 0!==(e.inputBindings??{})[t]||!0===o?.has(t)}checkParameterValue(e,t){if(ut(e))return{valid:!0};switch(t.type){case"string":case"code":case"expression":return"string"!=typeof e?To("string"):{valid:!0};case"number":return"number"==typeof e&&Number.isFinite(e)?{valid:!0}:To("number");case"boolean":return"boolean"!=typeof e?To("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}:To("array");case"object":case"resourceLocator":return null===e||"object"!=typeof e||Array.isArray(e)?To("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 i of Object.keys(e.metadata??{}))jo.has(i)?o.push({code:"metadata.key-not-allowed",path:`${n}.metadata.${i}`,message:`Node '${e.id}' metadata key '${i}' is reserved and must not be set directly`,nodeId:e.id}):Array.isArray(r)&&!r.includes(i)&&o.push({code:"metadata.key-not-allowed",path:`${n}.metadata.${i}`,message:`Node '${e.id}' metadata key '${i}' is not in the allowed metadata keys of kind '${t.kind}'`,nodeId:e.id})}validateDisabledBehavior(e,t,o){!0!==e.disabled&&!1!==e.disabled&&void 0!==e.disabled&&t.push({code:"disabled.invalid",path:o+".disabled",message:`Node '${e.id}' disabled flag must be a boolean`,nodeId:e.id});const n=(e.metadata??{}).disabledBehavior;void 0===n||ae(n)||t.push({code:"disabled.invalid-behavior",path:o+".metadata.disabledBehavior",message:`Node '${e.id}' disabled behavior '${n+""}' is not one of: ${ie.join(", ")}`,nodeId:e.id})}validateBindingShapes(e,t,o,n){for(const[r,i]of Object.entries(e.inputBindings??{})){if("literal"===i.mode){const a=t.inputs.find(e=>e.id===r);if(a?.schema){const t=Co(i.value,a.schema);t.valid||o.push({code:"binding.literal-invalid",path:`${n}.inputBindings.${r}`,message:`Node '${e.id}' literal binding for '${r}' is schema-invalid: ${t.message}`,nodeId:e.id})}}"expression"!==i.mode||"string"==typeof i.expression&&i.expression.trim()||o.push({code:"binding.expression-invalid",path:`${n}.inputBindings.${r}`,message:`Node '${e.id}' expression binding for '${r}' must contain a non-empty expression`,nodeId:e.id})}}validateBindingSatisfaction(e,t,o,n,r,i={}){const a=new Set(o.filter(e=>"data"===e.type).map(e=>e.targetPort)),s=new Set(Object.entries(e.inputBindings??{}).map(([e])=>e));for(const t of a){const o=(e.inputBindings??{})[t];o&&"literal"===o.mode&&!0!==i.allowLiteralAndEdgeBindings&&n.push({code:"binding.conflict",path:`${r}.inputBindings.${t}`,message:`Node '${e.id}' input '${t}' has both an incoming edge and a literal binding`,nodeId:e.id})}for(const o of t.inputs)!0===o.required&&(a.has(o.id)||s.has(o.id)||void 0===(e.parameters??{})[o.id]&&n.push({code:"topology.required-input-unsatisfiable",path:r+".parameters",message:`Node '${e.id}' required input '${o.id}' has no incoming edge or binding`,nodeId:e.id,details:{port:o.id}}))}static disabledBehaviorOf(e,t){const o=(e.metadata??{}).disabledBehavior;if(ae(o))return o;const n=t?.disabledBehavior;return ae(n)?n:"skip"}}class Uo{resolveEdges(e,t,o){const n=new Set(e.inputs.map(e=>e.id)),r=new Set(e.outputs.map(e=>e.id)),i=[];for(const[a,s]of(e.edges??[]).entries()){const e=`edges[${a}]`,d=this.resolveEndpoint(s,"source",t,n,r,o,e),l=this.resolveEndpoint(s,"target",t,n,r,o,e);if(!d||!l)continue;if(!this.validateDirectionAndType(s,d,l,t,o,e))continue;const c={id:s.id,type:s.type,sourceNodeId:d.nodeId,sourcePort:d.port,targetNodeId:l.nodeId,targetPort:l.port,metadata:s.metadata,edge:s};void 0!==s.label&&(c.label=s.label),i.push(c)}return i}resolveEndpoint(e,t,o,n,r,i,a){const s=e[t];return Xe(s)?("source"===t?n.has(s.port):r.has(s.port))?{nodeId:Ft,port:s.port}:void i.push({code:"edge.unknown-port",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} references workflow port '${s.port}' which is not declared on the document boundary`,edgeId:e.id,details:{scope:"workflow",port:s.port}}):Ye(s)?o.get(s.nodeId)?{nodeId:s.nodeId,port:s.port}:void i.push({code:"edge.unknown-node",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} references node '${s.nodeId}' which is not part of the document or did not resolve`,edgeId:e.id,nodeId:s.nodeId}):void i.push({code:"edge.invalid-endpoint",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} endpoint is not a valid GraphEndpoint`,edgeId:e.id})}validateDirectionAndType(e,t,o,n,r,i){let a=!0;const s=t.nodeId===Ft?void 0:n.get(t.nodeId),d=o.nodeId===Ft?void 0:n.get(o.nodeId),l=e=>!0===e?.manifest.policies?.allowUndeclaredParameters;if("data"===e.type)!s||l(s)||this.hasPortDirection(s,t.port,"output")||(this.pushPortIssue(e,"source",t,s,r,i),a=!1),!d||l(d)||this.hasPortDirection(d,o.port,"input")||(this.pushPortIssue(e,"target",o,d,r,i),a=!1);else{if(!s||!d)return r.push({code:"edge.boundary-routing",path:i,message:`Connection edge '${e.id}' must connect two node connection ports; the workflow boundary only routes data`,edgeId:e.id}),!1;if(!(l(s)||l(d)||this.hasPortDirection(s,t.port,"connection")&&this.hasPortDirection(d,o.port,"connection")))return r.push({code:"edge.type-mismatch",path:i,message:`Connection edge '${e.id}' endpoints must both be connection ports`,edgeId:e.id,details:{sourcePort:t.port,targetPort:o.port}}),!1}return a}hasPortDirection(e,t,o){return("input"===o?e.manifest.inputs:"output"===o?e.manifest.outputs:e.manifest.connections??[]).some(e=>e.id===t)}pushPortIssue(e,t,o,n,r,i){const a="source"===t?"output":"input";r.push({code:"data"===e.type?"edge.invalid-direction":"edge.type-mismatch",path:`${i}.${t}`,message:`Edge '${e.id}' ${t} port '${o.port}' on node '${o.nodeId}' is not an ${a} port of kind '${n.manifest.kind}'`,edgeId:e.id,nodeId:o.nodeId,details:{port:o.port,expected:a}})}}class Fo{validate(e,t){this.validateDuplicates(e.edges,t),this.validatePolicies(e,t)}validateDuplicates(e,t){const o=new Map;for(const n of e){const e=`${n.sourceNodeId}:${n.sourcePort}->${n.targetNodeId}:${n.targetPort}`,r=o.get(e);r?t.push({code:"connection.duplicate-edge",path:`edges[${n.id}]`,message:`Edge '${n.id}' duplicates the routing of edge '${r.id}' (${e})`,edgeId:n.id,details:{duplicateOf:r.id,routing:e}}):o.set(e,n)}}validatePolicies(e,t){const o=new Map;for(const t of e.edges){if("connection"!==t.type)continue;const e=`${t.targetNodeId}:${t.targetPort}`,n=o.get(e)??[];n.push(t),o.set(e,n)}for(const o of e.edges){if("connection"!==o.type)continue;const n=e.nodeById.get(o.targetNodeId),r=n?.manifest.connections?.find(e=>e.id===o.targetPort)?.connectionPolicy;this.validateEdgePolicy(o,e.nodeById,r,t)}for(const[n,r]of o){const o=n.lastIndexOf(":"),i=n.slice(0,o),a=n.slice(o+1),s=e.nodeById.get(i),d=s?.manifest.connections?.find(e=>e.id===a)?.connectionPolicy;if(!d)continue;const l=void 0!==d.maxConnections?d.maxConnections:!1===d.allowMultiple?1:1/0;r.length>l&&t.push({code:"connection.max-connections",path:`edges[${r[r.length-1].id}]`,message:`Connection port '${a}' on node '${i}' accepts at most ${l} connection(s) but has ${r.length}`,nodeId:i,edgeId:r[r.length-1].id,details:{port:a,max:l,actual:r.length}})}}validateEdgePolicy(e,t,o,n){if(e.sourceNodeId===e.targetNodeId&&!o?.allowSelf)return void n.push({code:"connection.self-connection",path:`edges[${e.id}]`,message:`Edge '${e.id}' connects node '${e.sourceNodeId}' to itself, which the target port policy does not allow`,edgeId:e.id,nodeId:e.sourceNodeId});if(!o)return;const r=t.get(e.sourceNodeId),i=r?.manifest.kind;if(!o.allowedNodeKinds?.length||i&&o.allowedNodeKinds.includes(i)||n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source kind '${i??"unknown"}' is not in the allowed node kinds of target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{allowedNodeKinds:o.allowedNodeKinds}}),i&&o.blockedNodeKinds?.includes(i)&&n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source kind '${i}' is blocked by target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{blockedNodeKinds:o.blockedNodeKinds}}),o.allowedPortCategories?.length){const t=r?.manifest.connections?.find(t=>t.id===e.sourcePort)?.category;t&&o.allowedPortCategories.includes(t)||n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source port '${e.sourcePort}' category '${t??"unknown"}' is not in the allowed port categories of target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{allowedPortCategories:o.allowedPortCategories}})}}}class Bo{constructor(e){this.authorizer=e}async validate(e,t,o,n){const r=this.collectReferences(e,t);for(const i of t.credentials??[]){const a=r.find(e=>void 0===e.credentialType||e.credentialType===i.type);if(a){if(this.checkType(a,i))o.push({code:"credential.type-mismatch",path:n,message:`Node '${e.id}' credential '${a.credentialId}' has type '${a.credentialType}' but kind '${t.kind}' requires '${i.type}'`,nodeId:e.id,details:{credentialType:a.credentialType??"",requiredType:i.type}});else if(this.authorizer){if(!await this.authorizer.hasCredential(a)){o.push({code:"credential.not-found",path:n,message:`Node '${e.id}' references credential '${a.credentialId}' which does not exist`,nodeId:e.id,details:{credentialId:a.credentialId}});continue}await this.authorizer.authorize(a,i)||o.push({code:"credential.unauthorized",path:n,message:`Node '${e.id}' is not authorized to use credential '${a.credentialId}'`,nodeId:e.id,details:{credentialId:a.credentialId}})}}else!1!==i.required&&o.push({code:"credential.missing",path:n,message:`Node '${e.id}' does not provide the required credential of type '${i.type}'`,nodeId:e.id,details:{credentialType:i.type}})}this.scanPlainSecrets(e,o,n)}collectReferences(e,t){const o=[];for(const n of t.parameters){if("credential"!==n.type)continue;const t=(e.parameters??{})[n.id];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(Mo);for(const[r,i]of Object.entries(e.parameters??{}))this.scanPlainSecretValue(i,[r],e,o+".parameters",n,t);for(const[r,i]of Object.entries(e.metadata??{}))this.scanPlainSecretValue(i,[r],e,o+".metadata",n,t)}scanPlainSecretValue(e,t,o,n,r,i,a=0){const s=t[t.length-1];if(r.has(s))i.push({code:"credential.plain-secret",path:`${n}.${t.join(".")}`,message:`Node '${o.id}' carries plain secret material in '${t.join(".")}'; workflow documents may only hold credential references`,nodeId:o.id});else if(8>a&&null!==e)if(Array.isArray(e))for(const s of e)this.scanPlainSecretValue(s,[...t,"[]"],o,n,r,i,a+1);else if("object"==typeof e)for(const[s,d]of Object.entries(e))this.scanPlainSecretValue(d,[...t,s],o,n,r,i,a+1)}}class qo extends x{constructor(e,t=[]){super(e),this.issues=t,this.name=qo.name}}class Wo extends x{constructor(e,t){super(e),this.edgeId=t,this.name=Wo.name}}class Vo extends M{constructor(e){super(e),this.name=Vo.name}}const Ho={maxDocumentBytes:2e6,maxNestingDepth:10,maxNodes:500,maxEdges:1e3},Ko=["node","definition","executor","execute","ports","component"];function zo(e){if(!e||"object"!=typeof e)return!1;const t=e;return pt(t.document)&&Array.isArray(t.nodes)&&Array.isArray(t.edges)&&t.nodeById instanceof Map&&t.incomingByNode instanceof Map&&t.outgoingByNode instanceof Map&&t.nodes.every(e=>null!==e&&"object"==typeof e&&"object"==typeof e.instance&&"object"==typeof e.manifest&&"object"==typeof e.executor)}function Jo(e,t){const o=[];for(const n of Object.keys(e))Ko.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 Xo{constructor(e){this.options=e,this.parameterValidator=new Go,this.edgeValidator=new Uo,this.connectionPolicyValidator=new Fo,this.nodeValidator=new So(e.catalogue),this.credentialValidator=new Bo(e.credentialAuthorizer)}async validateOrThrow(e,...t){const o=await this.validate(e,0,...t);if(!o.valid||!o.resolved)throw new qo(`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={...Ho,...this.options.limits};if(!await this.validateStructure(e,r,t,n,...o))return{valid:!1,issues:n};const i=await this.nodeValidator.resolveNodes(e.nodes,n,this.options.resolutionContext,...o),a=e.nodes.filter(e=>i.has(e.id)).map(e=>i.get(e.id)),s=(e=>{const t=new Map;for(const o of e.edges??[]){if("data"!==o.type)continue;const e=o.target;if("node"!==e.scope)continue;const n=t.get(e.nodeId)??new Set;n.add(e.port),t.set(e.nodeId,n)}return t})(e);for(const e of a)this.parameterValidator.validate(e.instance,e.manifest,n,`nodes[${e.instance.id}]`,s.get(e.instance.id));for(const e of a)this.nodeValidator.validateEffectivePorts(e.instance,e.manifest,n,`nodes[${e.instance.id}]`);const d=this.edgeValidator.resolveEdges(e,i,n),l=new Map,c=new Map;for(const e of d){if(e.targetNodeId!==Ft){const t=l.get(e.targetNodeId)??[];t.push(e),l.set(e.targetNodeId,t)}if(e.sourceNodeId!==Ft){const t=c.get(e.sourceNodeId)??[];t.push(e),c.set(e.sourceNodeId,t)}}this.connectionPolicyValidator.validate({edges:d,nodeById:i},n),this.validateAcyclicity(a,d,e,n),Ro(e,n);for(const e of a)this.parameterValidator.validateBindingSatisfaction(e.instance,e.manifest,l.get(e.instance.id)??[],n,`nodes[${e.instance.id}]`,{allowLiteralAndEdgeBindings:this.options.allowLiteralAndEdgeBindings});this.validateRequiredWorkflowOutputs(e,c,n);for(const e of a)await this.credentialValidator.validate(e.instance,e.manifest,n,`nodes[${e.instance.id}]`);return this.validateCapabilities(a,n),n.length>0?{valid:!1,issues:n}:{valid:!0,issues:n,resolved:{document:e,nodes:a,edges:d,nodeById:i,incomingByNode:l,outgoingByNode:c}}}async validateStructure(e,t,o,n,...r){if(!pt(e))return n.push({code:"document.shape",path:"$",message:"Payload is not a canonical GraphWorkflowDocument: id and name must be strings and inputs, outputs, nodes and edges must be arrays"}),!1;if(e.id&&e.id.trim()||n.push({code:"document.empty-id",path:"$.id",message:"Workflow document id must be a non-empty string"}),!Ue(e))return n.push({code:"document.json-unsafe",path:"$",message:"Document contains JSON-unsafe values: functions, class instances, undefined, NaN/Infinity, symbol keys and unsafe prototype keys are rejected"}),!1;n.push(...Jo(e,"$"));for(const t of[...e.inputs,...e.outputs])n.push(...Jo(t,"ports"));for(const t of e.nodes)n.push(...Jo(t,`nodes[${t.id}]`));for(const t of e.edges)n.push(...Jo(t,`edges[${t.id}]`));this.validateUniqueIds(e,n),this.validateLimits(e,t,o,n);try{ot(e)}catch(e){n.push({code:"document.structure",path:"$",message:e instanceof Error?e.message:e+""})}return await this.validateNestedBodies(e,o,n,...r),!0}validateUniqueIds(e,t){const o=new Set,n=new Set;for(const[r,i]of[["input",e.inputs],["output",e.outputs]]){const e="input"===r?o:n;for(const o of i)e.has(o.id)?t.push({code:"document.duplicate-port-id",path:`${"input"===r?"inputs":"outputs"}[${o.id}]`,message:`Workflow ${r} port '${o.id}' is declared more than once; workflow port ids must be unique`}):e.add(o.id)}const r=new Set;for(const o of e.nodes)r.has(o.id)?t.push({code:"document.duplicate-node-id",path:`nodes[${o.id}]`,message:`Node '${o.id}' is declared more than once; node ids must be unique`,nodeId:o.id}):r.add(o.id);const i=new Set;for(const o of e.edges)i.has(o.id)?t.push({code:"document.duplicate-edge-id",path:`edges[${o.id}]`,message:`Edge '${o.id}' is declared more than once; edge ids must be unique`,edgeId:o.id}):i.add(o.id)}validateLimits(e,t,o,n){e.nodes.length>t.maxNodes&&n.push({code:"document.limit.nodes",path:"$.nodes",message:`Document declares ${e.nodes.length} nodes; at most ${t.maxNodes} are allowed`,details:{count:e.nodes.length,limit:t.maxNodes}}),e.edges.length>t.maxEdges&&n.push({code:"document.limit.edges",path:"$.edges",message:`Document declares ${e.edges.length} edges; at most ${t.maxEdges} are allowed`,details:{count:e.edges.length,limit:t.maxEdges}}),o>t.maxNestingDepth&&n.push({code:"document.limit.depth",path:"$",message:`Document nests loop bodies ${o} levels deep; at most ${t.maxNestingDepth} levels are allowed`,details:{depth:o,limit:t.maxNestingDepth}});const r=Buffer.byteLength(JSON.stringify(e),"utf8");r>t.maxDocumentBytes&&n.push({code:"document.limit.size",path:"$",message:`Document serializes to ${r} bytes; at most ${t.maxDocumentBytes} bytes are allowed`,details:{bytes:r,limit:t.maxDocumentBytes}})}async validateNestedBodies(e,t,o,...n){for(const r of e.nodes){const e=[["loop.body",r.loop?.body],["errorBoundary.try",r.errorBoundary?.try],["errorBoundary.catch",r.errorBoundary?.catch],["errorBoundary.finally",r.errorBoundary?.finally]];for(const[i,a]of e){if(!a)continue;const e=await this.validate(a,t+1,...n);for(const t of e.issues)o.push({...t,path:`nodes[${r.id}].${i}.${t.path}`,nodeId:t.nodeId??r.id})}}}validateAcyclicity(e,t,o,n){const r=new Set(e.map(e=>e.instance.id)),i=new Map(e.map(e=>[e.instance.id,0]));for(const e of t)r.has(e.sourceNodeId)&&i.has(e.targetNodeId)&&i.set(e.targetNodeId,(i.get(e.targetNodeId)??0)+1);const a=[...i.entries()].filter(([,e])=>0===e).map(([e])=>e),s=[];for(;a.length>0;){const e=a.shift();s.push(e);for(const o of t){if(o.sourceNodeId!==e)continue;if(!i.has(o.targetNodeId))continue;const t=(i.get(o.targetNodeId)??1)-1;i.set(o.targetNodeId,t),0===t&&a.push(o.targetNodeId)}}if(s.length!==i.size){const e=[...i.keys()].filter(e=>!s.includes(e));n.push({code:"topology.cycle",path:"$.edges",message:`Workflow '${o.id}' contains an unsupported cycle involving node(s): ${e.join(", ")}`,details:{cyclicNodes:e}})}}validateRequiredWorkflowOutputs(e,t,o){const n=new Set;for(const e of t.values())for(const t of e)t.targetNodeId===Ft&&n.add(t.targetPort);for(const t of e.outputs)!0===t.required&&void 0===t.defaultValue&&(n.has(t.id)||o.push({code:"topology.required-output-unsatisfiable",path:`outputs[${t.id}]`,message:`Required workflow output '${t.id}' has no incoming edge from any node`}))}validateCapabilities(e,t){for(const o of e){const e=o.manifest;for(const n of e.capabilities??[])gt(n)||t.push({code:"capability.invalid",path:`nodes[${o.instance.id}]`,message:`Kind '${e.kind}' declares unknown capability '${n+""}'`,nodeId:o.instance.id,details:{capability:n+""}});!0!==e.policies?.allowUndeclaredParameters&&o.instance.loop&&((e.capabilities??[]).includes("loop")||t.push({code:"capability.loop-not-supported",path:`nodes[${o.instance.id}].loop`,message:`Node '${o.instance.id}' carries loop configuration but kind '${e.kind}' does not declare the 'loop' capability`,nodeId:o.instance.id}))}}}let Yo=class extends U{constructor(){super()}async plan(e,...t){const{log:o}=(await this.logCtx(t,"plan",!0)).for(this.plan);if(o.debug(`Planning resolved workflow '${e?.document?.id??"unknown"}'`),!zo(e))throw new io("GraphExecutionPlanner.plan accepts only a GraphResolvedWorkflow produced by the nine-stage validation gate; raw workflow definitions and inline node definitions are rejected",{received:(n=e,n&&"object"==typeof n?{reason:"input is not a GraphResolvedWorkflow",looksLikeWorkflowDefinition:"nodes"in n&&"relations"in n&&!("nodeById"in n),hasResolvedNodes:Array.isArray(n.nodes)}:{reason:"input is not an object"})});var n;const r=this.buildPlanNodes(e),i=this.buildPlanEdges(e),a=this.buildIncomingMap(i),s=this.buildOutgoingMap(i),d=this.topologicalLayers(r,i);return{resolved:e,workflowId:e.document.id||e.document.name,nodes:r,edges:i,layers:d,incomingByNode:a,outgoingByNode:s}}buildPlanNodes(e){return e.nodes.map(e=>({id:e.instance.id,kind:e.manifest.kind,instance:e.instance,manifest:e.manifest,executor:e.executor,inputPorts:e.manifest.inputs.map(e=>e.id),outputPorts:e.manifest.outputs.map(e=>e.id),connectionPorts:(e.manifest.connections??[]).map(e=>e.id),metadata:e.instance.metadata}))}buildPlanEdges(e){return e.edges.map(e=>({id:e.id,type:e.type,sourceNodeId:e.sourceNodeId,sourcePort:e.sourcePort,targetNodeId:e.targetNodeId,targetPort:e.targetPort,...void 0!==e.label?{label:e.label}:{},metadata:e.metadata}))}buildIncomingMap(e){const t=new Map;for(const o of e){if(o.targetNodeId===Ft)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===Ft)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!==Ft),n=new Set(o.map(e=>e.id)),r=t.filter(e=>n.has(e.sourceNodeId)&&n.has(e.targetNodeId)),i=new Map;for(const e of o)i.set(e.id,0);for(const e of r)i.set(e.targetNodeId,(i.get(e.targetNodeId)??0)+1);const a=[],s=new Set;let d=o.filter(e=>0===(i.get(e.id)??0)),l=0;for(;d.length>0;){const e={index:l++,nodes:d};a.push(e);const t=[];for(const e of d){s.add(e.id);const n=r.filter(t=>t.sourceNodeId===e.id);for(const e of n){const n=(i.get(e.targetNodeId)??1)-1;if(i.set(e.targetNodeId,n),0===n&&!s.has(e.targetNodeId)){const n=o.find(t=>t.id===e.targetNodeId);n&&t.push(n)}}}d=t}if(s.size!==o.length){const e=o.filter(e=>!s.has(e.id)).map(e=>e.id);throw new Zt({unplannedNodes:e,workflowId:o[0]?.manifest.kind})}return a}};Yo=D([G(),$("design:paramtypes",[])],Yo);let Qo=class extends T{constructor(e){super(e)}};function Zo(e){return[e.namespace??"default",e.workflowId,e.nodeId,e.version??"default",e.fingerprint].join(":")}function en(e){return new Qo({id:Zo(e.key),workflowId:e.key.workflowId,nodeId:e.key.nodeId,fingerprint:e.key.fingerprint,...void 0!==e.key.namespace?{namespace:e.key.namespace}:{},...void 0!==e.key.version?{version:e.key.version}:{},pinned:e.pinned,outputs:e.outputs,createdAt:new Date(e.createdAt),updatedAt:new Date(e.updatedAt),...e.expiresAt?{expiresAt:new Date(e.expiresAt)}:{},...e.metadata?{metadata:e.metadata}:{}})}function tn(e){return{key:{workflowId:e.workflowId,nodeId:e.nodeId,fingerprint:e.fingerprint,...void 0!==e.namespace?{namespace:e.namespace}:{},...void 0!==e.version?{version:e.version}:{}},outputs:e.outputs,pinned:e.pinned,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString(),...e.expiresAt?{expiresAt:e.expiresAt.toISOString()}:{},...e.metadata?{metadata:e.metadata}:{}}}D([P({type:String,generated:!1}),$("design:type",String)],Qo.prototype,"id",void 0),D([S(),R(),$("design:type",String)],Qo.prototype,"workflowId",void 0),D([S(),R(),$("design:type",String)],Qo.prototype,"nodeId",void 0),D([S(),$("design:type",String)],Qo.prototype,"fingerprint",void 0),D([S(),$("design:type",String)],Qo.prototype,"namespace",void 0),D([S(),$("design:type",String)],Qo.prototype,"version",void 0),D([S(),$("design:type",Boolean)],Qo.prototype,"pinned",void 0),D([S(),$("design:type",Object)],Qo.prototype,"outputs",void 0),D([S(),$("design:type",Date)],Qo.prototype,"createdAt",void 0),D([S(),$("design:type",Date)],Qo.prototype,"updatedAt",void 0),D([S(),$("design:type",Date)],Qo.prototype,"expiresAt",void 0),D([S(),$("design:type",Object)],Qo.prototype,"metadata",void 0),Qo=D([C("graph_value"),E(),$("design:paramtypes",[Object])],Qo);let on=class extends B{constructor(e){super(e,Qo,!0),this.runtimeValues=new Map}seedWorkflowInputs(e){this.runtimeValues.set(Ft,{...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(Ft)??{};o[e]=t,this.runtimeValues.set(Ft,o)}getWorkflowValues(){return{...this.runtimeValues.get(Ft)??{}}}snapshot(){return Object.fromEntries(this.runtimeValues.entries())}async readCached(e,...t){try{return tn(await this.read(Zo(e),...t))}catch{return}}async writeCached(e,t,...o){const n=Zo(e);let r;try{r=await this.read(n,...o)}catch{r=void 0}r?await this.update(Object.assign(r,en(t)),...o):await this.create(en(t),...o)}async deleteCached(e,...t){try{await this.delete(Zo(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=>tn(e)).filter(t=>((e,t)=>!(void 0!==t.workflowId&&e.workflowId!==t.workflowId||void 0!==t.nodeId&&e.nodeId!==t.nodeId||void 0!==t.namespace&&e.namespace!==t.namespace||void 0!==t.version&&e.version!==t.version||void 0!==t.fingerprint&&e.fingerprint!==t.fingerprint))(t.key,e))}async clearRun(e,...t){const o=await this.select().execute(...t);for(const e of o)await this.delete(e.id,...t)}readRuntimeValues(e){return this.runtimeValues.get(e)}writeRuntimeValues(e,t){this.runtimeValues.set(e,{...t})}getAdapter(){return this.adapter}};function nn(e){return new(0,B.forModel(Qo,e.alias).constructor)(e)}on=D([F(Qo,m),$("design:paramtypes",[Function])],on);class rn{static upstreamNodes(e,t,o=!1){const n=new Set,r=[e];for(;r.length;){const e=r.pop(),i=t.get(e)??[];for(const e of i)!o&&this.isBoundary(e.sourceNodeId)||n.has(e.sourceNodeId)||(n.add(e.sourceNodeId),r.push(e.sourceNodeId))}return n}static downstreamNodes(e,t,o=!1){const n=new Set,r=[e];for(;r.length;){const e=r.pop(),i=t.get(e)??[];for(const e of i)!o&&this.isBoundary(e.targetNodeId)||n.has(e.targetNodeId)||(n.add(e.targetNodeId),r.push(e.targetNodeId))}return n}static isBoundary(e){return"$workflow"===e}}class an{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 oo(`Node '${e}' not found in plan`);if(!this.policy.canPin(o))throw new oo(`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 oo(`Node '${o}' has no completed output to pin`);const i=r.inputs??{},a=this.dependencyFingerprints(t,o,e.result),s=this.createValueKey(e.document.id,n,i,a),d=(new Date).toISOString(),l={key:s,outputs:r.outputs,pinned:!0,createdAt:d,updatedAt:d,metadata:{...e.result.metadata,nodeId:o}};await this.store.writeCached(s,l)}}async unpinNode(e){const t={workflowId:e.document.id,nodeId:e.nodeId,fingerprint:e.fingerprint,namespace:e.namespace};await this.store.deleteCached(t)}async readPinnedValue(e,t,o,n,r){const i=this.createValueKey(e,t,o,n,r),a=await this.store.readCached(i);if(a&&a.pinned){if(a.expiresAt&&new Date(a.expiresAt)<new Date)return;return a}}createValueKey(e,t,o,n,r){return{workflowId:e,nodeId:t.id,fingerprint:this.computeFingerprint(e,t,o,n),namespace:r}}computeFingerprint(e,t,o,n){const r={workflowId:e,nodeId:t.id,nodeKind:t.kind,parameters:this.stableSerialize(t.instance.parameters??{}),inputBindings:this.stableSerialize(t.instance.inputBindings??{}),metadata:this.stableSerialize(this.relevantMetadata(t)),inputs:this.stableSerialize(o),dependencyFingerprints:this.stableSerialize(n)},i=this.stableSerialize(r);return this.simpleHash(i)}relevantMetadata(e){const t={...e.metadata??{}};return delete t.ui,delete t.position,delete t.visual,t}topologicalOrder(e,t){const o=[],n=new Set,r=i=>{if(n.has(i))return;n.add(i);const a=rn.upstreamNodes(i,e.incomingByNode,!1);for(const e of a)t.has(e)&&r(e);o.push(i)};for(const e of t)r(e);return o}dependencyFingerprints(e,t,o){const n=this.dependencyResolver.getDependencies(e,t),r={};for(const t of n){const n=e.nodes.find(e=>e.id===t);if(n){const i=o.nodeResults[t],a=i?.inputs??{},s=this.dependencyFingerprints(e,t,o);r[t]=this.computeFingerprint(e.workflowId,n,a,s)}}return r}stableSerialize(e){return null===e||"object"!=typeof e?JSON.stringify(e):Array.isArray(e)?`[${e.map(e=>this.stableSerialize(e)).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${this.stableSerialize(e[t])}`).join(",")}}`}simpleHash(e){let t=0;for(let o=0;o<e.length;o++)t=(t<<5)-t+e.charCodeAt(o),t|=0;return`fp_${Math.abs(t).toString(16).padStart(8,"0")}_${e.length}`}}const sn={enabled:!0,strategy:"manual",includeDependencies:!0};function dn(e){return!0===e?.enabled&&"disabled"!==e.strategy}class ln{canPin(e){return dn(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?{...sn,...t}:{...sn,enabled:!1}}}class cn{getDependencies(e,t){return rn.upstreamNodes(t,e.incomingByNode,!1)}getPinSet(e,t){const o=this.getDependencies(e,t);return o.add(t),o}}class un extends q{constructor(){super()}async initialize(...e){const t=e[0];if(!t||"object"!=typeof t||!t.registry)return this._config=void 0,this._client=void 0,{config:void 0,client:void 0};const o=t.catalogue??t.registry.catalog,n=t.valueAdapter??W.current;if(!n)throw new Qt("GraphExecutionEngine requires a Decaf adapter for cached/pinned values: pass `valueAdapter` or configure one via `Adapter.setCurrent(...)`","GRAPH_VALUE_ADAPTER_MISSING");const r={registry:t.registry,catalogue:o,planner:t.planner??new Yo,valueAdapter:n,eventEmitter:t.eventEmitter??new co,documentValidator:t.documentValidator??new Xo({catalogue:o,limits:t.documentLimits,credentialAuthorizer:t.credentialAuthorizer}),authValidator:new xo({enabled:!0===t.authEnabled,...t.authMatch?{match:t.authMatch}:{}}),...t.codeSandboxEvaluator?{codeSandboxEvaluator:t.codeSandboxEvaluator}:{}};return this._config=t,this._client=r,await(t.onEngineCreated?.(this)),{config:t,client:r}}get codeSandboxEvaluator(){return this.client.codeSandboxEvaluator}get emitter(){return this.client.eventEmitter}get planner(){return this.client.planner}get valueAdapter(){return this.client.valueAdapter}get defaultOptions(){return this.config.defaultOptions??{}}get documentValidator(){return this.client.documentValidator}observe(e){return this.emitter.observe(e)}unObserve(e){this.emitter.unObserve(e)}async dispatchEvent(e){await this.emitter.updateObservers(e)}async execute(e,t={},o={},...n){const{log:r,ctx:i}=(await this.logCtx(n,"execute",!0)).for(this.execute);r.debug(`Executing workflow '${e.id||e.name}'`);const a=this.mergeOptions(o);this.assertNotAborted(a);const s=Ao(No(i),a.auth);a.auth=s,a.metadata={...a.metadata??{},...s};const d=a.runId??this.generateRunId(),l=a.path??[],c=new uo,u=nn(this.valueAdapter);u.seedWorkflowInputs(this.withWorkflowInputDefaults(e,t));const p=async t=>{await this.emitEvent(m,{type:t.type??ce.NODE_OUTPUT,runId:d,parentRunId:a.parentRunId,workflowId:e.id||e.name,nodeId:t.nodeId,path:t.path??l,...t})},h=async t=>{const o=c.create({id:"",sequence:0,timestamp:new Date,runId:d,parentRunId:a.parentRunId,workflowId:e.id||e.name,path:l,...t});await this.emitter.updateObservers(o)};await h({type:ce.VALIDATION_STARTED,status:se.PLANNING});const f=await this.documentValidator.validate(e,0,i);if(!f.valid||!f.resolved)throw await h({type:ce.VALIDATION_FAILED,status:se.FAILED,payload:{issues:f.issues}}),new qo(`Graph workflow document '${e.id}' failed validation with ${f.issues.length} issue(s)`,f.issues);await h({type:ce.VALIDATION_COMPLETED,status:se.PLANNING,payload:{issues:f.issues.length}}),this.assertNotAborted(a);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 $o(d,g,u,c);await this.emitEvent(m,{type:ce.WORKFLOW_STARTED,runId:d,parentRunId:a.parentRunId,workflowId:g.workflowId,path:l,status:se.RUNNING,payload:{inputs:t}}),await this.emitEvent(m,{type:ce.WORKFLOW_PLANNED,runId:d,parentRunId:a.parentRunId,workflowId:g.workflowId,path:l,status:se.PLANNING,payload:{layers:g.layers.length,nodes:g.nodes.length}});try{for(const e of g.layers)this.assertNotAborted(a),await this.executeLayer(m,g,e.nodes,a,p);this.assertNotAborted(a);const o=[...m.nodeResults.values()].find(e=>e.status===se.FAILED);if(o?.error)throw new Qt(o.error.message,o.error.code??"GRAPH_EXECUTION_ERROR",o.error.details);return m.finish(),await this.emitEvent(m,{type:ce.WORKFLOW_COMPLETED,runId:d,parentRunId:a.parentRunId,workflowId:g.workflowId,path:l,status:se.SUCCEEDED,payload:{outputs:u.getWorkflowValues()}}),Po(m,e,t,se.SUCCEEDED,a.metadata)}catch(o){if(o instanceof ao)throw m.finish(),o;m.finish();const n=this.toErrorPayload(o);return o instanceof so||!0===a.abortSignal?.aborted?(await this.emitEvent(m,{type:ce.WORKFLOW_CANCELLED,runId:d,parentRunId:a.parentRunId,workflowId:g.workflowId,path:l,status:se.CANCELLED,error:n}),Po(m,e,t,se.CANCELLED,a.metadata)):(await this.emitEvent(m,{type:ce.WORKFLOW_FAILED,runId:d,parentRunId:a.parentRunId,workflowId:g.workflowId,path:l,status:se.FAILED,error:n}),Po(m,e,t,se.FAILED,a.metadata))}}async pinNode(e){const t=this.createPinningService();await t.pinNode(e),await this.emitPinningEvent(e.nodeId,ce.NODE_PINNED)}async unpinNode(e){const t=this.createPinningService();await t.unpinNode(e),await this.emitPinningEvent(e.nodeId,ce.NODE_UNPINNED)}createPinningService(){const e=nn(this.valueAdapter);return new an(e,new ln,new cn)}async emitPinningEvent(e,t){const o=(new uo).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 i=Math.max(1,n.concurrency??4),a=[...o];for(;a.length>0;){const o=a.splice(0,i);await Promise.all(o.map(o=>this.executeNode(e,t,o,n,r)))}}async executeNode(e,t,o,n,r){if(this.assertNotAborted(n),!this.isNodeActivated(e,t,o))return void await this.skipInactiveNode(e,t,o,n);if(!0===o.instance.disabled)return void await this.executeDisabledNode(e,t,o,n);const i=new Date,a=[...n.path??[],o.id];await this.emitEvent(e,{type:ce.NODE_STARTED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.RUNNING}),this.emitNodeStateChanged(e,t,o,a,de.RUNNING,se.RUNNING);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:se.CACHED,inputs:s,outputs:n.outputs,startedAt:i,finishedAt:r,fromCache:!0,pinned:!0,events:[]};return e.recordNodeResult(d),await this.emitEvent(e,{type:ce.NODE_CACHE_HIT,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.CACHED,payload:{outputs:n.outputs}}),await this.emitEvent(e,{type:ce.NODE_COMPLETED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.SUCCEEDED,payload:{outputs:n.outputs,fromCache:!0}}),void this.emitNodeStateChanged(e,t,o,a,de.SUCCEEDED,se.SUCCEEDED)}}try{const d=new Do(e.runId,n.parentRunId,t.workflowId,t.resolved.document,o.instance,o.manifest,a,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:se.SUCCEEDED,inputs:s,outputs:p,startedAt:i,finishedAt:h,events:[]};e.recordNodeResult(f),await this.emitEvent(e,{type:ce.NODE_COMPLETED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.SUCCEEDED,payload:{outputs:p}}),this.emitNodeStateChanged(e,t,o,a,de.SUCCEEDED,se.SUCCEEDED)}catch(r){if(r instanceof ao)throw r;const d=new Date,l=this.toErrorPayload(r),c={nodeId:o.id,status:se.FAILED,inputs:s,error:l,startedAt:i,finishedAt:d,events:[]};if(e.recordNodeResult(c),await this.emitEvent(e,{type:ce.NODE_FAILED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.FAILED,error:l}),this.emitNodeStateChanged(e,t,o,a,de.FAILED,se.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===Ft||e.isDataEdgeActive(t.id))}async skipInactiveNode(e,t,o,n){const r=new Date,i=[...n.path??[],o.id];await this.emitEvent(e,{type:ce.NODE_SKIPPED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:se.SKIPPED,payload:{reason:"branchNotSelected"}});const a={nodeId:o.id,status:se.SKIPPED,inputs:{},startedAt:r,finishedAt:new Date,events:[]};e.recordNodeResult(a),this.emitNodeStateChanged(e,t,o,i,de.SKIPPED,se.SKIPPED)}async executeDisabledNode(e,t,o,n){const r=new Date,i=[...n.path??[],o.id],a=Go.disabledBehaviorOf(o.instance,t.resolved.document.settings);if(await this.emitEvent(e,{type:ce.NODE_SKIPPED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:se.SKIPPED,payload:{disabled:!0,behavior:a}}),"skip"===a){const n={nodeId:o.id,status:se.SKIPPED,inputs:{},startedAt:r,finishedAt:new Date,events:[]};return e.recordNodeResult(n),void this.emitNodeStateChanged(e,t,o,i,de.SKIPPED,se.SKIPPED)}const s=await this.resolveNodeInputs(e,t,o,n);let d;if("passThroughFirstInput"===a){const n=(t.incomingByNode.get(o.id)??[]).find(e=>"data"===e.type),r=o.manifest.outputs[0]?.id??"value",i=n?e.valueStore.getPort(n.sourceNodeId,n.sourcePort):Object.values(s)[0];d={[r]:i}}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:se.SUCCEEDED,inputs:s,outputs:d,startedAt:r,finishedAt:new Date,events:[]};e.recordNodeResult(l),this.emitNodeStateChanged(e,t,o,i,de.SUCCEEDED,se.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 Qt(`Node '${e.id}' of kind '${e.kind}' produced unknown output(s): ${r.join(", ")}`,"GRAPH_OUTPUT_VALIDATION_FAILED",{nodeId:e.id,unknownOutputs:r});const i=o.outputs.filter(e=>!0===e.required&&!(e.id in t)).map(e=>e.id);if(i.length>0)throw new Qt(`Node '${e.id}' of kind '${e.kind}' did not produce required output(s): ${i.join(", ")}`,"GRAPH_OUTPUT_VALIDATION_FAILED",{nodeId:e.id,missingRequired:i});return t}collectCredentials(e){const t={};for(const o of e.manifest.parameters){if("credential"!==o.type)continue;const n=(e.instance.parameters??{})[o.id];"string"==typeof n&&n.length>0?t[o.id]={credentialId:n,credentialType:o.credentialType??""}: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={},i=(t.incomingByNode.get(o.id)??[]).filter(e=>"data"===e.type),a=new Map;for(const e of i){const t=a.get(e.targetPort)??[];t.push(e),a.set(e.targetPort,t)}for(const[t,o]of a)if(1===o.length)r[t]=e.valueStore.getPort(o[0].sourceNodeId,o[0].sourcePort);else{let n,i=!1;for(const t of o){const o=e.valueStore.getPort(t.sourceNodeId,t.sourcePort);r[t.sourcePort]=o,void 0!==o&&(n=o,i=!0)}i&&void 0===r[t]&&(r[t]=n)}const s=o.instance.inputBindings??{};for(const e of o.manifest.inputs){const t=s[e.id];if("literal"===t?.mode)r[e.id]=t.value;else if("expression"===t?.mode)r[e.id]=await this.evaluateExpressionBinding(o,t.expression,r,n);else if(void 0===r[e.id]){const t=e.metadata?.defaultValue;void 0!==t&&(r[e.id]=t)}}return r}async resolveNodeParameters(e,t,o){const n=e.instance.parameters??{},r={};for(const[i,a]of Object.entries(n))r[i]=ut(a)?await this.evaluateValueTemplate(a,e,t,o):a;return r}async evaluateValueTemplate(e,t,o,n){const r=this.codeSandboxEvaluator;if(!r)throw new Qt(`Value template on node '${t.id}' requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator`,"GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{nodeId:t.id});const i=e.language??("expression"===e.mode?"javascript":"text"),a="template"===e.mode?(e=>`\`${e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\{\{\s*([\s\S]*?)\s*\}\}/g,(e,t)=>`\${${t}}`)}\``)(e.expression):e.expression,s=n.metadata;return await r.evaluate({code:a,language:"typescript"===i?"typescript":"javascript",input:o,vars:s?.vars??void 0,item:s?.item,index:s?.index,abortSignal:n.abortSignal})}async evaluateExpressionBinding(e,t,o,n){const r=this.codeSandboxEvaluator;if(!r)throw new Qt(`Expression binding on node '${e.id}' requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator`,"GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{nodeId:e.id,expression:t});const i=n.metadata;return await r.evaluate({code:t,language:"javascript",input:o,vars:i?.vars??void 0,item:i?.item,index:i?.index,abortSignal:n.abortSignal})}async tryPinnedValue(e,t,o,n){if(!(new ln).shouldUsePinnedValue(o))return;const r=this.createPinningService(),i=this.computeDependencyFingerprints(e,t,o.id);return r.readPinnedValue(t.workflowId,o,n,i)}computeDependencyFingerprints(e,t,o){const n=this.createPinningService(),r=(new cn).getDependencies(t,o),i={};for(const o of r){const r=t.nodes.find(e=>e.id===o);if(r){const a=e.nodeResults.get(o),s=a?.inputs??{},d=this.computeDependencyFingerprints(e,t,o);i[o]=n.computeFingerprint(t.workflowId,r,s,d)}}return i}routeOutgoingEdges(e,t,o,n){const r=(t.outgoingByNode.get(o.id)??[]).filter(e=>"data"===e.type);for(const i of r){if(!Object.prototype.hasOwnProperty.call(n,i.sourcePort))continue;const r=n[i.sourcePort];e.activateDataEdge(i.id),i.targetNodeId===Ft&&e.valueStore.setWorkflowOutput(i.targetPort,r),this.emitEdgeStateChanged(e,t,o,i,de.SUCCEEDED,se.SUCCEEDED),this.emitEvent(e,{type:ce.EDGE_VALUE_ROUTED,runId:e.runId,workflowId:t.workflowId,edgeId:i.id,nodeId:o.id,path:[],payload:{edge:i,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,i){this.emitEvent(e,{type:ce.NODE_STATE_CHANGED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:n,status:i,payload:{nodeId:o.id,state:r,runId:e.runId,workflowId:t.workflowId,status:i}}).catch(()=>{})}emitEdgeStateChanged(e,t,o,n,r,i){this.emitEvent(e,{type:ce.EDGE_STATE_CHANGED,runId:e.runId,workflowId:t.workflowId,edgeId:n.id,nodeId:o.id,path:[],status:i,payload:{edgeId:n.id,state:r,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,status:i}}).catch(()=>{})}mergeOptions(e){return{concurrency:4,failFast:!0,validateInputs:!0,validateOutputs:!0,maxLoopIterations:Vt,maxForeachIterations:Ht,usePinnedValues:!0,writeThroughCache:!1,path:[],metadata:{},...this.defaultOptions,...e}}executionLimits(e){return{maxLoopIterations:e.maxLoopIterations??Vt,maxForeachIterations:e.maxForeachIterations??Ht}}assertNotAborted(e){if(!0===e.abortSignal?.aborted)throw new so(e.runId??"unknown")}generateRunId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new Qt("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 pn=new Set(["process","require","module","exports","global","globalThis","Function","eval","fetch","XMLHttpRequest","WebSocket","Worker","Deno","Bun","__dispatch"]);class hn extends q{constructor(){super()}async initialize(...e){const t=e[0]??{},o=t&&"object"==typeof t?t:{};return this._config=o,this._client=K,{config:o,client:K}}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 Qt("Code sandbox received empty code","GRAPH_CODE_SANDBOX_EMPTY_CODE");const n=((e,t)=>"javascript"===t?e:X.transpileModule(e,{compilerOptions:{target:X.ScriptTarget.ES2022,module:X.ModuleKind.None,strict:!0,noEmitHelpers:!0,importHelpers:!1}}).outputText.replace(/^"use strict";\s*/,""))(o,e.language??"javascript");(e=>{if(e.length>1e5)throw new Qt("Code exceeds the maximum length of 100000 characters","GRAPH_CODE_SANDBOX_CODE_TOO_LONG",{length:e.length});let t;try{t=z.parse(`async function __validate() {\n${e}\n}`,{ecmaVersion:"latest",sourceType:"script"})}catch{try{t=z.parse(e,{ecmaVersion:"latest",sourceType:"module"})}catch(t){throw new Qt("Code failed to parse: "+t.message,"GRAPH_CODE_SANDBOX_PARSE_ERROR",{code:e,error:t.message})}}J.full(t,e=>{const t=e;if("ImportDeclaration"===t.type)throw new Qt("Imports are not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"import"});if("ExportNamedDeclaration"===t.type||"ExportDefaultDeclaration"===t.type)throw new Qt("Exports are not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"export"});if("Identifier"===t.type&&"string"==typeof t.name&&pn.has(t.name))throw new Qt(`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 Qt("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 Qt("eval() is not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"eval"})})})(n);const r=!(e=>/\breturn\b[\s;]/.test(e))(n),i=r?n.replace(/[\s;]+$/,""):n,a={$input:e.input??{},$vars:e.vars??{},$item:e.item,$index:e.index,$node:e.nodes??{},$output:void 0},s=Object.keys(a),d=r?`return (${i});`:i,l=`"use strict";\nasync function __userFunction(${s.join(", ")}) {\n${d}\n}\n__userFunction(${s.join(", ")}).then(function(__r) { return JSON.stringify({ v: __r }); });`,c=new K.Isolate({memoryLimit:this.defaultMemoryMb}),u=await c.createContext();try{const t=u.global;e.logger&&await this.injectConsole(u,e.logger);for(const[e,o]of Object.entries(a))await t.set(e,new K.ExternalCopy(void 0===o?null:o).copyInto());let o;try{o=await c.compileScript(l,{filename:"graph-code-node.js"})}catch(e){if(!r)throw new Qt("Code failed to compile: "+e.message,"GRAPH_CODE_SANDBOX_COMPILE_ERROR",{code:n,error:e.message});{const e=i,t=`"use strict";\nasync function __userFunction(${s.join(", ")}) {\n${e}\n}\n__userFunction(${s.join(", ")}).then(function(__r) { return JSON.stringify({ v: __r }); });`;try{o=await c.compileScript(t,{filename:"graph-code-node.js"})}catch(e){throw new Qt("Code failed to compile: "+e.message,"GRAPH_CODE_SANDBOX_COMPILE_ERROR",{code:n,error:e.message})}}}const d=e.timeoutMs??this.defaultTimeoutMs;let p;try{p=await this.runBounded(o,u,d,e.abortSignal)}catch(e){if(e instanceof Qt)throw e;const t=e.message;if(t.includes("timed out")||t.includes("timeout"))throw new Qt(`Code execution timed out after ${d} ms`,"GRAPH_CODE_SANDBOX_TIMEOUT",{timeoutMs:d});if(t.includes("memory")||t.includes("heap"))throw new Qt(`Code exceeded the memory limit of ${this.defaultMemoryMb} MB`,"GRAPH_CODE_SANDBOX_MEMORY_LIMIT",{memoryMb:this.defaultMemoryMb});throw new Qt("Code execution failed: "+t,"GRAPH_CODE_SANDBOX_RUNTIME_ERROR",{code:n,error:t})}if("string"!=typeof p)throw new Qt("Code sandbox returned an unexpected non-string result","GRAPH_CODE_SANDBOX_UNEXPECTED_RESULT",{result:p});return JSON.parse(p).v}finally{u.release(),c.dispose()}}async runBounded(e,t,o,n){const r=e.run(t,{timeout:o,promise:!0});r.catch(()=>{});const i=[r];let a,s;try{return i.push(new Promise((e,t)=>{a=setTimeout(()=>{t(new Qt(`Code execution timed out after ${o} ms`,"GRAPH_CODE_SANDBOX_TIMEOUT",{timeoutMs:o}))},o+100)})),n&&i.push(new Promise((e,t)=>{const r=()=>{const e="timeout"===n.reason;t(new Qt(e?`Code execution timed out after ${o} ms`:"Code execution aborted",e?"GRAPH_CODE_SANDBOX_TIMEOUT":"GRAPH_CODE_SANDBOX_ABORTED",{timeoutMs:o,reason:n.reason}))};n.aborted?r():(n.addEventListener("abort",r,{once:!0}),s=()=>n.removeEventListener("abort",r))})),await Promise.race(i)}finally{a&&clearTimeout(a),s?.()}}async injectConsole(e,t){const o=new K.Reference((e,o)=>{let n;try{n=JSON.parse(o)}catch{n=[o]}const r=n.map(e=>"string"==typeof e?e:JSON.stringify(e)).join(" "),i=1===n.length?n[0]:n;switch(e){case"log":case"info":default:t.info(r,i);break;case"warn":t.warn(r,i);break;case"error":t.error(r,i);break;case"debug":case"dir":case"dirxml":case"table":t.debug(r,i);break;case"trace":t.trace(r,i);break;case"group":case"groupCollapsed":t.debug("[group] "+r,i);break;case"groupEnd":t.debug("[groupEnd]",void 0);break;case"time":case"timeEnd":case"timeLog":case"count":case"countReset":t.debug(`[${e}] ${r}`,i);break;case"assert":n[0]||t.error("Assertion failed: "+r,i);case"clear":}});await e.evalClosure("\n function __ser() {\n var out = [];\n for (var i = 0; i < arguments.length; i++) {\n var a = arguments[i];\n try { out.push(typeof a === 'object' ? JSON.parse(JSON.stringify(a)) : a); }\n catch (e) { out.push(String(a)); }\n }\n return JSON.stringify(out);\n }\n function __call(level) {\n return function() {\n $0.applySync(undefined, [level, __ser.apply(null, arguments)]);\n };\n }\n globalThis.console = {\n log: __call('log'),\n info: __call('info'),\n warn: __call('warn'),\n error: __call('error'),\n debug: __call('debug'),\n trace: __call('trace'),\n dir: __call('dir'),\n dirxml: __call('dirxml'),\n table: __call('table'),\n group: __call('group'),\n groupCollapsed: __call('groupCollapsed'),\n groupEnd: __call('groupEnd'),\n time: __call('time'),\n timeEnd: __call('timeEnd'),\n timeLog: __call('timeLog'),\n assert: __call('assert'),\n count: __call('count'),\n countReset: __call('countReset'),\n clear: __call('clear')\n };\n ",[o]),o.release()}}class fn extends k{constructor(e){super(e,fn.name,500)}}class gn extends _{constructor(e){super(e),this.name=gn.name}}class mn extends _{constructor(e){super(e),this.name=mn.name}}class yn{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 fn(`Method declaration for kind '${this.kind}' is missing a name`);if(this.declarations.has(e.name))throw new fn(`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 fn(`Method implementation '${e}' for kind '${this.kind}' is not a function`);if(!this.declarations.has(e))throw new fn(`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 fn(`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 mn(`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 wn(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 bn(e,t,o){const n=wn(t,e.itemIdPath),r=e.itemLabelPath?wn(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 vn(e,t){switch(t){case"input":return e.inputs;case"output":return e.outputs;default:return e.connections}}function In(e,t){const o={inputs:[],outputs:[],connections:[]},n={input:new Set((e.inputs??[]).map(e=>e.id)),output:new Set((e.outputs??[]).map(e=>e.id)),connection:new Set((e.connections??[]).map(e=>e.id))},r=(e,t)=>{const o=n[e];return!o.has(t)&&(o.add(t),!0)};for(const n of e.dynamicPorts??[])if("repeatFromParameter"===n.type){const e=t[n.parameter];if(!Array.isArray(e))continue;const i=vn(o,n.direction);e.forEach((e,t)=>{const{id:o,label:a}=bn(n,e,t),s=(d={id:o,index:t,label:a??o},n.portIdTemplate.replaceAll("${id}",d.id).replaceAll("${index}",d.index+"").replaceAll("${label}",d.label));var d;if(!r(n.direction,s))return;const l=n.defaultPort?Fe(n.defaultPort):{id:s,label:a??s,direction:n.direction};l.id=s,l.direction=n.direction,a&&(l.label=a),i.push(l)})}else if("togglePort"===n.type){if(t[n.parameter]!==n.equals)continue;const e=Fe(n.port);if(!r(e.direction,e.id))continue;vn(o,e.direction).push(e)}return o}function En(e,t){const o=In(e,t),n={kind:e.kind,display:e.display,inputs:[...e.inputs,...o.inputs],outputs:[...e.outputs,...o.outputs],parameters:e.parameters},r=[...e.connections??[],...o.connections];return r.length&&(n.connections=r),e.dynamicPorts?.length&&(n.dynamicPorts=e.dynamicPorts),e.credentials?.length&&(n.credentials=e.credentials),e.capabilities?.length&&(n.capabilities=e.capabilities),e.policies&&(n.policies=e.policies),e.metadata&&(n.metadata=e.metadata),e.namespaces?.length&&(n.namespaces=e.namespaces),Fe(n)}class Nn{async resolve(e,t,o,n,r){if(o){const i=await o(n,r);if(!(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.kind&&"object"==typeof t.display&&null!==t.display&&Array.isArray(t.inputs)&&Array.isArray(t.outputs)&&Array.isArray(t.parameters)})(i))throw new fn(`resolveManifest provider for kind '${e}' returned a value that does not conform to GraphResolvedNodeManifest`);if(!Ue(i))throw new fn(`resolveManifest provider for kind '${e}' returned a non-JSON-safe resolved manifest`);const a=Fe(i);return!a.namespaces?.length&&t.namespaces?.length&&(a.namespaces=t.namespaces.slice()),a}return En(t,n.parameters??{})}}const On=["edge","literal","expression"];function An(e){return On.includes(e)}function xn(e,t,o){if("string"!=typeof o||!o)throw new fn(`Manifest for kind '${e}' has a ${t} with an empty port id`);if(Le(o))throw new fn(`Manifest for kind '${e}' has a ${t} with unsafe port id '${o}'`)}let kn=class extends U{constructor(){super(),this.entries=new Map,this.resolver=new Nn,this.fallbackContext=new j}withContext(e){return e[e.length-1]instanceof j?e:[this.fallbackContext]}register(e,t={},...o){const{log:n}=this.logCtx(this.withContext(o),"register").for(this.register);n.debug(`Registering graph node kind '${e?.manifest?.kind??"unknown"}'`),(e=>{if(!e||"object"!=typeof e)throw new fn("Graph node registration is required");if(!e.manifest||"object"!=typeof e.manifest)throw new fn("Graph node registration is missing a manifest");if(!e.executor||"function"!=typeof e.executor.execute)throw new fn(`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 fn("Graph node manifest kind is required and must be a non-empty string");const i=r.kind;if(this.entries.has(i)&&!t.replace)throw new fn(`Graph node kind '${i}' is already registered; pass { replace: true } to replace it`);try{mt(r)}catch(e){throw new fn(`Manifest for kind '${i}' is not JSON-serializable: ${e.message}`)}((e,t)=>{const o=[["input",t.inputs],["output",t.outputs],["connection",t.connections??[]]];for(const[t,n]of o){const o=new Set;for(const r of n){if(xn(e,t+" port",r?.id),o.has(r.id))throw new fn(`Manifest for kind '${e}' declares duplicate static ${t} port id '${r.id}'`);if(o.add(r.id),void 0!==r.defaultMode&&!An(r.defaultMode))throw new fn(`Manifest for kind '${e}' declares invalid default binding mode '${r.defaultMode+""}' on ${t} port '${r.id}'`)}}})(i,r);const a=((e,t)=>{const o=new Set;for(const n of t.parameters){const t=n?.id;if("string"!=typeof t||!t)throw new fn(`Manifest for kind '${e}' has a parameter with an empty id`);if(Le(t))throw new fn(`Manifest for kind '${e}' has a parameter with unsafe id '${t}'`);if(o.has(t))throw new fn(`Manifest for kind '${e}' declares duplicate parameter id '${t}'`);o.add(t)}return o})(i,r);((e,t,o)=>{for(const n of t.dynamicPorts??[]){if(!n||"string"!=typeof n.parameter||!n.parameter)throw new fn(`Manifest for kind '${e}' has a dynamic-port rule without a parameter reference`);if(!o.has(n.parameter))throw new fn(`Manifest for kind '${e}' has a dynamic-port rule referencing missing parameter '${n.parameter}'`);if("togglePort"===n.type){if(!n.port)throw new fn(`Manifest for kind '${e}' has a togglePort rule without a port`);xn(e,"togglePort rule port",n.port.id)}if("repeatFromParameter"===n.type&&"string"!=typeof n.portIdTemplate)throw new fn(`Manifest for kind '${e}' has a repeatFromParameter rule without a portIdTemplate`)}})(i,r,a),((e,t)=>{for(const o of t.credentials??[]){if(!ht(o))throw new fn(`Manifest for kind '${e}' has a malformed credential requirement`);if(!o.type)throw new fn(`Manifest for kind '${e}' has a credential requirement with an empty type`)}})(i,r),((e,t)=>{for(const o of t.methods??[])if(!wt(o))throw new fn(`Manifest for kind '${e}' has a malformed method declaration`)})(i,r);const s=new yn(i,r.methods??[],e.methods??{});return this.entries.set(i,{registration:e,methods:s,placeholderManifest:!1}),this}registerExecutor(e,t,...o){const{log:n}=this.logCtx(this.withContext(o),"registerExecutor").for(this.registerExecutor);if(n.debug(`Registering graph executor for kind '${e}'`),"string"!=typeof e||!e.trim())throw new fn("Graph executor kind is required");if(!t||"function"!=typeof t.execute)throw new fn(`Executor registered for kind '${e}' is missing an execute method`);const r=this.entries.get(e);if(r)return r.registration={...r.registration,executor:t},this;const i={kind:e,display:{name:e},inputs:[],outputs:[],parameters:[],policies:{allowUndeclaredParameters:!0,allowUnknownOutputs:!0}};return this.entries.set(e,{registration:{manifest:i,executor:t},methods:new yn(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 gn(`No graph node kind '${e}' is registered in the catalogue`);return t}getManifest(e,...t){return this.logCtx(this.withContext(t),"getManifest").for(this.getManifest),Fe(this.entry(e).registration.manifest)}getExecutor(e,...t){return this.logCtx(this.withContext(t),"getExecutor").for(this.getExecutor),this.entry(e).registration.executor}getMethodDeclaration(e,t,...o){return this.logCtx(this.withContext(o),"getMethodDeclaration").for(this.getMethodDeclaration),this.entry(e).methods.getDeclaration(t)}getMethod(e,t,...o){return this.logCtx(this.withContext(o),"getMethod").for(this.getMethod),this.entry(e).methods.getDeclaration(t),this.entry(e).methods.get(t)}listMethodDeclarations(e,...t){return this.logCtx(this.withContext(t),"listMethodDeclarations").for(this.listMethodDeclarations),this.entry(e).methods.list()}listManifests(e,...t){this.logCtx(this.withContext(t),"listManifests").for(this.listManifests);const o=[...this.entries.keys()].sort(),n=e?.categories?.length?new Set(e.categories):void 0,r=e?.kinds?.length?new Set(e.kinds):void 0,i=[];for(const e of o){if(r&&!r.has(e))continue;const o=this.getManifest(e,...t);n&&!n.has(o.display.category??"")||i.push(o)}return i}listKinds(...e){return this.logCtx(this.withContext(e),"listKinds").for(this.listKinds),[...this.entries.keys()].sort()}get size(){return this.entries.size}async resolveManifest(e,t,o,...n){this.logCtx(this.withContext(n),"resolveManifest").for(this.resolveManifest);const r=this.entry(e);return this.resolver.resolve(e,r.registration.manifest,r.registration.resolveManifest,t,o)}};kn=D([G(),$("design:paramtypes",[])],kn);let _n=class extends U{constructor(e=new kn){super(),this.catalogue=e}get catalog(){return this.catalogue}register(e,t,...o){const{log:n}=this.logCtx(o,"register").for(this.register);if(n.debug(`Registering graph executor for kind '${e}'`),!e)throw new Qt("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 gn)throw new Qt(`No graph executor registered for kind '${e}'`,"GRAPH_EXECUTOR_NOT_FOUND",{kind:e});throw t}}};_n=D([G(),$("design:paramtypes",[kn])],_n);let Dn=class extends U{constructor(e,t){super(),this.registry=e,this.defaultExecutor=t}resolve(e,...t){const{log:o}=this.logCtx(t,"resolve").for(this.resolve);return o.debug(`Resolving graph executor for kind '${e}'`),this.registry.has(e,...t)?this.registry.resolve(e,...t):this.defaultExecutor?this.defaultExecutor:this.registry.resolve(e,...t)}};function $n(e){return e}function Pn(e){return e.methods??[]}function Sn(e){if(!e)return;const t={...e.metadata??{},...e.parameters??{},...e.state??{}};return e.loop&&(t.loop=e.loop),t}Dn=D([G(),$("design:paramtypes",[Function,Object])],Dn);class Rn extends w{constructor(e){super(),w.fromModel(this,e)}execute(e,t){throw new Qt(`Graph node kind '${this.constructor.name}' does not implement execute`,"GRAPH_NODE_EXECUTE_NOT_IMPLEMENTED",{kind:this.constructor.name})}static applyMetadata(e){return null}static instantiate(e){return new this(e)}}let Cn=class extends Rn{execute(e,t){throw new ao(e.inputs.value)}};function Tn(e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack,code:e.graphCode??("number"==typeof e.code?e.code+"":e.code)}:{name:"UnknownError",message:e+""}}D([b(),i("ngx-decaf-crud-field",{label:"graph.node.flow_control.break.fields.value.label",placeholder:"graph.node.flow_control.break.fields.value.placeholder",type:"textarea"}),Se({handle:"value"}),$("design:type",Object)],Cn.prototype,"value",void 0),Cn=D([$e("core.flow.break",{kind:"core.flow.break",category:"Flow Control",color:"#f59e0b",icon:"ti-square-arrow-right",width:96,height:96,labels:["flow","break","loop","control"],metadata:{title:"graph.node.flow_control.break.name",description:"graph.node.flow_control.break.description"}}),E()],Cn);let Ln=class extends Rn{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 Qt("errorBoundary node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");try{const r=await n.execute(o.try,e.inputs,{parentRunId:t.runId,path:[...t.path,"try"]}),i=Object.values(r.nodeResults).find(e=>e.status===se.FAILED);if(i)throw new Qt(i.error?.message??"error boundary try body failed",i.error?.code??"GRAPH_ERROR_BOUNDARY",i.error?.details);return{result:r.outputs.result??r.outputs}}catch(r){let i=r;if(o.catch){const a=await n.execute(o.catch,{...e.inputs,error:Tn(r)},{parentRunId:t.runId,path:[...t.path,"catch"]});i=a.outputs.error??a.outputs}return{error:i}}finally{o.finally&&await n.execute(o.finally,e.inputs,{parentRunId:t.runId,path:[...t.path,"finally"]})}}};D([b(),i("ngx-decaf-crud-field",{label:"graph.node.flow_control.error_boundary.fields.value.label",placeholder:"graph.node.flow_control.error_boundary.fields.value.placeholder",type:"textarea"}),Se({handle:"value"}),$("design:type",Object)],Ln.prototype,"value",void 0),D([Re({handle:"result"}),$("design:type",Object)],Ln.prototype,"result",void 0),D([Re({handle:"error"}),$("design:type",Object)],Ln.prototype,"error",void 0),Ln=D([$e("core.flow.errorBoundary",{kind:"core.flow.errorBoundary",category:"Flow Control",color:"#f59e0b",icon:"ti-shield-check",width:96,height:96,labels:["flow","error","try-catch"],metadata:{title:"graph.node.flow_control.error_boundary.name",description:"graph.node.flow_control.error_boundary.description",finally:!1}}),E()],Ln);let jn=class extends Rn{execute(e){const t=e.inputs.value??e.inputs;return!1===this.approved?{rejected:t}:{approved:t}}};D([b(),Se({handle:"value"}),$("design:type",Object)],jn.prototype,"value",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.human_approval.fields.message.label",placeholder:"graph.node.flow_control.human_approval.fields.message.placeholder",type:"textarea"}),Se({handle:"message",userControlled:!0}),$("design:type",String)],jn.prototype,"message",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.human_approval.fields.approved.label",type:"checkbox"}),Se({handle:"approved",userControlled:!0}),$("design:type",Boolean)],jn.prototype,"approved",void 0),D([Re({handle:"approved"}),$("design:type",Object)],jn.prototype,"approvedOut",void 0),D([Re({handle:"rejected"}),$("design:type",Object)],jn.prototype,"rejectedOut",void 0),jn=D([$e("core.flow.humanApproval",{kind:"core.flow.humanApproval",category:"Flow Control",color:"#f59e0b",icon:"ti-user-check",width:96,height:96,labels:["flow","approval","suspend"],metadata:{title:"graph.node.flow_control.human_approval.name",description:"graph.node.flow_control.human_approval.description",approvers:[],timeoutMs:864e5}}),E()],jn);class Mn{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 Qt(`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 Qt("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 Gn(e){return"object"==typeof e&&null!==e&&"type"in e&&"code"===e.type}function Un(e){return"object"==typeof e&&null!==e&&"op"in e&&"string"==typeof e.op}async function Fn(e,t,o){const n=o.engine?.codeSandboxEvaluator;if(!n)throw new Qt("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 Bn(e,t,o){if(Un(e))return(new Mn).evaluate(e,t);throw((e,t)=>new Qt(`Unknown ${t??"flow"} condition type \u2014 must be ConditionExpression (op) or CodeCondition (type: 'code')`,"GRAPH_UNKNOWN_CONDITION_TYPE",{condition:e}))(e,o)}async function qn(e,t,o){return Gn(e)?Fn(e,t.input,o):Bn(e,t.state,t.label)}let Wn=class extends Rn{execute(e,t){const o=e.inputs,n=o.value??o;if(!this.condition)throw new Qt("If node has no condition configured","GRAPH_IF_NO_CONDITION",{input:o});if(Gn(this.condition))return Fn(this.condition,o,t).then(e=>this.route(e,n));const r=Bn(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 Qt("If node condition evaluated to false and the else branch is disabled","GRAPH_IF_ELSE_DISABLED",{condition:this.condition})}};D([b(),i("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.value.label",placeholder:"graph.node.flow_control.if.fields.value.placeholder",type:"textarea"}),Se({handle:"value"}),$("design:type",Object)],Wn.prototype,"value",void 0),D([b(),Re({handle:"then"}),$("design:type",Object)],Wn.prototype,"then",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.condition.label",placeholder:"graph.node.flow_control.if.fields.condition.placeholder",type:"code"}),Se({handle:"condition",userControlled:!0,type:"object"}),$("design:type",Object)],Wn.prototype,"condition",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.else.label",type:"checkbox"}),Se({handle:"else",userControlled:!0}),$("design:type",Boolean)],Wn.prototype,"else",void 0),Wn=D([$e("core.flow.if",{kind:"core.flow.if",category:"Flow Control",color:"#f59e0b",icon:"ti-arrows-split-2",width:96,height:96,labels:["flow","conditional","branch"],metadata:{title:"graph.node.flow_control.if.name",description:"graph.node.flow_control.if.description"}}),E()],Wn);let Vn=class extends Rn{async execute(e,t){const o=((e,t)=>{const o={cases:t.cases??[],defaultPort:t.defaultPort??"default",hasDefault:!0===t.hasDefault},n=e.node.metadata?.switch;return n&&Array.isArray(n.cases)?{cases:n.cases,defaultPort:n.defaultPort??o.defaultPort,hasDefault:!0===n.hasDefault||o.hasDefault}:o})(t,this),n=o.cases,r=e.inputs,i=r.value??r,a=((e,t)=>t===e||"object"!=typeof t||null===t||Array.isArray(t)?e:{...t,...e})(r,i);for(const e of n)if(await qn(e.condition,{input:r,state:a,label:"switch case"},t))return{[e.outputPort]:i};if(!0!==o.hasDefault)throw new Qt("No switch case matched and default port is not enabled","GRAPH_SWITCH_NO_MATCH",{cases:n.map(e=>e.id)});const s=o.defaultPort??"default";return{[s]:i}}static applyMetadata(e){const t=ke(this),o=e.defaultPort??"default",n=!0===e.hasDefault,r=t.ports.filter(t=>!e.cases.some(e=>e.outputPort===t.property)),i=r.filter(e=>e.property!==o),a=r.find(e=>e.property===o),s=[...i,...e.cases.map(e=>({property:e.outputPort,name:e.label,direction:Z.OUTPUT,label:e.label,required:!1,hidden:!1,path:e.outputPort}))];return n&&a&&s.push(a),{ports:s,size:te(t,{cases:e.cases.length}),dataPatch:{switchMetadata:e}}}};D([b(),i("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.value.label",placeholder:"graph.node.flow_control.switch.fields.value.placeholder",type:"textarea"}),Se({handle:"value"}),$("design:type",Object)],Vn.prototype,"value",void 0),D([b(),Re({handle:"default"}),$("design:type",Object)],Vn.prototype,"default",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.cases.label",type:"collection"}),$("design:type",Object)],Vn.prototype,"cases",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.hasDefault.label",type:"checkbox"}),$("design:type",Boolean)],Vn.prototype,"hasDefault",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.defaultPort.label",type:"text"}),$("design:type",String)],Vn.prototype,"defaultPort",void 0),Vn=D([$e("core.flow.switch",{kind:"core.flow.switch",category:"Flow Control",color:"#f59e0b",icon:"ti-arrows-shuffle",width:120,height:140,sizeRules:[{type:"parameterCount",parameter:"cases",dimension:"height",perItem:24}],labels:["flow","switch","multi-branch"],metadata:{title:"graph.node.flow_control.switch.name",description:"graph.node.flow_control.switch.description"}}),E()],Vn);const Hn={maxDocumentBytes:2e6,maxNestingDepth:10,maxNodes:500,maxEdges:1e3},Kn=o.accumulate({graph:{workflows:{limits:{...Hn},allowAnonymousAccess:!1},execution:{maxCodeTimeoutMs:Kt}}}),zn=1e3;function Jn(e,t){const o="number"==typeof e?e:Number(e);return Number.isFinite(o)&&o>0?Math.min(Math.floor(o),t):1e3}const Xn=["javascript","typescript"],Yn="javascript";let Qn=class extends w{constructor(){super(...arguments),this.language=Yn}};D([b(),i("ngx-decaf-crud-field",{label:"graph.node.utility.code.fields.language.label",type:"select"}),N([...Xn]),v(String),$("design:type",String)],Qn.prototype,"language",void 0),D([b(),i("code-editor",{label:"graph.node.utility.code.fields.code.label",placeholder:"graph.node.utility.code.fields.code.placeholder"}),Se({handle:"code"}),$("design:type",String)],Qn.prototype,"code",void 0),D([d(),Se({handle:"data"}),$("design:type",Object)],Qn.prototype,"data",void 0),Qn=D([E()],Qn);let Zn=class extends Rn{async execute(e,t){const o=e.inputs,n=this.input,r=o.code??e.parameters?.code??n?.code??this.defaultCode,i=n?.language??Yn;if(!r||"string"!=typeof r||0===r.trim().length)throw new eo("Code node has no code to execute (input.code is empty)",{input:o});const a=t.engine?.codeSandboxEvaluator;if(!a)throw new Qt("Code node execution requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator","GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{code:r});const s=Kn.graph.execution?.maxCodeTimeoutMs??Kt,d=Jn(this.timeoutMs,s),l=t.metadata,c={code:r,language:i,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:i,length:r.length,timeoutMs:d});const u=await a.evaluate(c);return await t.log("Code node executed",{hasResult:void 0!==u}),{result:u}}};D([b(),Se({handle:"input",model:Qn}),$("design:type",Qn)],Zn.prototype,"input",void 0),D([O(1),A(Kt),i("ngx-decaf-crud-field",{label:"graph.node.utility.code.fields.timeoutMs.label",type:"number"}),Se({handle:"timeoutMs"}),$("design:type",Number)],Zn.prototype,"timeoutMs",void 0),D([i("code-editor",{label:"graph.node.utility.code.fields.defaultCode.label",placeholder:"graph.node.utility.code.fields.defaultCode.placeholder"}),Se({handle:"defaultCode",userControlled:!0}),$("design:type",String)],Zn.prototype,"defaultCode",void 0),D([b(),Re({handle:"result"}),$("design:type",Object)],Zn.prototype,"result",void 0),Zn=D([$e("core.utility.code",{kind:"core.utility.code",category:"Utility",color:"#0d9488",icon:"ti-code",width:96,height:96,labels:["utility","code","sandbox","transform"],metadata:{title:"graph.node.utility.code.name",description:"graph.node.utility.code.description"}}),E()],Zn);let er=class extends Rn{execute(e){return{value:e.inputs.value??e.inputs}}};D([b(),Se({handle:"value"}),$("design:type",Object)],er.prototype,"value",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.utility.delay.fields.timeoutMs.label",type:"number"}),Se({handle:"timeoutMs"}),$("design:type",Number)],er.prototype,"timeoutMs",void 0),D([b(),Re({handle:"value"}),$("design:type",Object)],er.prototype,"valueOut",void 0),er=D([$e("core.flow.delay",{kind:"core.flow.delay",category:"Utility",color:"#0d9488",icon:"ti-clock-hour-4",width:96,height:96,labels:["flow","delay","wait"],metadata:{title:"graph.node.utility.delay.name",description:"graph.node.utility.delay.description"}}),E()],er);let tr=class extends Rn{execute(e,t){const o=e.inputs.value,n=this.level??"info";return t.logger[n](this.message??"Log node",{value:o}),{value:o}}};D([b(),Se({handle:"value"}),$("design:type",Object)],tr.prototype,"value",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.utility.log.fields.message.label",placeholder:"graph.node.utility.log.fields.message.placeholder",type:"textarea"}),Se({handle:"message"}),$("design:type",String)],tr.prototype,"message",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.utility.log.fields.level.label",placeholder:"graph.node.utility.log.fields.level.placeholder",type:"text"}),Se({handle:"level",userControlled:!0}),$("design:type",String)],tr.prototype,"level",void 0),D([b(),Re({handle:"value"}),$("design:type",Object)],tr.prototype,"valueOut",void 0),tr=D([$e("core.flow.log",{kind:"core.flow.log",category:"Utility",color:"#0d9488",icon:"ti-terminal",width:96,height:96,labels:["flow","log","debug","utility"],metadata:{title:"graph.node.utility.log.name",description:"graph.node.utility.log.description"}}),E()],tr);let or=class extends Rn{execute(e){return{result:{mapped:e.inputs.value??e.inputs}}}};D([b(),i("ngx-decaf-crud-field",{label:"graph.node.utility.map.fields.value.label",placeholder:"graph.node.utility.map.fields.value.placeholder",type:"textarea"}),Se({handle:"value"}),$("design:type",Object)],or.prototype,"value",void 0),D([b(),Re({handle:"result"}),$("design:type",Object)],or.prototype,"result",void 0),or=D([$e("core.utility.map",{kind:"core.utility.map",category:"Utility",color:"#0d9488",icon:"ti-arrows-right-left",width:96,height:96,labels:["utility","map","transform"],metadata:{title:"graph.node.utility.map.name",description:"graph.node.utility.map.description",mapper:{}}}),E()],or);let nr=class extends Rn{execute(e,t){const o=e.inputs.value,n=this.level??"info";return t.logger[n](this.message??"Log node",{value:o}),{value:o}}};D([b(),Se({handle:"value"}),$("design:type",Object)],nr.prototype,"value",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.utility.utility_log.fields.message.label",placeholder:"graph.node.utility.utility_log.fields.message.placeholder",type:"textarea"}),Se({handle:"message"}),$("design:type",String)],nr.prototype,"message",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.utility.utility_log.fields.level.label",placeholder:"graph.node.utility.utility_log.fields.level.placeholder"}),Se({handle:"level",userControlled:!0,type:"string"}),$("design:type",String)],nr.prototype,"level",void 0),D([b(),Re({handle:"value"}),$("design:type",Object)],nr.prototype,"valueOut",void 0),nr=D([$e("core.utility.log",{kind:"core.utility.log",category:"Utility",color:"#0d9488",icon:"ti-terminal",width:96,height:96,labels:["utility","log","debug","observability"],metadata:{title:"graph.node.utility.utility_log.name",description:"graph.node.utility.utility_log.description"}}),E()],nr);let rr=class extends Rn{execute(e){return{message:e.inputs.message??null,sessionId:e.inputs.sessionId??null,userId:e.inputs.userId??null}}};D([b(),Re({handle:"message"}),$("design:type",String)],rr.prototype,"message",void 0),D([b(),Re({handle:"sessionId"}),$("design:type",String)],rr.prototype,"sessionId",void 0),D([b(),Re({handle:"userId"}),$("design:type",String)],rr.prototype,"userId",void 0),rr=D([$e("core.trigger.chat",{kind:"core.trigger.chat",category:"Trigger",color:"#3b82f6",icon:"ti-message-circle",width:96,height:96,labels:["trigger","chat","entrypoint"],metadata:{title:"graph.node.trigger.chat.name",description:"graph.node.trigger.chat.description",trigger:{type:"chat"}}}),E()],rr);let ir=class extends Rn{execute(e){return{payload:e.inputs.payload??null}}};D([b(),Re({handle:"payload"}),$("design:type",Object)],ir.prototype,"payload",void 0),ir=D([$e("core.trigger.event",{kind:"core.trigger.event",category:"Trigger",color:"#3b82f6",icon:"ti-broadcast",width:96,height:96,labels:["trigger","event","bus"],metadata:{title:"graph.node.trigger.event.name",description:"graph.node.trigger.event.description",trigger:{type:"event",topic:"default"}}}),E()],ir);let ar=class extends Rn{execute(e){return{payload:e.inputs.payload??null}}};D([b(),Se({handle:"schema"}),i("ngx-decaf-model-builder",{label:"graph.node.trigger.form.fields.schema.label",placeholder:"graph.node.trigger.form.fields.schema.placeholder"}),$("design:type",Object)],ar.prototype,"schema",void 0),D([b(),Re({handle:"payload"}),$("design:type",Object)],ar.prototype,"payload",void 0),ar=D([$e("core.trigger.form",{kind:"core.trigger.form",category:"Trigger",color:"#3b82f6",icon:"ti-forms",width:96,height:96,labels:["trigger","form","public"],metadata:{title:"graph.node.trigger.form.name",description:"graph.node.trigger.form.description",trigger:{type:"form",fields:[]}}}),E()],ar);let sr=class extends Rn{execute(e){return{payload:e.inputs.payload??null}}};D([b(),Re({handle:"payload"}),$("design:type",Object)],sr.prototype,"payload",void 0),sr=D([$e("core.trigger.manual",{kind:"core.trigger.manual",category:"Trigger",color:"#3b82f6",icon:"ti-hand-click",width:96,height:96,labels:["trigger","manual","entrypoint"],metadata:{title:"graph.node.trigger.manual.name",description:"graph.node.trigger.manual.description",trigger:{type:"manual",inputSchema:{}}}}),E()],sr);let dr=class extends Rn{execute(e){return{payload:e.inputs.payload??null}}};D([b(),Se({handle:"cron"}),i("app-cron-selector-field",{label:"graph.node.trigger.schedule.fields.cron.label",placeholder:"graph.node.trigger.schedule.fields.cron.placeholder"}),$("design:type",String)],dr.prototype,"cron",void 0),D([b(),Re({handle:"payload"}),$("design:type",Object)],dr.prototype,"payload",void 0),dr=D([$e("core.trigger.schedule",{kind:"core.trigger.schedule",category:"Trigger",color:"#3b82f6",icon:"ti-calendar-time",width:96,height:96,labels:["trigger","schedule","cron"],metadata:{title:"graph.node.trigger.schedule.name",description:"graph.node.trigger.schedule.description",trigger:{type:"schedule",schedule:"0 * * * *",timezone:"UTC"}}}),E()],dr);let lr=class extends Rn{execute(e){return{payload:e.inputs.payload??null}}};D([b(),Se({handle:"schema"}),i("ngx-decaf-model-builder",{label:"graph.node.trigger.webhook.fields.schema.label",placeholder:"graph.node.trigger.webhook.fields.schema.placeholder"}),$("design:type",Object)],lr.prototype,"schema",void 0),D([b(),Re({handle:"payload"}),$("design:type",Object)],lr.prototype,"payload",void 0),lr=D([$e("core.trigger.webhook",{kind:"core.trigger.webhook",category:"Trigger",color:"#3b82f6",icon:"ti-webhook",width:96,height:96,labels:["trigger","webhook","http"],metadata:{title:"graph.node.trigger.webhook.name",description:"graph.node.trigger.webhook.description",trigger:{type:"webhook",path:"/webhook",method:"POST",auth:"none",responseMode:"onReceived"}}}),E()],lr);let cr=class extends Rn{execute(e){return{response:"[Agent response] "+(e.inputs.prompt??""),actions:[]}}};D([b(),i("ngx-decaf-crud-field",{label:"graph.node.agent.agent.fields.prompt.label",placeholder:"graph.node.agent.agent.fields.prompt.placeholder",type:"textarea"}),Se({handle:"prompt"}),$("design:type",String)],cr.prototype,"prompt",void 0),D([b(),Re({handle:"response"}),$("design:type",String)],cr.prototype,"response",void 0),D([b(),Re({handle:"actions"}),$("design:type",Array)],cr.prototype,"actions",void 0),D([Ce({category:"model",handle:"model"}),$("design:type",Object)],cr.prototype,"model",void 0),D([Ce({category:"memory",handle:"memory"}),$("design:type",Object)],cr.prototype,"memory",void 0),D([Ce({category:"workspace",handle:"workspace"}),$("design:type",Object)],cr.prototype,"workspace",void 0),cr=D([$e("core.agent",{kind:"core.agent",category:"Agent",width:140,height:120,labels:["agent","ai","orchestrator"],metadata:{title:"graph.node.agent.agent.name",description:"graph.node.agent.agent.description",shape:"rectangle"}}),E()],cr);const ur=[cr];function pr(e,t,o,n){const r=t??o;if(null==e)return Math.min(o,r);const i=Number(e);if(!Number.isFinite(i)||0>=i)throw new eo(n+" loop maxIterations must be a positive finite number");return Math.min(Math.floor(i),r)}function hr(e,t,o){const n=t.node.loop,r=t.metadata?.loop;if(!n?.body&&!r?.body)throw new eo(o+" node is missing loop configuration (instance.loop.body)");const i=t=>{const o=e[t]??n?.[t]??r?.[t],i=Number(o);return void 0!==o&&Number.isFinite(i)?i:void 0},a=t=>{const o=e[t]??r?.[t];return"string"==typeof o?o:void 0};return{body:n?.body??r?.body,maxIterations:i("maxIterations"),timeoutMs:i("timeoutMs"),concurrency:i("concurrency"),condition:e.condition??r?.condition,inputPort:a("inputPort"),outputPort:a("outputPort"),itemPort:a("itemPort"),resultPort:a("resultPort"),statePort:a("statePort"),slice:i("slice")}}let fr=class extends Rn{async execute(e,t){const o=hr(this,t,"foreach"),n=e.inputs,r=n.items,i=pr(o.maxIterations,t.limits?.maxForeachIterations,1e3,"foreach");if(!Array.isArray(r))throw new eo("foreach input 'items' must be an array");const a=t.engine;if(!a)throw new Qt("foreach node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");const s=Number(n.slice??o.slice??1),d=Number.isFinite(s)&&s>0?Math.floor(s):1,l=d>1?Math.ceil(r.length/d):r.length;if(l>i)throw new to(`foreach exceeded max iterations (${l} > ${i})`);const c=o.itemPort??"item",u=o.resultPort??"result",p=o.statePort??"state",h=o.body,f=[];let g=n.state,m=!1;await t.emit({type:ce.LOOP_STARTED});for(let e=0;l>e;e++){await t.emit({type:ce.LOOP_ITERATION_STARTED,iteration:e});const o=d>1?r.slice(e*d,e*d+d):r[e],n={[c]:o,index:e};d>1&&(n.slice=o),void 0!==g&&(n[p]=g);try{const r=await a.execute(h,n,{parentRunId:t.runId,path:[...t.path,"iteration:"+e],metadata:{item:o,index:e,slice:d},auth:t.auth},t);f.push(r.outputs[u]),void 0!==r.outputs[p]&&(g=r.outputs[p])}catch(o){if(o instanceof ao){const n=o.details?.value;void 0!==n&&f.push(n),m=!0,await t.emit({type:ce.LOOP_ITERATION_COMPLETED,iteration:e,metadata:{broken:!0}});break}throw o}await t.emit({type:ce.LOOP_ITERATION_COMPLETED,iteration:e})}await t.emit({type:ce.LOOP_COMPLETED,metadata:{broken:m}});const y={results:f,completed:f,iterations:f.length,broken:m};return void 0!==g&&(y[p]=g),y}};D([b(),i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.items.label",placeholder:"graph.node.loop.foreach.fields.items.placeholder",type:"textarea"}),Se({handle:"items"}),$("design:type",Array)],fr.prototype,"items",void 0),D([b(),i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.slice.label",placeholder:"graph.node.loop.foreach.fields.slice.placeholder",type:"number"}),Se({handle:"slice"}),$("design:type",Number)],fr.prototype,"slice",void 0),D([b(),Re({handle:"item"}),$("design:type",Object)],fr.prototype,"item",void 0),D([b(),Ce({handle:"loop",connectionRules:{allowSelf:!0,maxConnections:1}}),$("design:type",Object)],fr.prototype,"loop",void 0),D([b(),Re({handle:"completed"}),$("design:type",Array)],fr.prototype,"completed",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.maxIterations.label",type:"number"}),Se({handle:"maxIterations",userControlled:!0}),$("design:type",Number)],fr.prototype,"maxIterations",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.condition.label",type:"code"}),Se({handle:"condition",userControlled:!0}),$("design:type",Object)],fr.prototype,"condition",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.itemPort.label",type:"text"}),Se({handle:"itemPort",userControlled:!0}),$("design:type",String)],fr.prototype,"itemPort",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.resultPort.label",type:"text"}),Se({handle:"resultPort",userControlled:!0}),$("design:type",String)],fr.prototype,"resultPort",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.statePort.label",type:"text"}),Se({handle:"statePort",userControlled:!0}),$("design:type",String)],fr.prototype,"statePort",void 0),fr=D([$e("graph-foreach-loop-node",{kind:"core.loop.foreach",category:"Loop",color:"#eab308",icon:"ti-repeat",width:120,height:140,labels:["loop","iteration","foreach"],metadata:{title:"graph.node.loop.foreach.name",description:"graph.node.loop.foreach.description",loop:{maxIterations:100,itemPort:"item",resultPort:"result",slice:1}}}),E()],fr);class gr{constructor(){this.expressionEvaluator=new Mn}evaluate(e,t){if(this.isConditionExpression(e))return this.expressionEvaluator.evaluate(e,t);const o=this.resolveValue(e.left,t),n=e.right;switch(e.type){case Xt.TRUTHY:return!!o;case Xt.FALSY:return!o;case Xt.EQUALS:return o===n;case Xt.NOT_EQUALS:return o!==n;case Xt.GREATER_THAN:return Number(o)>Number(n);case Xt.GREATER_THAN_OR_EQUAL:return Number(o)>=Number(n);case Xt.LESS_THAN:return Number(n)>Number(o);case Xt.LESS_THAN_OR_EQUAL:return Number(n)>=Number(o);case Xt.EXISTS:return null!=o;case Xt.CUSTOM:throw new Qt("Custom condition evaluators are not supported in v1","GRAPH_CUSTOM_CONDITION_UNSUPPORTED");default:throw new Qt(`Unknown condition type '${e.type}'`,"GRAPH_UNKNOWN_CONDITION_TYPE",{condition:e})}}async evaluateAsync(e,t,o,n){return Gn(e)?Fn(e,n,o):this.evaluate(e,t)}resolveValue(e,t){if(!e)return t;const o=e.split(".");let n=t;for(const e of o){if(null==n)return;n=n[e]}return n}isConditionExpression(e){return"string"==typeof e.op}}let mr=class extends Rn{async execute(e,t){const o=hr(this,t,"until"),n=e.inputs,r=pr(o.maxIterations,t.limits?.maxLoopIterations,100,"until"),i=o.condition;if(!i)throw new eo("until node is missing a condition");const a=o.statePort??"state",s=o.inputPort??a,d=o.outputPort??a,l=o.body,c=t.engine;if(!c)throw new Qt("until node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");let u=n.state,p=0;await t.emit({type:ce.LOOP_STARTED});let h=!1;do{if(p>=r)throw await t.emit({type:ce.LOOP_LIMIT_REACHED,iteration:p}),new to(`until loop exceeded max iterations (${r})`);await t.emit({type:ce.LOOP_ITERATION_STARTED,iteration:p}),u=(await c.execute(l,{[s]:u,iteration:p},{parentRunId:t.runId,path:[...t.path,"iteration:"+p],auth:t.auth},t)).outputs[d],await t.emit({type:ce.LOOP_ITERATION_COMPLETED,iteration:p});const e=await(new gr).evaluateAsync(i,u,t,{...n,state:u});await t.emit({type:ce.LOOP_CONDITION_EVALUATED,iteration:p,payload:{result:e}}),p++,h=e}while(!h);return await t.emit({type:ce.LOOP_COMPLETED}),{state:u,iterations:p}}};D([b(),i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.state.label",placeholder:"graph.node.loop.until.fields.state.placeholder",type:"textarea"}),Se({handle:"state"}),$("design:type",Object)],mr.prototype,"state",void 0),D([b(),Re({handle:"state"}),$("design:type",Object)],mr.prototype,"stateOut",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.maxIterations.label",type:"number"}),Se({handle:"maxIterations",userControlled:!0}),$("design:type",Number)],mr.prototype,"maxIterations",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.condition.label",type:"code"}),Se({handle:"condition",userControlled:!0}),$("design:type",Object)],mr.prototype,"condition",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.statePort.label",type:"text"}),Se({handle:"statePort",userControlled:!0}),$("design:type",String)],mr.prototype,"statePort",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.inputPort.label",type:"text"}),Se({handle:"inputPort",userControlled:!0}),$("design:type",String)],mr.prototype,"inputPort",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.outputPort.label",type:"text"}),Se({handle:"outputPort",userControlled:!0}),$("design:type",String)],mr.prototype,"outputPort",void 0),mr=D([$e("graph-until-loop-node",{kind:"core.loop.until",category:"Loop",color:"#eab308",icon:"ti-player-stop",width:96,height:96,labels:["loop","conditional","until"],metadata:{title:"graph.node.loop.until.name",description:"graph.node.loop.until.description",loop:{maxIterations:50,statePort:"state",condition:{type:"greaterThanOrEqual",left:"iteration",right:2}}}}),E()],mr);let yr=class extends Rn{async execute(e,t){const o=hr(this,t,"while"),n=e.inputs,r=pr(o.maxIterations,t.limits?.maxLoopIterations,100,"while"),i=o.condition;if(!i)throw new eo("while node is missing a condition");const a=o.statePort??"state",s=o.inputPort??a,d=o.outputPort??a,l=o.body,c=t.engine;if(!c)throw new Qt("while node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");let u=n.state,p=0;for(await t.emit({type:ce.LOOP_STARTED});await(new gr).evaluateAsync(i,u,t,{...n,state:u});){if(p>=r)throw await t.emit({type:ce.LOOP_LIMIT_REACHED,iteration:p}),new to(`while loop exceeded max iterations (${r})`);await t.emit({type:ce.LOOP_CONDITION_EVALUATED,iteration:p,payload:{result:!0}}),await t.emit({type:ce.LOOP_ITERATION_STARTED,iteration:p}),u=(await c.execute(l,{[s]:u,iteration:p},{parentRunId:t.runId,path:[...t.path,"iteration:"+p],auth:t.auth},t)).outputs[d],await t.emit({type:ce.LOOP_ITERATION_COMPLETED,iteration:p}),p++}return await t.emit({type:ce.LOOP_COMPLETED}),{state:u,iterations:p}}};D([b(),i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.state.label",placeholder:"graph.node.loop.while.fields.state.placeholder",type:"textarea"}),Se({handle:"state"}),$("design:type",Object)],yr.prototype,"state",void 0),D([b(),Re({handle:"state"}),$("design:type",Object)],yr.prototype,"stateOut",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.maxIterations.label",type:"number"}),Se({handle:"maxIterations",userControlled:!0}),$("design:type",Number)],yr.prototype,"maxIterations",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.condition.label",type:"code"}),Se({handle:"condition",userControlled:!0}),$("design:type",Object)],yr.prototype,"condition",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.statePort.label",type:"text"}),Se({handle:"statePort",userControlled:!0}),$("design:type",String)],yr.prototype,"statePort",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.inputPort.label",type:"text"}),Se({handle:"inputPort",userControlled:!0}),$("design:type",String)],yr.prototype,"inputPort",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.outputPort.label",type:"text"}),Se({handle:"outputPort",userControlled:!0}),$("design:type",String)],yr.prototype,"outputPort",void 0),yr=D([$e("graph-while-loop-node",{kind:"core.loop.while",category:"Loop",color:"#eab308",icon:"ti-arrows-loop",width:96,height:96,labels:["loop","conditional","while"],metadata:{title:"graph.node.loop.while.name",description:"graph.node.loop.while.description",loop:{maxIterations:50,statePort:"state",condition:{type:"lessThan",left:"iteration",right:3}}}}),E()],yr);let wr=class extends Rn{execute(e){const t=e.inputs;return{value:t?.value??null}}};D([Re({handle:"value",connectionRules:{allowMultiple:!0}}),$("design:type",Object)],wr.prototype,"value",void 0),wr=D([$e("graph-input-value-node",{kind:"value",category:"Boundary",color:"#0f766e",icon:"ti-circle-plus",labels:["workflow","input","value"],metadata:{title:"graph.node.boundary.input.name",description:"graph.node.boundary.input.description"}}),E()],wr);let br=class extends Rn{execute(e){return{}}};function vr(e,t,o,n={}){return{id:e,label:t,direction:o,...n}}function Ir(e){const t=e,o=ve(t),n=o?.metadata?.title;return Tt(t,n?{name:n}:{})}D([b(),Se({handle:"value"}),$("design:type",Object)],br.prototype,"value",void 0),br=D([$e("graph-output-value-node",{kind:"result",category:"Boundary",color:"#0f766e",icon:"ti-circle-minus",width:96,height:96,labels:["workflow","output","value"],metadata:{title:"graph.node.boundary.output.name",description:"graph.node.boundary.output.description"}}),E()],br);const Er={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:[vr("items","graph.node.loop.foreach.ports.input.items.label","input",{required:!0,schema:{type:"array",items:{type:"any"}}}),vr("slice","graph.node.loop.foreach.ports.input.slice.label","input",{schema:{type:"number",integer:!0,min:1}}),vr("state","graph.node.loop.foreach.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[vr("results","graph.node.loop.foreach.ports.output.results.label","output",{schema:{type:"array",items:{type:"any"}}}),vr("completed","graph.node.loop.foreach.ports.output.completed.label","output",{schema:{type:"array",items:{type:"any"}}}),vr("iterations","graph.node.loop.foreach.ports.output.iterations.label","output",{schema:{type:"number",integer:!0,min:0}}),vr("broken","graph.node.loop.foreach.ports.output.broken.label","output",{schema:{type:"boolean"}}),vr("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}]},Nr={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:[vr("state","graph.node.loop.while.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[vr("state","graph.node.loop.while.ports.output.state.label","output",{schema:{type:"any"}}),vr("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"}]},Or={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:[vr("state","graph.node.loop.until.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[vr("state","graph.node.loop.until.ports.output.state.label","output",{schema:{type:"any"}}),vr("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"}]},Ar=[Ir(wr),Ir(br),Ir(sr),Ir(lr),Ir(dr),Ir(ir),Ir(ar),Ir(rr),(xr=Ir(Wn),{...xr,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"}}}]}))(Ir(Vn)),Ir(or),Ir(er),Ir(Ln),Ir(jn),Ir(Zn),Ir(tr),Ir(nr),Ir(Cn),Ir(cr),Er,Nr,Or];var xr;const kr=Object.fromEntries(Ar.map(e=>[e.kind,e])),_r=[sr,lr,dr,ir,ar,rr],Dr=[Wn,Vn,er,Ln,jn,tr,Cn],$r=[Zn,or,nr],Pr=[fr,yr,mr],Sr=[wr,br],Rr={value:wr,result:br,"core.trigger.manual":sr,"core.trigger.webhook":lr,"core.trigger.schedule":dr,"core.trigger.event":ir,"core.trigger.form":ar,"core.trigger.chat":rr,"core.flow.if":Wn,"core.flow.switch":Vn,"core.utility.map":or,"core.flow.delay":er,"core.flow.errorBoundary":Ln,"core.flow.humanApproval":jn,"core.utility.code":Zn,"core.flow.log":tr,"core.utility.log":nr,"core.flow.break":Cn,"core.agent":cr,"core.loop.foreach":fr,"core.loop.while":yr,"core.loop.until":mr};function Cr(e){return{execute:(t,o)=>e.instantiate({...Sn(o.node),...t.parameters,...o.node.state??{}}).execute(t,o)}}function Tr(){const e=[];for(const[t,o]of Object.entries(kr)){const n=Rr[t];n&&e.push($n({manifest:o,executor:Cr(n)}))}return e}function Lr(e,...t){for(const o of Tr())e.register(o,{},...t);return e}class jr{resolve(e){const t=this.createValidator(e);return{name:e.name,required:e.required,validate:t}}resolveAll(e){const t={};for(const o of e)t[o.name]=this.resolve(o);return t}createValidator(e){switch((e.type??e.designType??"").toLowerCase()){case"string":return e=>"string"==typeof e;case"number":return e=>"number"==typeof e;case"boolean":return e=>"boolean"==typeof e;case"date":return e=>e instanceof Date||"string"==typeof e&&!isNaN(Date.parse(e));case"array":return e=>Array.isArray(e);case"bigint":return e=>"bigint"==typeof e;default:return()=>!0}}}class Mr{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 eo(`Missing required ${o} port '${n.name}'`);if(e&&!this.resolver.resolve(n).validate(t[n.name]))throw new eo(`Invalid value for ${o} port '${n.name}'`)}}}const Gr=["node","definition","executor","execute","ports","component"];function Ur(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 Fr(e,t){const o=[];for(const n of Object.keys(e))Gr.includes(n)&&o.push(Ur("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 Br(e,t){t.push(...Fr(e,"$")),e.inputs.forEach((e,o)=>t.push(...Fr(e,`inputs[${o}]`))),e.outputs.forEach((e,o)=>t.push(...Fr(e,`outputs[${o}]`)));for(const o of e.nodes)t.push(...Fr(o,`nodes[${o.id}]`)),o.loop&&(t.push(...Fr(o.loop,`nodes[${o.id}].loop`)),Br(o.loop.body,t));for(const o of e.edges)t.push(...Fr(o,`edges[${o.id}]`))}function qr(e,t){const o=[];e.nodes.length>t.maxNodes&&o.push(Ur("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(Ur("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=Wr(e);n>t.maxNestingDepth&&o.push(Ur("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(Ur("document.limit.size","$",`Document serializes to ${r} bytes; at most ${t.maxDocumentBytes} bytes are allowed`,{details:{bytes:r,limit:t.maxDocumentBytes}})),o}function Wr(e,t=0){let o=t;for(const n of e.nodes)n.loop?.body&&(o=Math.max(o,Wr(n.loop.body,t+1)));return o}async function Vr(e,t,...o){const n=[];for(const r of e.nodes)t.has(r.kind,...o)||n.push(Ur("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 Vr(r.loop.body,t,...o));return n}async function Hr(e,t={},...o){const n={...Hn,...t.limits},r=[];if(!pt(e))return r.push(Ur("document.shape","$","Payload is not a canonical GraphWorkflowDocument: id and name must be strings and inputs, outputs, nodes and edges must be arrays")),{valid:!1,issues:r};if(!Ue(e))return r.push(Ur("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};Br(e,r),r.push(...(e=>{const t=[],o=new Set;for(const n of[...e.inputs,...e.outputs])o.has(n.id)?t.push(Ur("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(Ur("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(Ur("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(...qr(e,n)),Ro(e,r);try{ot(e)}catch(e){const t=e instanceof x?e.message:e+"";r.push(Ur("document.structure","$",t))}return t.catalogue&&r.push(...await Vr(e,t.catalogue,...o)),{valid:0===r.length,issues:r}}class Kr{constructor(e,t){this.iteration=e,this.metadata=t}}function zr(e,t,o={}){const n=e?.owner??null;return!n||n===t||(null==t||""===t)&&!0===o.allowAnonymousAccess}function Jr(e,t){return(e?.owner??null)===(t??null)}function Xr(e,t,o){if(!Jr(e,t))throw new L(`${o.resourceKind} '${o.resourceId}' is owned by another user`)}function Yr(e,t,o){if(!zr(e,t,o))throw new L(`${o.resourceKind} '${o.resourceId}' is owned by another user`)}function Qr(e){if(null===e||"object"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(e=>Qr(e)).join(",")}]`;const t=e;return`{${Object.keys(t).filter(e=>void 0!==t[e]).sort().map(e=>`${JSON.stringify(e)}:${Qr(t[e])}`).join(",")}}`}function Zr(e){return Y("sha256").update(Qr(e)).digest("hex")}class ei{constructor(e={}){this.events=new Map,this.listeners=new Map,this.limits={...ue,...e}}async append(e){let t=this.events.get(e.runId);t||(t=[],this.events.set(e.runId,t)),t.push(e),this.enforceRetention(t);for(const t of this.listeners.get(e.runId)??[])try{t(e)}catch{}}async listAfter(e,t){const o=this.events.get(e);return o?o.filter(e=>e.sequence>t):[]}subscribe(e,t){let o=this.listeners.get(e);return o||(o=new Set,this.listeners.set(e,o)),o.add(t),()=>{o.delete(t),0===o.size&&this.listeners.delete(e)}}release(e){this.events.delete(e),this.listeners.delete(e)}enforceRetention(e){const t=this.limits.maxEventsPerRun;for(;e.length>t;){const t=e.findIndex(e=>!he(e.type));if(-1===t)break;e.splice(t,1)}}}function ti(e){return new Lt({runId:e.runId,workflowId:e.workflowId,...e.ownerUser?{owner:e.ownerUser}:{},status:e.status,...e.documentFingerprint?{documentFingerprint:e.documentFingerprint}:{},...void 0!==e.result?{result:oi(e.result)}:{},...e.error?{error:oi(e.error)}:{},createdAt:new Date(e.createdAt),...e.startedAt?{startedAt:new Date(e.startedAt)}:{},...e.finishedAt?{finishedAt:new Date(e.finishedAt)}:{}})}function oi(e){if(null!=e)return JSON.parse(JSON.stringify(e))}class ni{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=>ti(e))}release(e){this.runs.delete(e)}}class ri{constructor(e,t={}){this.sequences=new Map,this.chains=new Map,this.store=e,this.limits={...ue,...t}}async publish(e){const t=e.runId,o=(this.sequences.get(t)??0)+1;this.sequences.set(t,o);const n={...e,payload:this.limitPayload(e.payload),sequence:o,timestamp:(new Date).toISOString()},r=(this.chains.get(t)??Promise.resolve()).then(()=>this.store.append(n));return this.chains.set(t,r.catch(()=>{})),await r,n}lastSequence(e){return this.sequences.get(e)??0}release(e){this.sequences.delete(e),this.chains.delete(e)}limitPayload(e){if(void 0===e)return;let t;try{t=JSON.stringify(e)}catch{return{nonSerializable:!0}}return t.length>this.limits.maxEventPayloadBytes?{truncated:!0,reason:"event payload exceeds the configured byte limit",bytes:t.length}:e}}class ii{constructor(e,t,o,n={},r={}){this.controllers=new Map,this.completions=new Map,this.timeouts=new Map,this.engine=e,this.runStore=t,this.publisher=o,this.hooks=n,this.limits={...ue,...r}}begin(e){const t=this.controllers.get(e);if(t)return t;const o=new AbortController;return this.controllers.set(e,o),o}abort(e,t){const o=this.controllers.get(e);return!!o&&(o.signal.aborted||o.abort(t),!0)}isAborted(e){return!0===this.controllers.get(e)?.signal.aborted}abortReason(e){const t=this.controllers.get(e)?.signal;if(t?.aborted)return"timeout"===t.reason?"timeout":"user"}waitFor(e){return this.completions.get(e)}schedule(e,t,o,...n){const r=this.completions.get(e.runId);if(r)return r;const i=this.runExecution({...e},t,o,...n).catch(async t=>{const o=ai(t);try{await this.emitTerminal({...e},ce.WORKFLOW_FAILED,o)}catch{}return await this.finalize({...e},"failed",void 0,o,...n)});return this.completions.set(e.runId,i),i}release(e){this.controllers.delete(e),this.completions.delete(e);const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.publisher.release(e)}armTimeout(e){const t=setTimeout(()=>{this.timeouts.delete(e),this.abort(e,"timeout")},this.limits.executionTimeoutMs);this.timeouts.set(e,t)}async runExecution(e,t,o,...n){const r=e.runId;let i,a,s=!1;const d=this.engine.observe({refresh:async t=>{t.runId===r&&(t.error&&(i=t.error),he((await this.publisher.publish(this.envelopeOf(e,t))).type)?s=!0:t.type===ce.WORKFLOW_STARTED&&"validating"===e.status&&(e.status="running",await this.persist(e,...n)))}});this.armTimeout(r);try{if(this.isAborted(r)){const t={name:"GraphRunCancelledError",message:`Graph run '${r}' was cancelled before execution started`,code:"GRAPH_RUN_CANCELLED"};return i=t,await this.emitTerminal(e,ce.WORKFLOW_CANCELLED,t),s=!0,await this.finalize(e,"cancelled",void 0,t,...n)}let d,l;e.status="validating",e.startedAt=(new Date).toISOString(),await this.persist(e,...n);try{({document:d,fingerprint:l}=await t(...n)),e.documentFingerprint=l,await this.persist(e,...n)}catch(t){const o=ai(t);return i=o,s||(await this.emitTerminal(e,ce.WORKFLOW_FAILED,o),s=!0),await this.finalize(e,"failed",void 0,o,...n)}if(this.isAborted(r)){const t={name:"GraphRunCancelledError",message:`Graph run '${r}' was cancelled before execution started`,code:"GRAPH_RUN_CANCELLED"};return i=t,s||(await this.emitTerminal(e,ce.WORKFLOW_CANCELLED,t),s=!0),await this.finalize(e,"cancelled",void 0,t,...n)}try{a=await this.engine.execute(d,o,{runId:r,abortSignal:this.controllers.get(r)?.signal,metadata:{documentFingerprint:l}},...n)}catch(e){i=ai(e)}const c=this.abortReason(r);let u,p;return"timeout"===c?(u="failed",p=i??{name:"GraphRunTimeoutError",message:`Graph run '${r}' exceeded the configured execution timeout of ${this.limits.executionTimeoutMs}ms`,code:"GRAPH_RUN_TIMEOUT"}):"user"===c?(u="cancelled",p=i):a?.status===se.SUCCEEDED?u="succeeded":a?.status===se.CANCELLED?(u="cancelled",p=i):(u="failed",p=i??ai(new Qt(a?`Graph run '${r}' failed`:`Graph run '${r}' failed without a result`,"GRAPH_RUN_FAILED",{runId:r}))),s||await this.emitTerminal(e,"succeeded"===u?ce.WORKFLOW_COMPLETED:"cancelled"===u?ce.WORKFLOW_CANCELLED:ce.WORKFLOW_FAILED,p),await this.finalize(e,u,a,p,...n)}finally{d();const e=this.timeouts.get(r);e&&(clearTimeout(e),this.timeouts.delete(r))}}async emitTerminal(e,t,o){await this.publisher.publish({runId:e.runId,workflowId:e.workflowId,type:t,error:o})}async finalize(e,t,o,n,...r){e.status=t,o&&(e.result=o),n&&(e.error=n),e.startedAt||(e.startedAt=(new Date).toISOString()),e.finishedAt=(new Date).toISOString(),await this.persist(e,...r);try{await(this.hooks.onRunCompleted?.(e,o))}catch{}return e}async persist(e,...t){await this.runStore.saveRun({...e},...t)}envelopeOf(e,t){return{runId:e.runId,workflowId:t.workflowId??e.workflowId,type:t.type,nodeId:t.nodeId,edgeId:t.edgeId,payload:void 0===t.payload?void 0:Ge(t.payload)?t.payload:{nonSerializable:!0},error:t.error,parentRunId:t.parentRunId,path:t.path}}}function ai(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 si{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 ri(o,n.limits),this.executor=new ii(e,t,this.publisher,{onRunCompleted:n.onRunCompleted},n.limits),this.options={...n,limits:{...ue,...n.limits}}}get limits(){return this.options.limits}async createRun(e,t,o,...n){this.validateCreateRequest(e);const r=e.workflowId??e.workflow?.id??"";if(!r)throw new x("Graph run request must carry a workflow document with an id or a saved workflowId");if(e.workflowId&&!this.options.documentResolver)throw new x("Graph run requests by workflowId require a document resolver");const i=o??t??"anonymous",a=this.activeByCaller.get(i)??new Set;if(a.size>=this.options.limits.maxConcurrentRuns)throw new x(`Graph run rejected: the configured limit of ${this.options.limits.maxConcurrentRuns} concurrent runs per caller is exhausted`);const s=this.generateRunId(),d={runId:s,workflowId:r,ownerUser:t,status:"queued",createdAt:(new Date).toISOString()};this.executor.begin(s),await this.runStore.saveRun({...d},...n);const l=this.documentProviderFor(e,t);return a.add(s),this.activeByCaller.set(i,a),this.callerKeysByRun.set(s,i),this.executor.schedule(d,l,e.inputs??{},...n).catch(()=>{}).finally(()=>this.finishActiveRun(s)),d}async getRun(e,t,...o){const n=await this.runStore.readRun(e,...o);if(!n)throw new _(`No graph run found for runId '${e}'`);return this.assertOwnership(n,t),n}async listRunsByWorkflow(e,t,...o){return(await this.runStore.listRuns(e,...o)).filter(e=>zr({owner:e.owner},t,{allowAnonymousAccess:!0===this.options.allowAnonymousAccess})).sort((e,t)=>{const o=e.updatedAt instanceof Date?e.updatedAt.getTime():NaN,n=t.updatedAt instanceof Date?t.updatedAt.getTime():NaN;return(Number.isFinite(n)?n:0)-(Number.isFinite(o)?o:0)})}async cancelRun(e,t,...o){const n=await this.runStore.readRun(e,...o);if(!n)throw new _(`No graph run found for runId '${e}'`);return this.assertWriteOwnership(n,t),"succeeded"===(r=n.status)||"failed"===r||"cancelled"===r||(this.executor.abort(e,"user"),n.status="cancelled",n.finishedAt=(new Date).toISOString(),await this.runStore.saveRun({...n},...o)),n;var r}async 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 x("Graph run request must be an object carrying either a workflow document or a workflowId plus inputs");const t=void 0!==e.workflow,o=void 0!==e.workflowId;if(t&&o)throw new x("Graph run request is ambiguous: supply either an unsaved workflow document or a saved workflowId, not both");if(!t&&!o)throw new x("Graph run request must supply either an unsaved workflow document or a saved workflowId");if(t&&!pt(e.workflow))throw new x("Graph run request carries a payload that is not a canonical GraphWorkflowDocument");if(void 0!==e.inputs&&!Ue(e.inputs))throw new x("Graph run inputs must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys and unsafe prototype keys (__proto__/prototype/constructor) are rejected");const n=(e=>{try{return JSON.stringify(e)?.length??0}catch{return Number.MAX_SAFE_INTEGER}})(e);if(n>this.options.limits.maxRequestBytes)throw new x(`Graph run request of ${n} bytes exceeds the configured limit of ${this.options.limits.maxRequestBytes} bytes`)}documentProviderFor(e,t){if(e.workflow){const t=e.workflow;return async()=>({document:t,fingerprint:Zr(t)})}const o=e.workflowId;return async(...e)=>{const n=this.options.documentResolver;if(!n)throw new x("Graph run requests by workflowId require a document resolver");const r=await n.resolve(o,t,...e);return{document:r,fingerprint:Zr(r)}}}assertOwnership(e,t){Yr({owner:e.ownerUser},t,{allowAnonymousAccess:!0===this.options.allowAnonymousAccess,resourceKind:"Graph run",resourceId:e.runId})}assertWriteOwnership(e,t){Xr({owner:e.ownerUser},t,{resourceKind:"Graph run",resourceId:e.runId})}generateRunId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new ro("Cannot generate a graph run id: crypto.randomUUID is unavailable in this runtime",{runtime:typeof globalThis.crypto});return e.randomUUID()}}function di(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 li(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&pt(e.document)&&!pt(e)}function ci(e){return JSON.parse(JSON.stringify(e))}function ui(e){if(null==e)return 0;let t;try{t=e.getTime()}catch{return 0}return Number.isFinite(t)?t:0}let pi=class extends V{constructor(e){super(jt),this.catalogue=e}get limits(){return{...Hn,...Kn.graph.workflows.limits??{}}}get allowAnonymousAccess(){return!0===Kn.graph.workflows.allowAnonymousAccess}async saveDocument(e,t,...o){const{ctx:n,ctxArgs:r}=(await this.logCtx(o,"saveDocument",!0)).for(this.saveDocument);if(!pt(t))throw new x("Payload is not a canonical GraphWorkflowDocument: id and name must be strings and inputs, outputs, nodes and edges must be arrays");if(t.id!==e)throw new x(`Document id '${t.id}' does not match the workflow id '${e}' from the request path`);const i=await this.validateDocument(t,n);if(!i.valid)throw new lo(i.issues);const a=di(n);let s;try{s=await this.read(e,...r)}catch{s=null}s&&this.assertWriteOwnership(e,s,a);const d=new Date;if(s)return s.name=t.name,s.document=ci(t),s.updatedAt=d,this.update(s,...r);const l=new jt({workflowId:e,name:t.name,document:ci(t),...a?{owner:a}:{},updatedAt:d});return this.create(l,...r)}async getDocument(e,...t){const{ctx:o,ctxArgs:n}=(await this.logCtx(t,"getDocument",!0)).for(this.getDocument);let r;try{r=await this.read(e,...n)}catch{r=null}if(!r)throw new _(`No graph workflow found for workflowId '${e}'`);if(this.assertOwnership(e,r,di(o)),r.document)return ci(r.document);throw new _(`Graph workflow '${e}' has no canonical document; legacy definition/state snapshots are no longer supported (DECAF-50 \xa74.26 R2-2)`)}async listWorkflows(...e){const{ctx:t,ctxArgs:o}=(await this.logCtx(e,"listWorkflows",!0)).for(this.listWorkflows),n=await this.listBy("workflowId",H.ASC,...o),r=di(t);return n.filter(e=>zr(e,r,{allowAnonymousAccess:this.allowAnonymousAccess})).sort((e,t)=>ui(t.updatedAt)-ui(e.updatedAt))}async assertAccess(e,...t){const{ctx:o,ctxArgs:n}=(await this.logCtx(t,"assertAccess",!0)).for(this.assertAccess);let r;try{r=await this.read(e,...n)}catch{r=null}if(!r)throw new _(`No graph workflow found for workflowId '${e}'`);return this.assertOwnership(e,r,di(o)),r}async validateDocument(e,...t){const{ctx:o}=(await this.logCtx(t,"validateDocument",!0)).for(this.validateDocument);return await Hr(e,{limits:this.limits,...this.catalogue?{catalogue:this.catalogue}:{}},o)}async saveSnapshot(e,t,...o){const{ctx:n,ctxArgs:r}=(await this.logCtx(o,"saveSnapshot",!0)).for(this.saveSnapshot);if(!Ue(t))throw new x("Workflow snapshot payload must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys and unsafe prototype keys (__proto__/prototype/constructor) are rejected");if(!li(t))throw new x("Workflow snapshots must wrap a canonical GraphWorkflowDocument ({ document, editor?, metadata? }): legacy definition/state snapshots are no longer accepted; save canonical documents via PUT /graph/workflows/{workflowId}");const i=di(n);let a;try{a=await this.read(e,...r)}catch{a=null}a&&this.assertWriteOwnership(e,a,i);const s=new Date;if(a)return a.snapshot=t,await this.applyCanonicalWrapper(a,t,n),a.updatedAt=s,this.update(a,...r);const d=new jt({workflowId:e,snapshot:t,...i?{owner:i}:{},updatedAt:s});return await this.applyCanonicalWrapper(d,t,n),this.create(d,...r)}async loadSnapshot(e,...t){const{ctx:o,ctxArgs:n}=(await this.logCtx(t,"loadSnapshot",!0)).for(this.loadSnapshot);try{const t=await this.read(e,...n);return this.assertOwnership(e,t,di(o)),t}catch{return null}}assertOwnership(e,t,o){Yr(t??null,o??null,{allowAnonymousAccess:this.allowAnonymousAccess,resourceKind:"Graph workflow",resourceId:e})}assertWriteOwnership(e,t,o){Xr(t??null,o??null,{resourceKind:"Graph workflow",resourceId:e})}async applyCanonicalWrapper(e,t,o){if(!li(t))return;if(t.document.id!==e.workflowId)throw new x(`Document id '${t.document.id}' does not match the workflow id '${e.workflowId}' from the request path`);const n=await Hr(t.document,{limits:this.limits,...this.catalogue?{catalogue:this.catalogue}:{}},o);if(!n.valid)throw new lo(n.issues);e.document=ci(t.document),e.name=t.document.name}};pi=D([G(jt),$("design:paramtypes",[Function])],pi);let hi=class extends V{constructor(){super(Lt)}async saveRun(e,...t){const{ctxArgs:o}=(await this.logCtx(t,"saveRun",!0)).for(this.saveRun),n=ti(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)}};hi=D([G(Lt),$("design:paramtypes",[])],hi);class fi{map(e){const t={};for(const[o,n]of Object.entries(e.nodeResults))t[o]={status:n.status,startedAt:n.startedAt?.toISOString(),finishedAt:n.finishedAt?.toISOString(),error:n.error,outputs:n.outputs,fromCache:n.fromCache,pinned:n.pinned};const o={};for(const t of e.events)t.edgeId&&"edge.valueRouted"===t.type&&(o[t.edgeId]={status:se.SUCCEEDED,lastValue:t.payload?.value,updatedAt:t.timestamp.toISOString()});const n=[...e.events];return{runId:e.runId,status:e.status,nodes:t,edges:o,outputs:e.outputs,events:n}}}export{cr as AgentNode,Cn as BreakFlowNode,rr as ChatTriggerNode,Qn as CodeInputSchema,Zn as CodeNode,Mn as ConditionExpressionEvaluator,Hn as DEFAULT_GRAPH_WORKFLOW_DOCUMENT_LIMITS,Ho as DEFAULT_GRAPH_WORKFLOW_VALIDATION_LIMITS,sn as DEFAULT_PINNING_METADATA,er as DelayFlowNode,Ln as ErrorBoundaryFlowNode,ir as EventTriggerNode,ar as FormTriggerNode,ur as GRAPH_AGENT_NODES,Sr as GRAPH_BOUNDARY_NODES,Rr as GRAPH_BUILT_IN_NODE_CLASSES_BY_KIND,Ar as GRAPH_BUILT_IN_NODE_MANIFESTS,kr as GRAPH_BUILT_IN_NODE_MANIFESTS_BY_KIND,Yn as GRAPH_CODE_DEFAULT_LANGUAGE,zn as GRAPH_CODE_DEFAULT_TIMEOUT_MS,Xn as GRAPH_CODE_LANGUAGES,Kt as GRAPH_CODE_MAX_TIMEOUT_MS,Bt as GRAPH_DEFAULT_CONCURRENCY,Wt as GRAPH_DEFAULT_MAX_FOREACH_ITERATIONS,qt as GRAPH_DEFAULT_MAX_LOOP_ITERATIONS,Ko as GRAPH_DOCUMENT_FORBIDDEN_FIELD_KEYS,Dr as GRAPH_FLOW_CONTROL_NODES,Yt as GRAPH_LOOP_KIND,Pr as GRAPH_LOOP_NODES,Ht as GRAPH_MAX_FOREACH_ITERATIONS,Vt as GRAPH_MAX_LOOP_ITERATIONS,zt as GRAPH_PINNING_METADATA_KEY,Mo as GRAPH_PLAIN_SECRET_KEYS,_r as GRAPH_TRIGGER_NODES,$r as GRAPH_UTILITY_NODES,Ft as GRAPH_WORKFLOW_BOUNDARY,Gr as GRAPH_WORKFLOW_FORBIDDEN_FIELD_KEYS,xo as GraphAuthValidator,ao as GraphBreakSignal,gr as GraphConditionEvaluator,Xt as GraphConditionType,Fo as GraphConnectionPolicyValidator,Wo as GraphConnectionValidationError,Vo as GraphCredentialAuthorizationError,Bo as GraphCredentialReferenceValidator,Zt as GraphCycleError,qo as GraphDocumentValidationError,Uo as GraphEdgeInstanceValidator,Kn as GraphEnvironment,Do as GraphExecutionContext,un as GraphExecutionEngine,Qt as GraphExecutionError,co as GraphExecutionEventEmitter,uo as GraphExecutionEventFactory,$o as GraphExecutionFrame,Yo as GraphExecutionPlanner,fi as GraphExecutionSnapshotMapper,fr as GraphForeachLoopNode,eo as GraphInputError,wr as GraphInputValueNode,Kr as GraphLoopExecutionContext,to as GraphLoopLimitError,Rn as GraphNode,kn as GraphNodeCatalogue,_n as GraphNodeExecutorRegistry,Dn as GraphNodeExecutorResolver,So as GraphNodeInstanceValidator,Nn as GraphNodeManifestResolver,mn as GraphNodeMethodNotFoundError,yn as GraphNodeMethodRegistry,gn as GraphNodeNotFoundError,fn as GraphNodeRegistrationError,br as GraphOutputValueNode,Go as GraphParameterValidator,cn as GraphPinningDependencyResolver,oo as GraphPinningError,ln as GraphPinningPolicy,an as GraphPinningService,Jt as GraphPinningStrategy,no as GraphPortError,jr as GraphPortSchemaResolver,so as GraphRunCancelledError,ri as GraphRunEventPublisher,ii as GraphRunExecutor,hi as GraphRunModelService,si as GraphRunService,ro as GraphStoreError,rn as GraphTopology,io as GraphTopologyError,mr as GraphUntilLoopNode,Qo as GraphValueModel,on as GraphValueRepository,Mr as GraphValueValidator,yr as GraphWhileLoopNode,lo as GraphWorkflowDocumentRejectedError,Xo as GraphWorkflowDocumentValidator,pi as GraphWorkflowService,jn as HumanApprovalFlowNode,Wn as IfFlowNode,ei as InMemoryGraphRunEventStore,ni as InMemoryGraphRunStore,hn as IsolatedVmCodeSandboxEvaluator,tr as LogFlowNode,sr as ManualTriggerNode,or as MapNode,dr as ScheduleTriggerNode,Vn as SwitchFlowNode,nr as UtilityLogNode,lr as WebhookTriggerNode,Yr as assertGraphResourceOwnership,Xr as assertGraphResourceWriteOwnership,Po as buildGraphExecutionResult,Tr as builtInGraphNodeRegistrations,zr as canAccessGraphResource,Jr as canAccessGraphResourcePayload,Co as checkGraphValueAgainstSchema,Jn as clampGraphCodeTimeoutMs,Ro as collectLooseNodeIssues,ho as composeGraphNamespace,nn as createGraphValueRepository,Pn as declaredGraphNodeMethods,po as decomposeGraphNamespace,Oo as decomposeGraphNamespaces,$n as defineGraphNode,Fn as evaluateCodeCondition,qn as evaluateCondition,Bn as evaluateConditionSync,wo as findMalformedGraphNamespaces,yo as findUngrantedGraphNamespaces,Eo as graphAuthDataFromRecord,No as graphAuthDataOf,mo as graphNamespaceCovers,go as graphNamespacePartsOf,Sn as graphNodeConfig,bo as graphRolesFromNamespaces,Zr as graphRunDocumentFingerprint,di as graphWorkflowOwnerOf,Gn as isCodeCondition,Un as isConditionExpression,Lo as isGraphCredentialReferenceLike,fo as isGraphNamespaceCacheEntryValid,zo as isGraphResolvedWorkflow,dn as isPinnable,Ao as mergeGraphAuthData,Lr as registerBuiltInGraphNodes,In as resolveGraphDynamicPorts,En as resolveGraphNodeManifest,Zo as serializeGraphValueKey,Hr as validateGraphWorkflowDocumentAtBoundary};
1
+ import{logParameterRegistry as e,Logging as t,LoggedEnvironment as o}from"@decaf-ts/logging";import{RenderingEngine as n,uimodel as r,uielement as i,uilistprop as a,uilistmodel as s,hidden as d}from"@decaf-ts/ui-decorators";import{Metadata as l,Decoration as c,apply as u,metadata as p,propMetadata as h,description as f,prop as g,DefaultFlavour as m}from"@decaf-ts/decoration";import{ValidationKeys as y,Model as w,required as b,type as v,date as I,model as E,option as N,min as O,max as k}from"@decaf-ts/decorator-validation";import{ValidationError as A,InternalError as x,NotFoundError as _}from"@decaf-ts/db-decorators";import{__decorate as S,__metadata as D}from"tslib";import{pk as P,column as R,index as $,table as C,BaseModel as T,ForbiddenError as L,Context as M,repository as j,Repository as G,AuthorizationError as U,service as F,Service as B,ClientBasedService as W,Adapter as q,ModelService as H,OrderDirection as K}from"@decaf-ts/core";import V from"isolated-vm";import*as z from"acorn";import*as J from"acorn-walk";import*as X from"typescript";import{createHash as Y}from"node:crypto";var Q,Z;y.REQUIRED,y.MIN,y.MIN_LENGTH,y.MAX,y.MAX_LENGTH,y.PATTERN,y.URL,y.STEP,y.DATE,y.EMAIL,y.PASSWORD,y.EQUALS,y.DIFF,y.LESS_THAN,y.LESS_THAN_OR_EQUAL,y.GREATER_THAN,y.GREATER_THAN_OR_EQUAL,(e=>{e.GRAPH="graph",e.NODE="graph.node",e.EDGE="graph.edge",e.PORT="graph.port",e.STATE="graph.state"})(Q||(Q={})),(e=>{e.INPUT="input",e.OUTPUT="output",e.CONNECTION="connection"})(Z||(Z={}));const ee={};function te(e,t={}){let o=e.width??96,n=e.height??96;for(const r of e.sizeRules??[]){if("parameterCount"!==r.type)continue;const e=t[r.parameter]??0;e>0&&("width"===r.dimension?o+=e*r.perItem:n+=e*r.perItem)}return{width:o,height:n}}function oe(e,t){ee[e]=t}function ne(e,t,o){const n=t?ee[t]:void 0;return n?.color?n.color:e||"#64748b"}function re(e,t,o){const n=t?ee[t]:void 0;return n?.icon?n.icon:e||"ti-pointer"}const ie=["skip","passThroughFirstInput","emitDefaults"];function ae(e){return ie.includes(e)}var se,de,le,ce;(e=>{e.PENDING="pending",e.PLANNING="planning",e.RUNNING="running",e.SUCCEEDED="succeeded",e.FAILED="failed",e.SKIPPED="skipped",e.CANCELLED="cancelled",e.CACHED="cached"})(se||(se={})),(e=>{e.IDLE="idle",e.RUNNING="running",e.BLOCKED="blocked",e.SUCCEEDED="succeeded",e.FAILED="failed",e.SKIPPED="skipped"})(de||(de={})),(e=>{e.NODE_ID="nodeId",e.WORKFLOW_ID="workflowId",e.RUN_ID="runId",e.USER="user",e.ROLES="roles",e.NAMESPACES="namespaces",e.ORGANIZATION="organization",e.IP="ip"})(le||(le={})),(e=>{e.WORKFLOW_STARTED="workflow.started",e.WORKFLOW_PLANNED="workflow.planned",e.WORKFLOW_COMPLETED="workflow.completed",e.WORKFLOW_FAILED="workflow.failed",e.WORKFLOW_CANCELLED="workflow.cancelled",e.WORKFLOW_SUSPENDED="workflow.suspended",e.WORKFLOW_RESUMED="workflow.resumed",e.NODE_QUEUED="node.queued",e.NODE_STARTED="node.started",e.NODE_OUTPUT="node.output",e.NODE_COMPLETED="node.completed",e.NODE_FAILED="node.failed",e.NODE_SKIPPED="node.skipped",e.NODE_CACHE_HIT="node.cacheHit",e.NODE_PINNED="node.pinned",e.NODE_UNPINNED="node.unpinned",e.NODE_STATE_CHANGED="node.stateChanged",e.EDGE_VALUE_ROUTED="edge.valueRouted",e.EDGE_STATE_CHANGED="edge.stateChanged",e.GRAPH_RUN_LOG="graph.run.log",e.LOOP_STARTED="loop.started",e.LOOP_ITERATION_STARTED="loop.iteration.started",e.LOOP_ITERATION_COMPLETED="loop.iteration.completed",e.LOOP_CONDITION_EVALUATED="loop.condition.evaluated",e.LOOP_COMPLETED="loop.completed",e.LOOP_LIMIT_REACHED="loop.limitReached",e.VALIDATION_STARTED="validation.started",e.VALIDATION_FAILED="validation.failed",e.VALIDATION_COMPLETED="validation.completed",e.STORE_READ="store.read",e.STORE_WRITE="store.write",e.STORE_DELETE="store.delete"})(ce||(ce={}));const ue={maxRequestBytes:4e6,maxConcurrentRuns:32,maxEventsPerRun:1e4,maxEventPayloadBytes:256e3,executionTimeoutMs:6e5,eventReplayWindowMs:3e5},pe=[ce.WORKFLOW_COMPLETED,ce.WORKFLOW_FAILED,ce.WORKFLOW_CANCELLED];function he(e){return pe.includes(e)}function fe(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}function ge(e){const t=l.constr(e);if("function"==typeof t)return t;const o=e.constructor;return"function"==typeof o?o:e}function me(e){if(null!=e)return"string"==typeof e?e:e+""}function ye(e,t,o){return me(e?.props?.label??e?.props?.name)??me(t?.name)??o??""}function we(e,t,o){const n=Ie(e,t);if(n?.model&&"function"==typeof n.model&&w.isModel(n.model))return n.model;const r=l.type(e,t);if("function"==typeof r&&w.isModel(r))return r;const i=l.getPropDesignTypes?.(e,t)?.designTypes||[];for(const e of i)if("function"==typeof e&&w.isModel(e))return e;const a=o?.[y.TYPE]?.customTypes||[];for(const e of a)if("function"==typeof e&&w.isModel(e))return e}function be(e,t){const o=[t,e.path??e.property].filter(Boolean).join(".");return{...e,path:o,children:e.children?.map(e=>be(e,o))}}function ve(e){const t=ge(e);return l.get(t,Q.NODE)}function Ie(e,t){const o=ge(e);return l.get(o,l.key(Q.PORT,t+""))}function Ee(e,t,o,n=new Set){const r=Ie(e,t);if(!r?.schema)return;const i=we(e,t,l.validationFor(e,t));if(!i)return;if(n.has(i))return[];const a=new Set(n);return a.add(e),a.add(i),ke(i,a).filter(e=>e.direction===o)}function Ne(e,t,o=new Set){const n=Ie(e,t);if(!n)return;const r=l.validationFor(e,t),i=we(e,t,r);if(n.schema&&i)return;const a=w.uiElementOf(e,t)||void 0,s=w.uiDecorationOf(e,t,"uiprop"),d=l.type(e,t),c=me(n.type??r?.[y.TYPE]?.customTypes?.[0]?.name??a?.props?.type??s?.type??d?.name),u=(n.expand||i&&!o.has(i))&&i?(()=>{const n=new Set(o);return n.add(e),n.add(i),ke(i,n).map(e=>be(e,t))})():void 0;return{property:t,path:t,direction:n.direction,name:t,label:ye(a,s,t),type:c?.toLowerCase(),required:!!r?.[y.REQUIRED],hidden:!!w.uiIsHidden(e,t),designType:d?.name,element:a,prop:s,validation:r,graph:n,connectionRules:n.connectionRules,composite:!!u?.length,children:u,model:i?.name}}function Oe(e){return ke(ge(e))}function ke(e,t=new Set){const o=l.properties(e)||[],n=[];for(const r of o){const o=r+"",i=Ie(e,o);if(i?.schema){const r=Ee(e,o,i.direction,t);if(r){n.push(...r);continue}}const a=Ne(e,o,t);a&&n.push(a)}return n}function Ae(e){return e.flatMap(e=>e.children&&e.children.length?Ae(e.children):[e])}function xe(e){const t=ge(e),o=w.uiModelOf(t),n=ve(t)||{},r=o?.tag||t.name,i=Oe(t),a=((e,t)=>{const o=t.portGroups||[],n=new Map(o.map(e=>[e.property,e])),r=[],i=l.properties(e)||[];for(const t of i){const o=t+"",i=Ie(e,o);if(!i?.schema)continue;if(!we(e,o,l.validationFor(e,o)))continue;const a=n.get(o);r.push(a?{...a,toggle:a.toggle??"all"}:{property:o,toggle:"all"})}for(const e of o)r.some(t=>t.property===e.property)||r.push(e);return r.length?r:void 0})(t,n),s=n.namespaces?.length?n.namespaces:(e=>{if(null==e)return[];let t,o=e;try{o=l.constr(e)}catch{o=e}try{t=l.get(o,"auth-namespace")}catch{t=void 0}return fe(t)??[]})(t),d=s.length?s:void 0;return{name:t.name,tag:r,kind:n.kind||r,category:n.category,color:n.color,effectiveColor:ne(n.color,n.category),group:n.group,height:n.height,icon:n.icon,effectiveIcon:re(n.icon,n.category),labels:n.labels||[],maxChildren:n.maxChildren,minWidth:n.minWidth,width:n.width,shape:n.shape,cornerRadius:n.cornerRadius,sizeRules:n.sizeRules,props:o?.props,ui:o,graph:n,ports:i,portGroups:a,namespaces:d}}const _e=new Set,Se=new Set;function De(e,t,o){return c.for(Q.NODE).define({decorator:(e,t,o)=>{const n={kind:t?.kind||e,...t};return t=>{const i=u(r(e,o),p(Q.NODE,n))(t);var a;return a=t,_e.add(a),i}},args:[e,t,o]}).apply()}function Pe(e,t){return c.for(Q.PORT).define({decorator:(e,t)=>(o,n)=>{const r={direction:e,...t};return u(h(l.key(Q.PORT,n),r))(o,n)},args:[e,t]}).apply()}function Re(e){return Pe(Z.INPUT,{...e,schema:!0})}function $e(e){return Pe(Z.OUTPUT,{...e,schema:!0})}function Ce(e){return Pe(Z.CONNECTION,e)}n.prototype.renderAsNode=(e,t,...o)=>xe(e),l.nodes=(()=>[..._e]).bind(l),l.workflows=(()=>[...Se]).bind(l);const Te=["__proto__","prototype","constructor"];function Le(e){return Te.includes(e)}function Me(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function je(e){return null===e||"string"==typeof e||"number"==typeof e&&Number.isFinite(e)||"boolean"==typeof e}function Ge(e){return!!je(e)||(Array.isArray(e)?e.every(e=>Ge(e)):!!Me(e)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&!Le(t)&&Ge(e[t])))}function Ue(e){if(void 0===e)return!1;if("number"==typeof e)return Number.isFinite(e);if("function"==typeof e)return!1;if(Ge(e))return!0;if(Array.isArray(e))return e.every(e=>Ue(e));if(Me(e)){const t=Reflect.ownKeys(e);for(const o of t){if("string"!=typeof o)return!1;if(Le(o))return!1;if(!Ue(e[o]))return!1}return!0}return!1}function Fe(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>Fe(e));const t={};for(const[o,n]of Object.entries(e))t[o]=Fe(n);return t}const Be={string:"string",char:"string",text:"string",textarea:"string",radio:"string",select:"string",number:"number",integer:"number",float:"number",double:"number",decimal:"number",boolean:"boolean",bool:"boolean",checkbox:"boolean",array:"array",list:"array",set:"array",object:"object",model:"model",any:"any",unknown:"any",enum:"enum"},We={date:"date",datetime:"date-time","date-time":"date-time",duration:"duration"};function qe(e){return e?Be[e.toLowerCase()]??"any":"any"}function He(e,t){const o=e[t];if(o&&"object"==typeof o)return o.value}function Ke(e,t){const o=He(e,t);return"number"==typeof o&&Number.isFinite(o)?o:void 0}function Ve(e,t,o){const n=e??{},r=(e=>{const t=He(e,y.ENUM);if(Array.isArray(t)&&t.every(je))return t})(n);if(r)return{type:"enum",values:r};const i=(e=>{const t=e[y.TYPE],o=t?.customTypes?.[0],n="function"==typeof o?o.name:o?.name;if(n)return n})(n)??o;return i?{type:"model",name:i}:((e,t)=>{switch(qe(e)){case"string":{const t=(e=>{if(e)return We[e.toLowerCase()]})(e);return void 0!==t?{type:"string",format:t}:{type:"string"}}case"number":{const o={type:"number"};e&&"integer"===e.toLowerCase()&&(o.integer=!0);const n=Ke(t,y.MIN),r=Ke(t,y.MAX);return void 0!==n&&(o.min=n),void 0!==r&&(o.max=r),o}case"boolean":return{type:"boolean"};case"array":return((e,t)=>{const o={type:"array",items:ze(e,t)},n=Ke(e,y.MIN),r=Ke(e,y.MAX);return void 0!==n&&(o.minItems=n),void 0!==r&&(o.maxItems=r),o})(t,e);case"object":return{type:"object",properties:{}};case"enum":return{type:"enum",values:[]};case"model":return{type:"model",name:e??"any"};default:return{type:"any"}}})(t,n)}function ze(e,t){if((e=>{const t=e[y.LIST];return!!t?.clazz?.length})(e))return{type:"model",name:Je(e)};const o=He(e,y.TYPE);if("string"==typeof o){const e=qe(o);return"model"===e?{type:"model",name:o}:{type:e}}if(t&&"array"!==t){const e=qe(t);return"model"===e?{type:"model",name:t}:{type:e}}return{type:"any"}}function Je(e){const t=e[y.LIST],o=t?.clazz?.[0];if("function"!=typeof o)return"any";if(o.name)return o.name;try{const e=o();if("function"==typeof e&&e.name)return e.name}catch{return"any"}return"any"}function Xe(e){return"workflow"===e.scope}function Ye(e){return"node"===e.scope}function Qe(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"workflow"===t.scope?"string"==typeof t.port&&2===Reflect.ownKeys(t).length:"node"===t.scope&&"string"==typeof t.nodeId&&"string"==typeof t.port&&3===Reflect.ownKeys(t).length}function Ze(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e.mode;if("edge"===t)return 1===Reflect.ownKeys(e).length;if("literal"===t){const t=e.value;return 2===Object.keys(e).length&&Ge(t)}return"expression"===t&&2===Object.keys(e).length&&"string"==typeof e.expression}const et=["any","string","number","boolean","array","object","enum","model"];function tt(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&(e=>et.includes(e))(e.type)}function ot(e,t={seen:[]}){if(t.seen.includes(e))throw new A(`Document '${(e=>{const t=e?.id;return"string"==typeof t?t:"<unnamed document>"})(e)}' contains a loop body that references itself (cyclic document)`);if("string"!=typeof e.id||!e.id)throw new A("Document 'id' is required and must be a non-empty string");if("string"!=typeof e.name||!e.name)throw new A("Document 'name' is required and must be a non-empty string");const o=new Set;for(const t of[...e.inputs,...e.outputs]){if("string"!=typeof t.id||!t.id)throw new A("Workflow port 'id' is required and must be a non-empty string");if(o.has(t.id))throw new A(`Workflow port '${t.id}' is declared more than once; workflow port ids must be unique`);if(void 0!==t.schema&&!tt(t.schema))throw new A(`Workflow port '${t.id}' schema must be a valid GraphValueSchema`);o.add(t.id)}const n={seen:[...t.seen,e]},r=new Set;for(const t of e.nodes)nt(t,r);for(const t of e.nodes)t.loop&&rt(t,t.loop,n),t.errorBoundary&&it(t,t.errorBoundary,n);const i=new Set;for(const t of e.edges)st(t,i);for(const t of e.edges)dt(t.source,0,o,r,`Edge '${t.id}' source`),dt(t.target,0,o,r,`Edge '${t.id}' target`);if(void 0!==e.settings&&!Ue(e.settings))throw new A("Document settings must be JSON-safe (a map of JSON-safe values)");if(void 0!==e.metadata&&!Ue(e.metadata))throw new A("Document metadata must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed");if(void 0!==e.ui&&!Ue(e.ui))throw new A("Document ui must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed")}function nt(e,t){if("string"!=typeof e.id||!e.id)throw new A("Node 'id' is required and must be a non-empty string");if(t.has(e.id))throw new A(`Node id '${e.id}' is declared more than once; node ids must be unique`);if("string"!=typeof e.kind||!e.kind)throw new A(`Node '${e.id}' must declare a non-empty string 'kind'`);if(void 0===e.parameters||null===e.parameters)throw new A(`Node '${e.id}' parameters must be present (an empty object when there are none)`);if(t.add(e.id),e.inputBindings)for(const[t,o]of Object.entries(e.inputBindings)){if(Le(t))throw new A(`Node '${e.id}' input binding key '${t}' is not allowed (unsafe prototype-pollutant key)`);if(!Ze(o))throw new A(`Node '${e.id}' input binding for '${t}' must be a valid GraphInputBinding (edge, literal, or expression)`);if("literal"===o.mode&&!Ue(o.value))throw new A(`Node '${e.id}' literal binding for '${t}' must contain JSON-safe values`);if("expression"===o.mode&&!o.expression)throw new A(`Node '${e.id}' expression binding for '${t}' must contain a non-empty expression`)}if(e.outputBindings)for(const[t,o]of Object.entries(e.outputBindings)){if(Le(t))throw new A(`Node '${e.id}' output binding key '${t}' is not allowed (unsafe prototype-pollutant key)`);if(!o||"object"!=typeof o||Array.isArray(o))throw new A(`Node '${e.id}' output binding for '${t}' must be an object with enabled and alias settings`)}if(!Ue(e.parameters))throw new A(`Node '${e.id}' parameters must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed`);if(void 0!==e.state){if(!e.state||"object"!=typeof e.state||Array.isArray(e.state))throw new A(`Node '${e.id}' state must be an object when present`);if(!Ue(e.state))throw new A(`Node '${e.id}' state must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed`)}}function rt(e,t,o){if(!t.body||"object"!=typeof t.body)throw new A(`Node '${e.id}' loop configuration requires a body document`);if(ot(t.body,o),!(void 0===t.maxIterations||Number.isFinite(t.maxIterations)&&t.maxIterations>0))throw new A(`Node '${e.id}' loop maxIterations must be a positive number`);if(void 0!==t.timeoutMs&&("number"!=typeof t.timeoutMs||0>=t.timeoutMs))throw new A(`Node '${e.id}' loop timeoutMs must be a positive number in milliseconds`);if(void 0!==t.concurrency&&("number"!=typeof t.concurrency||0>=t.concurrency))throw new A(`Node '${e.id}' loop concurrency must be a positive number`);for(const o of[t.inputMappings,t.outputMappings])if(o)for(const[t,n]of Object.entries(o)){if(Le(t))throw new A(`Node '${e.id}' loop mapping key '${t}' is not allowed (unsafe prototype-pollutant key)`);at(n,e.id,t)}}function it(e,t,o){if(!t.try||"object"!=typeof t.try)throw new A(`Node '${e.id}' error-boundary configuration requires a try body document`);ot(t.try,o);for(const[n,r]of[["catch",t.catch],["finally",t.finally]])if(void 0!==r){if(!r||"object"!=typeof r)throw new A(`Node '${e.id}' error-boundary ${n} body must be a document`);ot(r,o)}}function at(e,t,o){if(!e||"object"!=typeof e)throw new A(`Node '${t}' loop mapping '${o}' must reference a workflow port, node port, literal, or expression`);switch(e.source){case"workflow":if("string"!=typeof e.port||!e.port)throw new A(`Node '${t}' loop mapping '${o}' referencing a workflow must reference a port identifier`);break;case"node":if("string"!=typeof e.nodeId||!e.nodeId||"string"!=typeof e.port||!e.port)throw new A(`Node '${t}' loop mapping '${o}' referencing a node must reference a node id and a port`);break;case"literal":if(!Ue(e.value))throw new A(`Node '${t}' loop mapping '${o}' literal references must be JSON-safe values`);break;case"expression":if("string"!=typeof e.expression||!e.expression)throw new A(`Node '${t}' loop mapping '${o}' expression references must be non-empty expressions`);break;default:throw new A(`Node '${t}' loop mapping '${o}' must use a workflow, node, literal, or expression reference source`)}}function st(e,t){if("string"!=typeof e.id||!e.id)throw new A("Edge 'id' is required and must be a non-empty string");if(t.has(e.id))throw new A(`Edge id '${e.id}' is declared more than once; edge ids must be unique`);if(!Qe(e.source))throw new A(`Edge '${e.id}' source endpoint is not a valid GraphEndpoint`);if(!Qe(e.target))throw new A(`Edge '${e.id}' target endpoint is not a valid GraphEndpoint`);if("data"!==e.type&&"connection"!==e.type)throw new A(`Edge '${e.id}' type '${e.type+""}' is not a valid edge type (data or connection are allowed)`);if(t.add(e.id),!Ue(e))throw new A(`Edge '${e.id}' contains values that are not JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed`)}function dt(e,t,o,n,r){if(Xe(e)){if(!o.has(e.port))throw new A(`${r} references workflow port '${e.port}' which is not declared on the document`)}else if(Ye(e)){if(!n.has(e.nodeId))throw new A(`${r} references node '${e.nodeId}' which is not part of the document`);if("string"!=typeof e.port||!e.port)throw new A(r+" node endpoints must reference a non-empty port identifier")}}const lt=["expression","template"],ct=["javascript","typescript","json","text"];function ut(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return!(!(e=>lt.includes(e))(t.mode)||"string"!=typeof t.expression||!t.expression||void 0!==t.language&&!(e=>ct.includes(e))(t.language)||void 0!==t.metadata&&!Ge(t.metadata))}function pt(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.name&&Array.isArray(t.inputs)&&Array.isArray(t.outputs)&&Array.isArray(t.nodes)&&Array.isArray(t.edges)}function ht(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.type&&(void 0===t.required||"boolean"==typeof t.required)&&(void 0===t.displayName||"string"==typeof t.displayName)&&(void 0===t.allowedOperations||Array.isArray(t.allowedOperations)&&t.allowedOperations.every(e=>"string"==typeof e))}const ft=["trigger","loop","branching","stateful","retryable","cancellable","parallel","resource"];function gt(e){return ft.includes(e)}function mt(e){if(!(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.kind&&"object"==typeof t.display&&Array.isArray(t.inputs)&&Array.isArray(t.outputs)&&Array.isArray(t.parameters)})(e))throw new A("Graph node manifest does not conform to the required shape");if(!Ue(e))throw new A("Graph node manifest contains values that are not JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys or unsafe prototype keys are not allowed on manifests")}const yt=["loadOptions","listSearch","resourceLocator","resourceMapping","validateParameter","action"];function wt(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.name&&(e=>yt.includes(e))(t.type)&&(void 0===t.parameter||"string"==typeof t.parameter)&&(void 0===t.dependencies||Array.isArray(t.dependencies)&&t.dependencies.every(e=>"string"==typeof e))}function bt(e){const t=e.element?.props?.value,o=t??e.prop?.value??e.validation?.defaultValue;if(void 0!==o&&"function"!=typeof o&&Ue(o))try{return JSON.parse(JSON.stringify(o))}catch{return}}function vt(e){if(e.type&&e.type in We)return{type:"string",format:We[e.type]};const t=(e=>{for(const t of[e.graph?.type,e.element?.props?.type,e.prop?.type])if("string"==typeof t&&"any"!==qe(t))return t})(e);return t?Ve((e=>{if(!e)return;const t=Object.entries(e).filter(([e])=>e!==y.TYPE);return Object.fromEntries(t)})(e.validation),t):Ve(e.validation,e.type,e.model)}function It(e){const t={};for(const[o,n]of Object.entries(e.graph?.metadata??{}))Ue(n)&&(t[o]=JSON.parse(JSON.stringify(n)));return Object.keys(t).length?t:void 0}function Et(e){switch(e){case"output":return"output";case"connection":return"connection";default:return"input"}}function Nt(e){const t=e.graph?.handle;return"connection"!==e.direction&&"string"==typeof t&&t?t:e.path??e.property}function Ot(e,t){const o={id:Nt(e),label:e.label,direction:Et(e.direction),schema:vt(e)};e.required&&(o.required=!0),e.hidden&&(o.hidden=!0);const n=e.graph?.category;"string"==typeof n&&(o.category=n),!0===e.graph?.userControlled&&(o.configurable=!0);const r=e.graph?.handle;"string"==typeof r&&(o.handle=r);const i=Ct(e.graph?.connectionRules)??t;i&&(o.connectionPolicy=i);const a=(e=>{const t=e.element;if(!t||!Ue(t))return;const o=t.tag;if("string"!=typeof o)return;const n=t.props;return{tag:o,serialize:!0===t.serialize,props:n&&"object"==typeof n&&!Array.isArray(n)?Fe(n):{}}})(e);a&&(o.element=a);const s=It(e);return s&&(o.metadata=s),o}function kt(e){const t={type:"string",id:Nt(e),label:e.label,required:e.required};if(e.hidden)return((e,t)=>{const o={...t,type:"hidden"},n=bt(e);return void 0!==n&&(o.defaultValue=n),At(o)})(e,t);const o=bt(e);void 0!==o&&(t.defaultValue=o);const n=(e=>{const t=e.element?.props?.placeholder??e.prop?.placeholder;return"string"==typeof t?t:void 0})(e);n&&(t.placeholder=n);const r=It(e);if(r&&(t.metadata=r),(e=>{const t=St(e);return"code"===t||"code-editor"===t})(e))return At({...t,type:"code",language:Rt(e)});const i=vt(e);switch(i.type){case"number":{const o={...t,type:"number",integer:i.integer,min:i.min,max:i.max},n=_t(e.validation?.step);return void 0!==n&&(o.step=n),At(o)}case"boolean":return At({...t,type:"boolean"});case"enum":return At({...t,type:"options",options:i.values.map(e=>({value:e,label:e+""}))});case"array":{const e={...t,type:"collection"};return void 0!==i.maxItems&&(e.maxItems=i.maxItems),At(e)}case"object":case"model":return At({...t,type:"object"});default:return At({...t,type:"string",multiline:!!Dt(e)||void 0,pattern:xt(e.validation?.pattern),minLength:_t(e.validation?.minlength),maxLength:_t(e.validation?.maxlength)})}}function At(e){const t=e;for(const e of Object.keys(t))void 0===t[e]&&delete t[e];return e}function xt(e){const t=e?.value;return"string"==typeof t?t:void 0}function _t(e){const t=e?.value;return"number"==typeof t&&Number.isFinite(t)?t:void 0}function St(e){const t=e.element?.tag;return"string"==typeof t&&t?t:void 0}function Dt(e){return"textarea"===St(e)||"textarea"===(e=>{const t=e.element?.props?.type;return"string"==typeof t?t:void 0})(e)}const Pt=["javascript","typescript","json","text"];function Rt(e){const t=e.element?.props?.language;return"string"==typeof t&&Pt.includes(t)?t:"javascript"}function $t(e,t){const o={name:t.name??e.name},n=e.graph?.metadata?.description??void 0;"string"==typeof n&&n&&(o.description=n);const r=t.category??e.category;"string"==typeof r&&r&&(o.category=r),"string"==typeof e.group&&e.group&&(o.group=e.group),Array.isArray(e.labels)&&(o.labels=e.labels.slice());const i=((e,t)=>{if(t.icon)return t.icon;const o=e.effectiveIcon??e.icon;return"string"==typeof o?{type:"catalogue",name:o}:{type:"catalogue",name:"ph:circuitry"}})(e,t);return i&&(o.icon=i),"string"==typeof e.color&&e.color&&(o.color=e.color),"number"==typeof e.width&&Number.isFinite(e.width)&&(o.width=e.width),"number"==typeof e.minWidth&&Number.isFinite(e.minWidth)&&(o.minWidth=e.minWidth),"number"==typeof e.height&&Number.isFinite(e.height)&&(o.height=e.height),"string"==typeof e.shape&&(o.shape=e.shape),"number"==typeof e.cornerRadius&&Number.isFinite(e.cornerRadius)&&(o.cornerRadius=e.cornerRadius),Array.isArray(e.sizeRules)&&(o.sizeRules=e.sizeRules),o}function Ct(e){if(!e)return;const t=e,o={};"boolean"==typeof t.allowSelf&&(o.allowSelf=t.allowSelf),"boolean"==typeof t.allowMultiple&&(o.allowMultiple=t.allowMultiple);const n=t.allowedKinds;Array.isArray(n)&&n.every(e=>"string"==typeof e)&&(o.allowedNodeKinds=n);const r=t.blockedKinds;Array.isArray(r)&&r.every(e=>"string"==typeof e)&&(o.blockedNodeKinds=r);const i=t.maxConnections;return"number"==typeof i&&Number.isFinite(i)&&(o.maxConnections=i),Object.keys(o).length?o:void 0}function Tt(e,t={}){const o="function"==typeof e?e:e.constructor;if(!ve(o))throw new A(`Node '${o?.name??e+""}' is not decorated with @node and cannot produce a manifest`);const n=xe(o),r=Ae(Oe(o)),i=[],a=[],s=[],d=[],l=Ct(n.graph?.connectionRules);for(const e of r)("connection"===e.direction?s:"output"===e.direction?a:i).push(Ot(e,l)),"input"===e.direction&&d.push(kt(e));const c={kind:t.kind??n.kind??n.name,display:$t(n,t),inputs:i,outputs:a,parameters:d};return s.length&&(c.connections=s),n.namespaces?.length&&(c.namespaces=n.namespaces.slice()),mt(c),c}var Lt,Mt;(e=>{e.READABILITY="readability",e.COMPACTNESS="compactness",e.BALANCED="balanced"})(Lt||(Lt={})),(e=>{e.TIGHT="tight",e.NORMAL="normal",e.COMFORTABLE="comfortable"})(Mt||(Mt={})),Mt.TIGHT,Mt.NORMAL,Mt.COMFORTABLE,Lt.READABILITY,Mt.COMFORTABLE,Lt.COMPACTNESS,Mt.TIGHT,Lt.BALANCED,Mt.NORMAL;let jt=class extends T{constructor(e){super(e)}};S([P({type:String,generated:!1}),f("Unique graph run id"),i("ngx-decaf-crud-field",{label:"graph.run.id.label",readonly:!0}),D("design:type",String)],jt.prototype,"runId",void 0),S([R(),b(),$(),f("Workflow document id the run executes"),a("workflowId"),i("ngx-decaf-crud-field",{label:"graph.run.workflowId.label"}),D("design:type",String)],jt.prototype,"workflowId",void 0),S([R(),f("Owning user; absent for anonymous callers"),i("ngx-decaf-crud-field",{label:"graph.run.owner.label"}),D("design:type",String)],jt.prototype,"owner",void 0),S([R(),b(),v(String),$(),f("Current run lifecycle status"),a("status"),i("ngx-decaf-crud-field",{label:"graph.run.status.label",readonly:!0}),D("design:type",String)],jt.prototype,"status",void 0),S([R(),f("Fingerprint of the executed document"),i("ngx-decaf-crud-field",{label:"graph.run.fingerprint.label",readonly:!0}),D("design:type",String)],jt.prototype,"documentFingerprint",void 0),S([R(),g(),f("Workflow input values keyed by input port id"),D("design:type",Object)],jt.prototype,"inputs",void 0),S([R(),g(),f("Execution result, present on successful completion"),D("design:type",Object)],jt.prototype,"result",void 0),S([R(),g(),f("Structured error payload, present on failure"),D("design:type",Object)],jt.prototype,"error",void 0),S([I(),R(),f("Run creation timestamp"),D("design:type",Date)],jt.prototype,"createdAt",void 0),S([I(),R(),f("Execution start timestamp, once it has started"),D("design:type",Date)],jt.prototype,"startedAt",void 0),S([I(),R(),f("Terminal-state timestamp, once the run has finished"),D("design:type",Date)],jt.prototype,"finishedAt",void 0),jt=S([s("ngx-decaf-list-item",{icon:"ti-player-play"}),r("ngx-decaf-crud-form"),f("Persistable graph run lifecycle record"),C("graph_run"),E(),D("design:paramtypes",[Object])],jt);let Gt=class extends T{constructor(e){super(e)}};S([P({type:String,generated:!1}),D("design:type",String)],Gt.prototype,"workflowId",void 0),S([R(),D("design:type",String)],Gt.prototype,"name",void 0),S([R(),D("design:type",Object)],Gt.prototype,"document",void 0),S([R(),D("design:type",String)],Gt.prototype,"owner",void 0),S([R(),D("design:type",Object)],Gt.prototype,"snapshot",void 0),Gt=S([C("graph_workflow"),E(),D("design:paramtypes",[Object])],Gt),oe("Trigger",{color:"#3b82f6",icon:"ti-bolt"}),oe("Flow Control",{color:"#f59e0b",icon:"ti-arrows-split-2"}),oe("Utility",{color:"#0d9488",icon:"ti-tool"}),oe("Loop",{color:"#eab308",icon:"ti-repeat"}),oe("Workflow",{color:"#f97316",icon:"ti-sitemap"}),oe("Pipeline",{color:"#0ea5e9",icon:"ti-git-merge"}),oe("Node",{color:"#8b5cf6",icon:"ti-point-filled"}),oe("Agent",{color:"#7c3aed",icon:"ti-robot"}),oe("model",{color:"#3b82f6",icon:"ti-cpu"}),oe("memory",{color:"#10b981",icon:"ti-database"}),oe("workspace",{color:"#f59e0b",icon:"ti-folder"});const Ut=new Set;function Ft(e,t){return e.config[t]}function Bt(e){return Array.isArray(e)?e.map(e=>e+"").join(", "):e+""}(()=>{const t=[{key:le.NODE_ID,shouldInclude:e=>null!=Ft(e,le.NODE_ID),render:e=>Ft(e,le.NODE_ID)+""},{key:le.WORKFLOW_ID,shouldInclude:e=>null!=Ft(e,le.WORKFLOW_ID),render:e=>Ft(e,le.WORKFLOW_ID)+""},{key:le.RUN_ID,shouldInclude:e=>null!=Ft(e,le.RUN_ID),render:e=>Ft(e,le.RUN_ID)+""},{key:le.USER,shouldInclude:e=>null!=Ft(e,le.USER),render:e=>Ft(e,le.USER)+""},{key:le.ROLES,shouldInclude(e){const t=Ft(e,le.ROLES);return Array.isArray(t)&&t.length>0},render:e=>Bt(Ft(e,le.ROLES))},{key:le.NAMESPACES,shouldInclude(e){const t=Ft(e,le.NAMESPACES);return Array.isArray(t)&&t.length>0},render:e=>Bt(Ft(e,le.NAMESPACES))},{key:le.ORGANIZATION,shouldInclude:e=>null!=Ft(e,le.ORGANIZATION),render:e=>Ft(e,le.ORGANIZATION)+""},{key:le.IP,shouldInclude:e=>null!=Ft(e,le.IP),render:e=>Ft(e,le.IP)+""}];for(const o of t)Ut.has(o.key)||(e.register(o),Ut.add(o.key))})();const Wt="$workflow",qt="local",Ht=4,Kt=100,Vt=1e3,zt=1e3,Jt=1e4,Xt=3e4,Yt="graph.pinnable";var Qt,Zt;(e=>{e.MANUAL="manual",e.AUTOMATIC="automatic",e.DISABLED="disabled"})(Qt||(Qt={})),(e=>{e.TRUTHY="truthy",e.FALSY="falsy",e.EQUALS="equals",e.NOT_EQUALS="notEquals",e.GREATER_THAN="greaterThan",e.GREATER_THAN_OR_EQUAL="greaterThanOrEqual",e.LESS_THAN="lessThan",e.LESS_THAN_OR_EQUAL="lessThanOrEqual",e.EXISTS="exists",e.CUSTOM="custom"})(Zt||(Zt={}));const eo={FOREACH:"core.loop.foreach",WHILE:"core.loop.while",UNTIL:"core.loop.until"};class to extends x{constructor(e,t="GRAPH_EXECUTION_ERROR",o){super(e,to.name,500),this.graphCode=t,this.details=o,this.name=this.constructor.name}}class oo extends to{constructor(e){super("Graph workflow contains an unsupported cycle","GRAPH_CYCLE_ERROR",e)}}class no extends to{constructor(e,t){super(e,"GRAPH_INPUT_ERROR",t)}}class ro extends to{constructor(e,t){super(e,"GRAPH_LOOP_LIMIT_ERROR",t)}}class io extends to{constructor(e,t){super(e,"GRAPH_PINNING_ERROR",t)}}class ao extends to{constructor(e,t){super(e,"GRAPH_PORT_ERROR",t)}}class so extends to{constructor(e,t){super(e,"GRAPH_STORE_ERROR",t)}}class lo extends to{constructor(e,t){super(e,"GRAPH_TOPOLOGY_ERROR",t)}}class co extends to{constructor(e){super("Break signal","GRAPH_BREAK_SIGNAL",{value:e}),this.isBreakSignal=!0,this.name="GraphBreakSignal"}}class uo extends to{constructor(e){super(`Graph run '${e}' was cancelled`,"GRAPH_RUN_CANCELLED",{runId:e}),this.name=uo.name}}class po extends A{constructor(e){super(`Graph workflow document rejected with ${e.length} issue(s): ${e.map(e=>`${e.code} at ${e.path} (${e.message})`).join("; ")}`),this.name=po.name,this.issues=e}}class ho{constructor(){this.observers=new Set}observe(e){return this.observers.add(e),()=>this.unObserve(e)}unObserve(e){this.observers.delete(e)}async updateObservers(e){await Promise.all(Array.from(this.observers).map(async t=>{try{await Promise.resolve(t.refresh(e))}catch{}}))}}class fo{constructor(){this.sequence=0}create(e){return{...e,id:this.createEventId(),sequence:++this.sequence,timestamp:new Date}}createEventId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new to("Cannot generate a graph event id: crypto.randomUUID is unavailable in this runtime","GRAPH_EVENT_ID_ERROR",{runtime:typeof globalThis.crypto});return e.randomUUID()}}function go(e){if("string"!=typeof e)return;const t=e.trim();if(!t)return;const o=t.split(".");if(3!==o.length)return;const n=o[0].trim(),r=o[2].trim(),i=o[1].split(",").map(e=>e.trim()).filter(e=>e.length>0);return n&&r&&0!==i.length?{organization:n,departments:i,role:r}:void 0}function mo(e){return`${e.organization}.${e.departments.join(",")}.${e.role}`}function yo(e){if(!e||"string"!=typeof e.namespace||!e.parts)return!1;const t=go(e.namespace);return!!t&&mo(t)===mo(e.parts)}function wo(e,t){const o="string"==typeof e?e.trim():"";if(o){if(t)for(const e of t)if(e&&e.namespace===o&&yo(e))return e.parts;return go(o)}}function bo(e,t,o={},n){const r=wo(e,n),i=wo(t,n);return!(!r||!i)&&r.organization===i.organization&&r.role===i.role&&("exact"===(o.mode??"inherit")?r.departments.length===i.departments.length&&r.departments.every((e,t)=>e===i.departments[t]):r.departments.length<=i.departments.length&&r.departments.every((e,t)=>e===i.departments[t]))}function vo(e,t,o={},n){return e.filter(e=>!t.some(t=>bo(t,e,o,n)))}function Io(e){return e.filter(e=>void 0===go(e))}function Eo(e,t){const o=new Set;for(const n of e){const e=wo(n,t);e&&o.add(e.role)}return[...o]}function No(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}function Oo(e,t){try{const o=e.cache;if(o&&void 0!==o[t]&&null!==o[t])return o[t]}catch{}try{return e.get(t)}catch{return}}function ko(e){if(!e)return{};const t={},o=e.user;"string"==typeof o&&o&&(t.user=o);const n=e.organization;"string"==typeof n&&n&&(t.organization=n);const r=e.ip;"string"==typeof r&&r&&(t.ip=r);const i=No(e.roles);i&&(t.roles=i);const a=No(e.namespaces);return a&&(t.namespaces=a,t.namespaceCache=xo(a)),t}function Ao(e){return e?ko({user:Oo(e,"user"),organization:Oo(e,"organization"),ip:Oo(e,"ip"),roles:Oo(e,"roles"),namespaces:Oo(e,"namespaces")}):{}}function xo(e){const t=[];for(const o of e){const e=go(o);e&&t.push({namespace:o,parts:e})}return t}function _o(...e){const t={};for(const o of e)o&&(void 0!==o.user&&(t.user=o.user),void 0!==o.organization&&(t.organization=o.organization),void 0!==o.ip&&(t.ip=o.ip),void 0!==o.roles&&(t.roles=o.roles),void 0!==o.namespaces&&(t.namespaces=o.namespaces),void 0!==o.namespaces?t.namespaceCache=o.namespaceCache??xo(o.namespaces):void 0!==o.namespaceCache&&(t.namespaceCache=o.namespaceCache));return t}class So{constructor(e={}){this.options=e}get enabled(){return!0===this.options.enabled}validate(e,o,n,r){if(!this.enabled)return;const i=r??this.options.logger??t.for("GraphAuth"),a=e.id||e.name||o.workflowId,s=(e=>{if(!e||"object"!=typeof e)return;const t=e.auth;return t&&"object"==typeof t&&!Array.isArray(t)?(e=>{if(!e)return;const t=fe(e.namespaces),o=fe(e.roles);if(!t&&!o)return;const n={};return t&&(n.namespaces=t),o&&(n.roles=o),n})(t):void 0})(e.metadata);this.assertGranted(`workflow '${a}'`,s?.namespaces??[],n,s?.roles??[],i);for(const e of o.nodes)this.assertGranted(`node '${e.id}'`,e.manifest.namespaces??[],n,[],i)}assertGranted(e,t,o,n,r){const i=o.namespaces??[],a=vo(t,i,this.options.match,o.namespaceCache),s=Eo(i,o.namespaceCache),d=n.filter(e=>!s.includes(e));if(0===a.length&&0===d.length)return;const l=[...new Set([...Io(t),...Io(i)])],c=[];throw a.length&&c.push("namespace(s) "+a.join(", ")),d.length&&c.push("role(s) "+d.join(", ")),r.warn(`Graph access denied for ${e} for user ${o.user??"anonymous"}: missing ${c.join(" and ")}${l.length?`; malformed namespace(s) ${l.join(", ")} failed closed`:""}`),new L(`Access to ${e} requires ${c.join(" and ")}`)}}class Do{constructor(e){this.baseOptions=e,this.inner=t.for("GraphRun").for(this.attributeConfig(e))}attributeConfig(e){return{[le.NODE_ID]:e.nodeId,[le.WORKFLOW_ID]:e.workflowId,[le.RUN_ID]:e.runId,[le.USER]:e.user??null,[le.ROLES]:e.roles,[le.NAMESPACES]:e.namespaces,[le.ORGANIZATION]:e.organization,[le.IP]:e.ip}}emit(e,t,o){const n="string"==typeof t?t:t instanceof Error?t.message:t+"",r={level:e,message:n,timestamp:(new Date).toISOString(),runId:this.baseOptions.runId,workflowId:this.baseOptions.workflowId,nodeId:this.baseOptions.nodeId,user:this.baseOptions.user??null};void 0!==this.baseOptions.roles&&(r.roles=this.baseOptions.roles),void 0!==this.baseOptions.namespaces&&(r.namespaces=this.baseOptions.namespaces),void 0!==this.baseOptions.organization&&(r.organization=this.baseOptions.organization),void 0!==this.baseOptions.ip&&(r.ip=this.baseOptions.ip),void 0!==o&&(r.payload=o),this.baseOptions.forward({type:ce.GRAPH_RUN_LOG,payload:r}).catch(()=>{}),{benchmark:(e,t)=>this.inner.benchmark(e,t),fatal:(e,t)=>this.inner.fatal(e,t),critical:(e,t)=>this.inner.critical(e,t),silly:(e,t)=>this.inner.silly(e,t),trace:(e,t)=>this.inner.trace(e,t),verbose:(e,t)=>this.inner.verbose(e,t),info:(e,t)=>this.inner.info(e,t),warn:(e,t)=>this.inner.warn(e,t),error:(e,t)=>this.inner.error(e,t),debug:(e,t)=>this.inner.debug(e,t)}[e](n,o)}benchmark(e,t){this.emit("benchmark",e,t)}fatal(e,t,o){this.emit("fatal",e,t??o)}critical(e,t,o){this.emit("critical",e,t??o)}silly(e,t,o){this.emit("silly",e,"object"==typeof t?t:o)}trace(e,t){this.emit("trace",e,t)}verbose(e,t,o){this.emit("verbose",e,"object"==typeof t?t:o)}info(e,t){this.emit("info",e,t)}error(e,t,o){this.emit("error",e,t??o)}warn(e,t){this.emit("warn",e,t)}debug(e,t){this.emit("debug",e,t)}action(e,t,o){this.inner.action(e,t,o)}setConfig(){}for(e,t,...o){return this}clear(){return this}get root(){return this.inner.root}}function Po(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}class Ro extends M{constructor(e,t,o,n,r,i,a,s,d={},l,c,u){super(),this.runId=e,this.parentRunId=t,this.workflowId=o,this.document=n,this.node=r,this.manifest=i,this.path=a,this.emitFn=s,this.metadata=d,this.engine=l,this.abortSignal=c,this.limits=u;const p=ko(d);this.accumulate({...p,operation:"execute"});const h="string"==typeof d?.user?d.user:null;this.runLogger=new Do({runId:e,workflowId:o,nodeId:r.id,user:h,roles:Po(d?.roles),namespaces:Po(d?.namespaces),organization:"string"==typeof d?.organization?d.organization:void 0,ip:"string"==typeof d?.ip?d.ip:void 0,forward:async e=>{await this.emit(e)}})}get logger(){return this.runLogger}get auth(){return Ao(this)}async emit(e){await this.emitFn({...e,runId:this.runId,parentRunId:this.parentRunId,workflowId:this.workflowId,nodeId:this.node.id,path:e.path??this.path})}async progress(e){await this.emit({type:ce.NODE_OUTPUT,payload:e})}async log(e,t){await this.emit({type:ce.NODE_OUTPUT,payload:{message:e,payload:t}})}}class $o{constructor(e,t,o,n){this.nodeResults=new Map,this.events=[],this.activeDataEdges=new Set,this.runId=e,this.plan=t,this.valueStore=o,this.eventFactory=n,this.startedAt=new Date}recordNodeResult(e){this.nodeResults.set(e.nodeId,e)}activateDataEdge(e){this.activeDataEdges.add(e)}isDataEdgeActive(e){return this.activeDataEdges.has(e)}appendEvent(e){this.events.push(e)}finish(){this.finishedAt=new Date}}function Co(e,t,o,n,r){const i=e.valueStore.getWorkflowValues(),a={};for(const[t,o]of e.nodeResults)a[t]=o;const s=[...e.events];return{runId:e.runId,workflowId:t.id||t.name,status:n,document:t,inputs:{...o},outputs:i,nodeResults:a,events:s,startedAt:e.startedAt,finishedAt:e.finishedAt,metadata:r}}class To{constructor(e,t,o){this.emitter=e,this.eventFactory=t,this.options=o}get engine(){return this.options.engine}get codeSandboxEvaluator(){return this.options.codeSandboxEvaluator}get frame(){return this._frame}bindFrame(e){this._frame=e}async emit(e){const t=this.eventFactory.create({id:"",sequence:0,timestamp:new Date,runId:this.options.runId,parentRunId:this.options.parentRunId,workflowId:this.options.workflowId,type:ce.NODE_OUTPUT,path:this.options.path??[],...e});this._frame?.appendEvent(t),await this.emitter.updateObservers(t)}async updateObservers(e){await this.emitter.updateObservers(e)}}function Lo(e){const t=e.capabilities;return{codeMode:t?.codeMode??e.codeMode,workflows:{list:t?.workflows?.list??("function"==typeof e.listWorkflows?"supported":"not_supported"),get:t?.workflows?.get??("function"==typeof e.getWorkflow?"supported":"not_supported")}}}class Mo{static{this._cache={}}static register(e,t){return Mo._cache[e]=t,t}static get(e){const t=e??Mo._currentFlavour;if(t)return Mo._cache[t]}static getOrFail(e){const t=Mo.get(e);if(!t)throw new to(`No graph execution backend registered under '${e}'`,"GRAPH_EXECUTION_BACKEND_NOT_REGISTERED");return t}static get current(){return Mo.get()}static get currentFlavour(){return Mo._currentFlavour??qt}static setCurrent(e){Mo._currentFlavour=e}static list(){return Object.entries(Mo._cache).map(([e,t])=>({flavour:e,backend:t}))}static unregister(e){e&&(delete Mo._cache[e],Mo._currentFlavour===e&&(Mo._currentFlavour=void 0))}static clear(){for(const e of Object.keys(Mo._cache))delete Mo._cache[e];Mo._currentFlavour=void 0}}class jo{evaluate(e,t){switch(e.op){case"eq":return this.resolveValue(e.left,t)===this.resolveValue(e.right,t);case"neq":return this.resolveValue(e.left,t)!==this.resolveValue(e.right,t);case"gt":return Number(this.resolveValue(e.left,t))>Number(this.resolveValue(e.right,t));case"gte":return Number(this.resolveValue(e.left,t))>=Number(this.resolveValue(e.right,t));case"lt":return Number(this.resolveValue(e.left,t))<Number(this.resolveValue(e.right,t));case"lte":return Number(this.resolveValue(e.left,t))<=Number(this.resolveValue(e.right,t));case"and":return e.conditions.every(e=>this.evaluate(e,t));case"or":return e.conditions.some(e=>this.evaluate(e,t));case"not":return!this.evaluate(e.condition,t);case"exists":return void 0!==this.resolveValue(e.value,t)&&null!==this.resolveValue(e.value,t);default:throw new to(`Unknown ConditionExpression op '${e.op}'`,"GRAPH_UNKNOWN_CONDITION_OP",{expr:e})}}resolveValue(e,t){if("const"in e)return e.const;if("path"in e&&!("step"in e))return this.resolvePath(e.path,t);if("step"in e&&"path"in e){const o=t?.nodes;if(o&&"object"==typeof o){const t=o[e.step];return this.resolvePath(e.path,t)}return this.resolvePath(e.path,t)}throw new to("Invalid ExprValue: must have `const`, `path`, or `step`+`path`","GRAPH_INVALID_EXPR_VALUE",{ref:e})}resolvePath(e,t){if(!e)return t;const o=e.split(".");let n=t;for(const e of o){if(null==n)return;n=n[e]}return n}}function Go(e){return"object"==typeof e&&null!==e&&"type"in e&&"code"===e.type}function Uo(e){return"object"==typeof e&&null!==e&&"op"in e&&"string"==typeof e.op}async function Fo(e,t,o){const n=o.engine?.codeSandboxEvaluator;if(!n)throw new to("Code conditions require a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator","GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{code:e.code});await o.log("Evaluating code condition",{language:e.language??"javascript"});const r=o.metadata;return!!await n.evaluate({code:e.code,language:e.language,input:t,vars:r?.vars??void 0,item:r?.item,index:r?.index,nodes:r?.nodes??void 0,logger:o.logger,abortSignal:o.abortSignal})}function Bo(e,t,o){if(Uo(e))return(new jo).evaluate(e,t);throw((e,t)=>new to(`Unknown ${t??"flow"} condition type \u2014 must be ConditionExpression (op) or CodeCondition (type: 'code')`,"GRAPH_UNKNOWN_CONDITION_TYPE",{condition:e}))(e,o)}async function Wo(e,t,o){return Go(e)?Fo(e,t.input,o):Bo(e,t.state,t.label)}function qo(e,t,o,n){if(e&&"object"==typeof e&&!n.has(e))if(n.add(e),Go(e))o.push({nodeId:t,kind:"code-condition"});else if(ut(e))o.push({nodeId:t,kind:"value-template"});else if((e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"expression"===t.source&&"string"==typeof t.expression})(e))o.push({nodeId:t,kind:"expression-binding"});else if((e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.name&&Array.isArray(t.nodes)&&Array.isArray(t.edges)})(e))Ko(e,o,n);else if(Array.isArray(e))for(const r of e)qo(r,t,o,n);else for(const r of Object.keys(e))qo(e[r],t,o,n)}function Ho(e,t,o){const n=e.id;"core.utility.code"===e.kind&&t.push({nodeId:n,kind:"code-node",detail:e.kind});const r=e.inputBindings??{};for(const[e,o]of Object.entries(r))o&&"expression"===o.mode&&t.push({nodeId:n,kind:"expression-binding",detail:e});qo(e.parameters,n,t,o),qo(e.metadata,n,t,o),qo(e.state,n,t,o),qo(e.loop,n,t,o)}function Ko(e,t,o){for(const n of e.nodes??[])Ho(n,t,o)}function Vo(e){const t=[];return Ko(e,t,new Set),t}function zo(e){return Vo(e).length>0}function Jo(e,t){if(!t)return{valid:!0};switch(t.type){case"any":default:return{valid:!0};case"string":return"string"!=typeof e?Xo("string"):{valid:!0};case"number":return"number"==typeof e&&Number.isFinite(e)?t.integer&&!Number.isInteger(e)?{valid:!1,message:"expected an integer number"}:void 0!==t.min&&e<t.min?{valid:!1,message:"expected a number >= "+t.min}:void 0!==t.max&&e>t.max?{valid:!1,message:"expected a number <= "+t.max}:{valid:!0}:Xo("number");case"boolean":return"boolean"!=typeof e?Xo("boolean"):{valid:!0};case"array":if(!Array.isArray(e))return Xo("array");if(void 0!==t.minItems&&e.length<t.minItems)return{valid:!1,message:`expected at least ${t.minItems} items`};if(void 0!==t.maxItems&&e.length>t.maxItems)return{valid:!1,message:`expected at most ${t.maxItems} items`};for(const o of e){const e=Jo(o,t.items);if(!e.valid)return e}return{valid:!0};case"object":case"model":{if(null===e||"object"!=typeof e||Array.isArray(e))return Xo(t.type);const o=t,n=o.properties;if(!n)return{valid:!0};for(const[t,o]of Object.entries(n))if(t in e){const n=Jo(e[t],o);if(!n.valid)return{valid:!1,message:`property '${t}': ${n.message}`}}if(o.required)for(const t of o.required)if(!(t in e))return{valid:!1,message:`missing required property '${t}'`};if(!1===o.additionalProperties)for(const t of Object.keys(e))if(!(t in n))return{valid:!1,message:`unexpected property '${t}'`};return{valid:!0}}case"enum":return t.values.some(t=>t===e)?{valid:!0}:{valid:!1,message:"value is not one of the enum values"}}}function Xo(e){return{valid:!1,message:`expected a ${e} value`}}function Yo(e){if("string"==typeof e)return e.length>0;if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.credentialId&&t.credentialId.length>0&&(void 0===t.credentialType||"string"==typeof t.credentialType)}const Qo=new Set(["loop"]),Zo=["secret","secrets","password","passwd","token","accessToken","refreshToken","apiKey","api_key","privateKey","credentials"];class en{validate(e,t,o,n,r){this.validateParameters(e,t,o,n,r),this.validateMetadataKeys(e,t,o,n),this.validateDisabledBehavior(e,o,n),this.validateBindingShapes(e,t,o,n)}validateParameters(e,t,o,n,r){const i=!0===t.policies?.allowUndeclaredParameters,a=new Map(t.parameters.map(e=>[e.id,e]));for(const[r,s]of Object.entries(e.parameters??{})){const d=a.get(r);if(!d){i||o.push({code:"parameter.undeclared",path:`${n}.parameters.${r}`,message:`Node '${e.id}' sets parameter '${r}' which is not declared by kind '${t.kind}'`,nodeId:e.id,details:{kind:t.kind}});continue}if(void 0===s){o.push({code:"parameter.invalid",path:`${n}.parameters.${r}`,message:`Node '${e.id}' parameter '${r}' must not be undefined`,nodeId:e.id});continue}const l=this.checkParameterValue(s,d);l.valid||o.push({code:"parameter.type-mismatch",path:`${n}.parameters.${r}`,message:`Node '${e.id}' parameter '${r}' is invalid: ${l.message}`,nodeId:e.id,details:{expectedType:d.type}})}for(const i of t.parameters)void 0===(e.parameters??{})[i.id]&&(this.isParameterSatisfiedByInput(e,i.id,r)||(!0===i.required||(i.validation??[]).some(e=>"required"===e.kind))&&void 0===i.defaultValue&&o.push({code:"parameter.required-missing",path:`${n}.parameters.${i.id}`,message:`Node '${e.id}' is missing required parameter '${i.id}' declared by kind '${t.kind}'`,nodeId:e.id}))}isParameterSatisfiedByInput(e,t,o){return void 0!==(e.inputBindings??{})[t]||!0===o?.has(t)}checkParameterValue(e,t){if(ut(e))return{valid:!0};switch(t.type){case"string":case"code":case"expression":return"string"!=typeof e?Xo("string"):{valid:!0};case"number":return"number"==typeof e&&Number.isFinite(e)?{valid:!0}:Xo("number");case"boolean":return"boolean"!=typeof e?Xo("boolean"):{valid:!0};case"options":{const o=t.options;return o&&o.length&&!o.some(t=>t.value===e)?{valid:!1,message:"value is not one of the declared options"}:{valid:!0}}case"collection":return Array.isArray(e)?{valid:!0}:Xo("array");case"object":case"resourceLocator":return null===e||"object"!=typeof e||Array.isArray(e)?Xo("object"):{valid:!0};case"credential":return Yo(e)?t.credentialType&&"object"==typeof e&&void 0!==e.credentialType&&e.credentialType!==t.credentialType?{valid:!1,message:`credential type '${e.credentialType}' does not match the declared type '${t.credentialType}'`}:{valid:!0}:{valid:!1,message:"credential parameters must hold a credential reference (credentialId), never a secret"};default:return{valid:!0}}}validateMetadataKeys(e,t,o,n){const r=t.metadata?.allowedInstanceMetadataKeys;for(const i of Object.keys(e.metadata??{}))Qo.has(i)?o.push({code:"metadata.key-not-allowed",path:`${n}.metadata.${i}`,message:`Node '${e.id}' metadata key '${i}' is reserved and must not be set directly`,nodeId:e.id}):Array.isArray(r)&&!r.includes(i)&&o.push({code:"metadata.key-not-allowed",path:`${n}.metadata.${i}`,message:`Node '${e.id}' metadata key '${i}' is not in the allowed metadata keys of kind '${t.kind}'`,nodeId:e.id})}validateDisabledBehavior(e,t,o){!0!==e.disabled&&!1!==e.disabled&&void 0!==e.disabled&&t.push({code:"disabled.invalid",path:o+".disabled",message:`Node '${e.id}' disabled flag must be a boolean`,nodeId:e.id});const n=(e.metadata??{}).disabledBehavior;void 0===n||ae(n)||t.push({code:"disabled.invalid-behavior",path:o+".metadata.disabledBehavior",message:`Node '${e.id}' disabled behavior '${n+""}' is not one of: ${ie.join(", ")}`,nodeId:e.id})}validateBindingShapes(e,t,o,n){for(const[r,i]of Object.entries(e.inputBindings??{})){if("literal"===i.mode){const a=t.inputs.find(e=>e.id===r);if(a?.schema){const t=Jo(i.value,a.schema);t.valid||o.push({code:"binding.literal-invalid",path:`${n}.inputBindings.${r}`,message:`Node '${e.id}' literal binding for '${r}' is schema-invalid: ${t.message}`,nodeId:e.id})}}"expression"!==i.mode||"string"==typeof i.expression&&i.expression.trim()||o.push({code:"binding.expression-invalid",path:`${n}.inputBindings.${r}`,message:`Node '${e.id}' expression binding for '${r}' must contain a non-empty expression`,nodeId:e.id})}}validateBindingSatisfaction(e,t,o,n,r,i={}){const a=new Set(o.filter(e=>"data"===e.type).map(e=>e.targetPort)),s=new Set(Object.entries(e.inputBindings??{}).map(([e])=>e));for(const t of a){const o=(e.inputBindings??{})[t];o&&"literal"===o.mode&&!0!==i.allowLiteralAndEdgeBindings&&n.push({code:"binding.conflict",path:`${r}.inputBindings.${t}`,message:`Node '${e.id}' input '${t}' has both an incoming edge and a literal binding`,nodeId:e.id})}for(const o of t.inputs)!0===o.required&&(a.has(o.id)||s.has(o.id)||void 0===(e.parameters??{})[o.id]&&n.push({code:"topology.required-input-unsatisfiable",path:r+".parameters",message:`Node '${e.id}' required input '${o.id}' has no incoming edge or binding`,nodeId:e.id,details:{port:o.id}}))}static disabledBehaviorOf(e,t){const o=(e.metadata??{}).disabledBehavior;if(ae(o))return o;const n=t?.disabledBehavior;return ae(n)?n:"skip"}}let tn=class extends T{constructor(e){super(e)}};function on(e){return[e.namespace??"default",e.workflowId,e.nodeId,e.version??"default",e.fingerprint].join(":")}function nn(e){return new tn({id:on(e.key),workflowId:e.key.workflowId,nodeId:e.key.nodeId,fingerprint:e.key.fingerprint,...void 0!==e.key.namespace?{namespace:e.key.namespace}:{},...void 0!==e.key.version?{version:e.key.version}:{},pinned:e.pinned,outputs:e.outputs,createdAt:new Date(e.createdAt),updatedAt:new Date(e.updatedAt),...e.expiresAt?{expiresAt:new Date(e.expiresAt)}:{},...e.metadata?{metadata:e.metadata}:{}})}function rn(e){return{key:{workflowId:e.workflowId,nodeId:e.nodeId,fingerprint:e.fingerprint,...void 0!==e.namespace?{namespace:e.namespace}:{},...void 0!==e.version?{version:e.version}:{}},outputs:e.outputs,pinned:e.pinned,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString(),...e.expiresAt?{expiresAt:e.expiresAt.toISOString()}:{},...e.metadata?{metadata:e.metadata}:{}}}S([P({type:String,generated:!1}),D("design:type",String)],tn.prototype,"id",void 0),S([R(),$(),D("design:type",String)],tn.prototype,"workflowId",void 0),S([R(),$(),D("design:type",String)],tn.prototype,"nodeId",void 0),S([R(),D("design:type",String)],tn.prototype,"fingerprint",void 0),S([R(),D("design:type",String)],tn.prototype,"namespace",void 0),S([R(),D("design:type",String)],tn.prototype,"version",void 0),S([R(),D("design:type",Boolean)],tn.prototype,"pinned",void 0),S([R(),D("design:type",Object)],tn.prototype,"outputs",void 0),S([R(),D("design:type",Date)],tn.prototype,"createdAt",void 0),S([R(),D("design:type",Date)],tn.prototype,"updatedAt",void 0),S([R(),D("design:type",Date)],tn.prototype,"expiresAt",void 0),S([R(),D("design:type",Object)],tn.prototype,"metadata",void 0),tn=S([C("graph_value"),E(),D("design:paramtypes",[Object])],tn);let an=class extends G{constructor(e){super(e,tn,!0),this.runtimeValues=new Map}seedWorkflowInputs(e){this.runtimeValues.set(Wt,{...e})}setNodeOutputs(e,t){this.runtimeValues.set(e,{...t})}getPort(e,t){return this.runtimeValues.get(e)?.[t]}hasPort(e,t){return Object.prototype.hasOwnProperty.call(this.runtimeValues.get(e)??{},t)}setWorkflowOutput(e,t){const o=this.runtimeValues.get(Wt)??{};o[e]=t,this.runtimeValues.set(Wt,o)}getWorkflowValues(){return{...this.runtimeValues.get(Wt)??{}}}snapshot(){return Object.fromEntries(this.runtimeValues.entries())}async readCached(e,...t){try{return rn(await this.read(on(e),...t))}catch{return}}async writeCached(e,t,...o){const n=on(e);let r;try{r=await this.read(n,...o)}catch{r=void 0}r?await this.update(Object.assign(r,nn(t)),...o):await this.create(nn(t),...o)}async deleteCached(e,...t){try{await this.delete(on(e),...t)}catch{}}async hasCached(e,...t){return void 0!==await this.readCached(e,...t)}async listCached(e,...t){return(await this.select().execute(...t)).map(e=>rn(e)).filter(t=>((e,t)=>!(void 0!==t.workflowId&&e.workflowId!==t.workflowId||void 0!==t.nodeId&&e.nodeId!==t.nodeId||void 0!==t.namespace&&e.namespace!==t.namespace||void 0!==t.version&&e.version!==t.version||void 0!==t.fingerprint&&e.fingerprint!==t.fingerprint))(t.key,e))}async clearRun(e,...t){const o=await this.select().execute(...t);for(const e of o)await this.delete(e.id,...t)}readRuntimeValues(e){return this.runtimeValues.get(e)}writeRuntimeValues(e,t){this.runtimeValues.set(e,{...t})}getAdapter(){return this.adapter}};function sn(e){return new(0,G.forModel(tn,e.alias).constructor)(e)}an=S([j(tn,m),D("design:paramtypes",[Function])],an);class dn{static upstreamNodes(e,t,o=!1){const n=new Set,r=[e];for(;r.length;){const e=r.pop(),i=t.get(e)??[];for(const e of i)!o&&this.isBoundary(e.sourceNodeId)||n.has(e.sourceNodeId)||(n.add(e.sourceNodeId),r.push(e.sourceNodeId))}return n}static downstreamNodes(e,t,o=!1){const n=new Set,r=[e];for(;r.length;){const e=r.pop(),i=t.get(e)??[];for(const e of i)!o&&this.isBoundary(e.targetNodeId)||n.has(e.targetNodeId)||(n.add(e.targetNodeId),r.push(e.targetNodeId))}return n}static isBoundary(e){return"$workflow"===e}}class ln{constructor(e,t,o){this.store=e,this.policy=t,this.dependencyResolver=o}async pinNode(e){const t=e.plan,o=e.includeDependencies??!0?this.dependencyResolver.getPinSet(t,e.nodeId):new Set([e.nodeId]);for(const e of o){const o=t.nodes.find(t=>t.id===e);if(!o)throw new io(`Node '${e}' not found in plan`);if(!this.policy.canPin(o))throw new io(`Node '${e}' is not pinnable`,{nodeId:e})}const n=this.topologicalOrder(t,o);for(const o of n){const n=t.nodes.find(e=>e.id===o),r=e.result.nodeResults[o];if(!r||!r.outputs)throw new io(`Node '${o}' has no completed output to pin`);const i=r.inputs??{},a=this.dependencyFingerprints(t,o,e.result),s=this.createValueKey(e.document.id,n,i,a),d=(new Date).toISOString(),l={key:s,outputs:r.outputs,pinned:!0,createdAt:d,updatedAt:d,metadata:{...e.result.metadata,nodeId:o}};await this.store.writeCached(s,l)}}async unpinNode(e){const t={workflowId:e.document.id,nodeId:e.nodeId,fingerprint:e.fingerprint,namespace:e.namespace};await this.store.deleteCached(t)}async readPinnedValue(e,t,o,n,r){const i=this.createValueKey(e,t,o,n,r),a=await this.store.readCached(i);if(a&&a.pinned){if(a.expiresAt&&new Date(a.expiresAt)<new Date)return;return a}}createValueKey(e,t,o,n,r){return{workflowId:e,nodeId:t.id,fingerprint:this.computeFingerprint(e,t,o,n),namespace:r}}computeFingerprint(e,t,o,n){const r={workflowId:e,nodeId:t.id,nodeKind:t.kind,parameters:this.stableSerialize(t.instance.parameters??{}),inputBindings:this.stableSerialize(t.instance.inputBindings??{}),metadata:this.stableSerialize(this.relevantMetadata(t)),inputs:this.stableSerialize(o),dependencyFingerprints:this.stableSerialize(n)},i=this.stableSerialize(r);return this.simpleHash(i)}relevantMetadata(e){const t={...e.metadata??{}};return delete t.ui,delete t.position,delete t.visual,t}topologicalOrder(e,t){const o=[],n=new Set,r=i=>{if(n.has(i))return;n.add(i);const a=dn.upstreamNodes(i,e.incomingByNode,!1);for(const e of a)t.has(e)&&r(e);o.push(i)};for(const e of t)r(e);return o}dependencyFingerprints(e,t,o){const n=this.dependencyResolver.getDependencies(e,t),r={};for(const t of n){const n=e.nodes.find(e=>e.id===t);if(n){const i=o.nodeResults[t],a=i?.inputs??{},s=this.dependencyFingerprints(e,t,o);r[t]=this.computeFingerprint(e.workflowId,n,a,s)}}return r}stableSerialize(e){return null===e||"object"!=typeof e?JSON.stringify(e):Array.isArray(e)?`[${e.map(e=>this.stableSerialize(e)).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${this.stableSerialize(e[t])}`).join(",")}}`}simpleHash(e){let t=0;for(let o=0;o<e.length;o++)t=(t<<5)-t+e.charCodeAt(o),t|=0;return`fp_${Math.abs(t).toString(16).padStart(8,"0")}_${e.length}`}}const cn={enabled:!0,strategy:"manual",includeDependencies:!0};function un(e){return!0===e?.enabled&&"disabled"!==e.strategy}class pn{canPin(e){return un(this.getPinningMetadata(e))}shouldUsePinnedValue(e){const t=this.getPinningMetadata(e);return!0===t.enabled&&"disabled"!==t.strategy}shouldAutoPin(e){const t=this.getPinningMetadata(e);return!0===t.enabled&&"automatic"===t.strategy}getPinningMetadata(e){const t=e.manifest.metadata?.pinnable??e.metadata?.pinnable;return t?{...cn,...t}:{...cn,enabled:!1}}}class hn{getDependencies(e,t){return dn.upstreamNodes(t,e.incomingByNode,!1)}getPinSet(e,t){const o=this.getDependencies(e,t);return o.add(t),o}}class fn{constructor(){this.local=!0,this.codeMode="hostSide",Mo.register(qt,this)}async initialize(e){this.valueAdapter=e.valueAdapter,this.codeSandboxEvaluator=e.codeSandboxEvaluator,this.workflowStore=e.workflowStore,this.engine=e.engine}get capabilities(){const e=this.workflowStore?"supported":"not_supported";return{codeMode:this.codeMode,workflows:{list:e,get:e}}}async listWorkflows(...e){const t=this.workflowStore;if(!t)throw new to("LocalGraphExecutionBackend has no workflowStore configured; workflow listing is not supported","GRAPH_BACKEND_WORKFLOWS_NOT_SUPPORTED");return(await t.listWorkflows(...e)).map(e=>({id:e.workflowId,...void 0!==e.name?{name:e.name}:{},...void 0!==e.updatedAt&&null!==e.updatedAt?{updatedAt:e.updatedAt}:{}}))}async getWorkflow(e,...t){const o=this.workflowStore;if(!o)throw new to("LocalGraphExecutionBackend has no workflowStore configured; workflow lookup is not supported","GRAPH_BACKEND_WORKFLOWS_NOT_SUPPORTED");return await o.getDocument(e,...t)}async execute(e){const{document:t,plan:o,inputs:n,options:r,events:i}=e,a=i,s=a.frame;if(!s)throw new to("LocalGraphExecutionBackend requires the frame-bound event sink created by GraphExecutionEngine","GRAPH_EXECUTION_FRAME_MISSING");const d=s.valueStore,l=s.runId,c=r.path??[],u=async e=>{await a.emit(e)};try{for(const e of o.layers)this.assertNotAborted(r),await this.executeLayer(s,o,e.nodes,r,u);this.assertNotAborted(r);const e=[...s.nodeResults.values()].find(e=>e.status===se.FAILED);if(e?.error)throw new to(e.error.message,e.error.code??"GRAPH_EXECUTION_ERROR",e.error.details);return s.finish(),await a.emit({type:ce.WORKFLOW_COMPLETED,runId:l,parentRunId:r.parentRunId,workflowId:o.workflowId,path:c,status:se.SUCCEEDED,payload:{outputs:d.getWorkflowValues()}}),Co(s,t,n,se.SUCCEEDED,r.metadata)}catch(e){if(e instanceof co)throw s.finish(),e;s.finish();const i=this.toErrorPayload(e);return e instanceof uo||!0===r.abortSignal?.aborted?(await a.emit({type:ce.WORKFLOW_CANCELLED,runId:l,parentRunId:r.parentRunId,workflowId:o.workflowId,path:c,status:se.CANCELLED,error:i}),Co(s,t,n,se.CANCELLED,r.metadata)):(await a.emit({type:ce.WORKFLOW_FAILED,runId:l,parentRunId:r.parentRunId,workflowId:o.workflowId,path:c,status:se.FAILED,error:i}),Co(s,t,n,se.FAILED,r.metadata))}}async executeLayer(e,t,o,n,r){const i=Math.max(1,n.concurrency??4),a=[...o];for(;a.length>0;){const o=a.splice(0,i);await Promise.all(o.map(o=>this.executeNode(e,t,o,n,r)))}}async executeNode(e,t,o,n,r){if(this.assertNotAborted(n),!this.isNodeActivated(e,t,o))return void await this.skipInactiveNode(e,t,o,n,r);if(!0===o.instance.disabled)return void await this.executeDisabledNode(e,t,o,n,r);const i=new Date,a=[...n.path??[],o.id];await r({type:ce.NODE_STARTED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.RUNNING}),this.emitNodeStateChanged(e,t,o,a,de.RUNNING,se.RUNNING,r);const s=await this.resolveNodeInputs(e,t,o,n);if(n.usePinnedValues){const n=await this.tryPinnedValue(e,t,o,s);if(n){e.valueStore.setNodeOutputs(o.id,n.outputs),this.routeOutgoingEdges(e,t,o,n.outputs,r);const d=new Date,l={nodeId:o.id,status:se.CACHED,inputs:s,outputs:n.outputs,startedAt:i,finishedAt:d,fromCache:!0,pinned:!0,events:[]};return e.recordNodeResult(l),await r({type:ce.NODE_CACHE_HIT,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.CACHED,payload:{outputs:n.outputs}}),await r({type:ce.NODE_COMPLETED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.SUCCEEDED,payload:{outputs:n.outputs,fromCache:!0}}),void this.emitNodeStateChanged(e,t,o,a,de.SUCCEEDED,se.SUCCEEDED,r)}}try{const d=new Ro(e.runId,n.parentRunId,t.workflowId,t.resolved.document,o.instance,o.manifest,a,r,n.metadata,this.engine,n.abortSignal,this.executionLimits(n)),l=await this.resolveNodeParameters(o,s,n),c={nodeId:o.id,kind:o.kind,inputs:s,parameters:l,credentials:this.collectCredentials(o),metadata:o.instance.metadata},u=await this.invokeExecutor(o,c,d),p=this.validateNodeOutputs(o,u??{});e.valueStore.setNodeOutputs(o.id,p),this.routeOutgoingEdges(e,t,o,p,r);const h=new Date,f={nodeId:o.id,status:se.SUCCEEDED,inputs:s,outputs:p,startedAt:i,finishedAt:h,events:[]};e.recordNodeResult(f),await r({type:ce.NODE_COMPLETED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.SUCCEEDED,payload:{outputs:p}}),this.emitNodeStateChanged(e,t,o,a,de.SUCCEEDED,se.SUCCEEDED,r)}catch(d){if(d instanceof co)throw d;const l=new Date,c=this.toErrorPayload(d),u={nodeId:o.id,status:se.FAILED,inputs:s,error:c,startedAt:i,finishedAt:l,events:[]};if(e.recordNodeResult(u),await r({type:ce.NODE_FAILED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.FAILED,error:c}),this.emitNodeStateChanged(e,t,o,a,de.FAILED,se.FAILED,r),n.failFast??!0)throw d}}isNodeActivated(e,t,o){const n=(t.incomingByNode.get(o.id)??[]).filter(e=>"data"===e.type);return 0===n.length||n.some(t=>t.sourceNodeId===Wt||e.isDataEdgeActive(t.id))}async skipInactiveNode(e,t,o,n,r){const i=new Date,a=[...n.path??[],o.id];await r({type:ce.NODE_SKIPPED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.SKIPPED,payload:{reason:"branchNotSelected"}});const s={nodeId:o.id,status:se.SKIPPED,inputs:{},startedAt:i,finishedAt:new Date,events:[]};e.recordNodeResult(s),this.emitNodeStateChanged(e,t,o,a,de.SKIPPED,se.SKIPPED,r)}async executeDisabledNode(e,t,o,n,r){const i=new Date,a=[...n.path??[],o.id],s=en.disabledBehaviorOf(o.instance,t.resolved.document.settings);if(await r({type:ce.NODE_SKIPPED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.SKIPPED,payload:{disabled:!0,behavior:s}}),"skip"===s){const n={nodeId:o.id,status:se.SKIPPED,inputs:{},startedAt:i,finishedAt:new Date,events:[]};return e.recordNodeResult(n),void this.emitNodeStateChanged(e,t,o,a,de.SKIPPED,se.SKIPPED,r)}const d=await this.resolveNodeInputs(e,t,o,n);let l;if("passThroughFirstInput"===s){const n=(t.incomingByNode.get(o.id)??[]).find(e=>"data"===e.type),r=o.manifest.outputs[0]?.id??"value",i=n?e.valueStore.getPort(n.sourceNodeId,n.sourcePort):Object.values(d)[0];l={[r]:i}}else{l={};for(const e of o.manifest.outputs)l[e.id]=e.metadata?.defaultValue}e.valueStore.setNodeOutputs(o.id,l),this.routeOutgoingEdges(e,t,o,l,r);const c={nodeId:o.id,status:se.SUCCEEDED,inputs:d,outputs:l,startedAt:i,finishedAt:new Date,events:[]};e.recordNodeResult(c),this.emitNodeStateChanged(e,t,o,a,de.SUCCEEDED,se.SUCCEEDED,r)}async invokeExecutor(e,t,o){return await e.executor.execute(t,o)}validateNodeOutputs(e,t){const o=e.manifest;if(!0===o.policies?.allowUnknownOutputs)return t;const n=new Set(o.outputs.map(e=>e.id)),r=Object.keys(t).filter(e=>!n.has(e));if(r.length>0)throw new to(`Node '${e.id}' of kind '${e.kind}' produced unknown output(s): ${r.join(", ")}`,"GRAPH_OUTPUT_VALIDATION_FAILED",{nodeId:e.id,unknownOutputs:r});const i=o.outputs.filter(e=>!0===e.required&&!(e.id in t)).map(e=>e.id);if(i.length>0)throw new to(`Node '${e.id}' of kind '${e.kind}' did not produce required output(s): ${i.join(", ")}`,"GRAPH_OUTPUT_VALIDATION_FAILED",{nodeId:e.id,missingRequired:i});return t}collectCredentials(e){const t={};for(const o of e.manifest.parameters){if("credential"!==o.type)continue;const n=(e.instance.parameters??{})[o.id];"string"==typeof n&&n.length>0?t[o.id]={credentialId:n,credentialType:o.credentialType??""}:Yo(n)&&(t[o.id]={credentialId:n.credentialId,credentialType:n.credentialType})}const o=(e.instance.metadata??{}).credentials;if(o&&"object"==typeof o&&!Array.isArray(o))for(const[e,n]of Object.entries(o)){const o=n;"string"==typeof o&&o.length>0?t[e]={credentialId:o,credentialType:""}:Yo(o)&&(t[e]={credentialId:o.credentialId,credentialType:o.credentialType})}return t}async resolveNodeInputs(e,t,o,n){const r={},i=(t.incomingByNode.get(o.id)??[]).filter(e=>"data"===e.type),a=new Map;for(const e of i){const t=a.get(e.targetPort)??[];t.push(e),a.set(e.targetPort,t)}for(const[t,o]of a)if(1===o.length)r[t]=e.valueStore.getPort(o[0].sourceNodeId,o[0].sourcePort);else{let n,i=!1;for(const t of o){const o=e.valueStore.getPort(t.sourceNodeId,t.sourcePort);r[t.sourcePort]=o,void 0!==o&&(n=o,i=!0)}i&&void 0===r[t]&&(r[t]=n)}const s=o.instance.inputBindings??{};for(const e of o.manifest.inputs){const t=s[e.id];if("literal"===t?.mode)r[e.id]=t.value;else if("expression"===t?.mode)r[e.id]=await this.evaluateExpressionBinding(o,t.expression,r,n);else if(void 0===r[e.id]){const t=e.metadata?.defaultValue;void 0!==t&&(r[e.id]=t)}}return r}async resolveNodeParameters(e,t,o){const n=e.instance.parameters??{},r={};for(const[i,a]of Object.entries(n))r[i]=ut(a)?await this.evaluateValueTemplate(a,e,t,o):a;return r}async evaluateValueTemplate(e,t,o,n){const r=this.codeSandboxEvaluator;if(!r)throw new to(`Value template on node '${t.id}' requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator`,"GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{nodeId:t.id});const i=e.language??("expression"===e.mode?"javascript":"text"),a="template"===e.mode?(e=>`\`${e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\{\{\s*([\s\S]*?)\s*\}\}/g,(e,t)=>`\${${t}}`)}\``)(e.expression):e.expression,s=n.metadata;return await r.evaluate({code:a,language:"typescript"===i?"typescript":"javascript",input:o,vars:s?.vars??void 0,item:s?.item,index:s?.index,abortSignal:n.abortSignal})}async evaluateExpressionBinding(e,t,o,n){const r=this.codeSandboxEvaluator;if(!r)throw new to(`Expression binding on node '${e.id}' requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator`,"GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{nodeId:e.id,expression:t});const i=n.metadata;return await r.evaluate({code:t,language:"javascript",input:o,vars:i?.vars??void 0,item:i?.item,index:i?.index,abortSignal:n.abortSignal})}async tryPinnedValue(e,t,o,n){if(!(new pn).shouldUsePinnedValue(o))return;const r=this.createPinningService(e),i=this.computeDependencyFingerprints(e,t,o.id);return r.readPinnedValue(t.workflowId,o,n,i)}computeDependencyFingerprints(e,t,o){const n=this.createPinningService(e),r=(new hn).getDependencies(t,o),i={};for(const o of r){const r=t.nodes.find(e=>e.id===o);if(r){const a=e.nodeResults.get(o),s=a?.inputs??{},d=this.computeDependencyFingerprints(e,t,o);i[o]=n.computeFingerprint(t.workflowId,r,s,d)}}return i}routeOutgoingEdges(e,t,o,n,r){const i=(t.outgoingByNode.get(o.id)??[]).filter(e=>"data"===e.type);for(const a of i){if(!Object.prototype.hasOwnProperty.call(n,a.sourcePort))continue;const i=n[a.sourcePort];e.activateDataEdge(a.id),a.targetNodeId===Wt&&e.valueStore.setWorkflowOutput(a.targetPort,i),this.emitEdgeStateChanged(e,t,o,a,de.SUCCEEDED,se.SUCCEEDED,r),r({type:ce.EDGE_VALUE_ROUTED,runId:e.runId,workflowId:t.workflowId,edgeId:a.id,nodeId:o.id,path:[],payload:{edge:a,value:i}}).catch(()=>{})}}emitNodeStateChanged(e,t,o,n,r,i,a){a({type:ce.NODE_STATE_CHANGED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:n,status:i,payload:{nodeId:o.id,state:r,runId:e.runId,workflowId:t.workflowId,status:i}}).catch(()=>{})}emitEdgeStateChanged(e,t,o,n,r,i,a){a({type:ce.EDGE_STATE_CHANGED,runId:e.runId,workflowId:t.workflowId,edgeId:n.id,nodeId:o.id,path:[],status:i,payload:{edgeId:n.id,state:r,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,status:i}}).catch(()=>{})}createPinningService(e){const t=sn(e.valueStore.getAdapter()??this.valueAdapter);return new ln(t,new pn,new hn)}executionLimits(e){return{maxLoopIterations:e.maxLoopIterations??zt,maxForeachIterations:e.maxForeachIterations??Jt}}assertNotAborted(e){if(!0===e.abortSignal?.aborted)throw new uo(e.runId??"unknown")}toErrorPayload(e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack,code:e.graphCode??("number"==typeof e.code?e.code+"":e.code)}:{name:"UnknownError",message:e+""}}}class gn{constructor(e){this.catalogue=e}async resolveNodes(e,t,o,...n){const r=new Map;for(const[i,a]of e.entries()){const e=`nodes[${i}]`;if(this.catalogue.has(a.kind,...n))try{const e=await this.catalogue.resolveManifest(a.kind,a,o,...n),t=this.catalogue.getExecutor(a.kind,...n);r.set(a.id,{instance:a,manifest:e,executor:t})}catch(o){t.push({code:"kind.resolution-failed",path:e+".kind",message:`Node '${a.id}' kind '${a.kind}' failed to resolve: ${o.message}`,nodeId:a.id,details:{kind:a.kind}})}else t.push({code:"kind.unknown",path:e+".kind",message:`Node '${a.id}' references kind '${a.kind}' which is not registered in the backend catalogue`,nodeId:a.id,details:{kind:a.kind}})}return r}validateEffectivePorts(e,t,o,n){const r=!0===t.policies?.allowUndeclaredParameters,i=new Set(t.inputs.map(e=>e.id)),a=new Set(t.outputs.map(e=>e.id));for(const a of Object.keys(e.inputBindings??{}))r||i.has(a)||o.push({code:"binding.unknown-port",path:`${n}.inputBindings.${a}`,message:`Node '${e.id}' input binding '${a}' does not refer to an effective input port of kind '${t.kind}'`,nodeId:e.id,details:{effectiveInputs:[...i]}});for(const i of Object.keys(e.outputBindings??{}))r||a.has(i)||o.push({code:"binding.unknown-port",path:`${n}.outputBindings.${i}`,message:`Node '${e.id}' output binding '${i}' does not refer to an effective output port of kind '${t.kind}'`,nodeId:e.id,details:{effectiveOutputs:[...a]}})}}function mn(e,t,o="$"){const n=new Set;for(const t of e.edges)"node"===t.source.scope&&n.add(t.source.nodeId),"node"===t.target.scope&&n.add(t.target.nodeId);for(const r of e.nodes){n.has(r.id)||t.push({code:"topology.loose-node",path:`${o}.nodes[${r.id}]`,message:`Node '${r.id}' is connected to nothing; every node must participate in at least one edge`,nodeId:r.id});const e=r.loop?.body;e&&mn(e,t,`${o}.nodes[${r.id}].loop.body`)}}class yn{resolveEdges(e,t,o){const n=new Set(e.inputs.map(e=>e.id)),r=new Set(e.outputs.map(e=>e.id)),i=[];for(const[a,s]of(e.edges??[]).entries()){const e=`edges[${a}]`,d=this.resolveEndpoint(s,"source",t,n,r,o,e),l=this.resolveEndpoint(s,"target",t,n,r,o,e);if(!d||!l)continue;if(!this.validateDirectionAndType(s,d,l,t,o,e))continue;const c={id:s.id,type:s.type,sourceNodeId:d.nodeId,sourcePort:d.port,targetNodeId:l.nodeId,targetPort:l.port,metadata:s.metadata,edge:s};void 0!==s.label&&(c.label=s.label),i.push(c)}return i}resolveEndpoint(e,t,o,n,r,i,a){const s=e[t];return Xe(s)?("source"===t?n.has(s.port):r.has(s.port))?{nodeId:Wt,port:s.port}:void i.push({code:"edge.unknown-port",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} references workflow port '${s.port}' which is not declared on the document boundary`,edgeId:e.id,details:{scope:"workflow",port:s.port}}):Ye(s)?o.get(s.nodeId)?{nodeId:s.nodeId,port:s.port}:void i.push({code:"edge.unknown-node",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} references node '${s.nodeId}' which is not part of the document or did not resolve`,edgeId:e.id,nodeId:s.nodeId}):void i.push({code:"edge.invalid-endpoint",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} endpoint is not a valid GraphEndpoint`,edgeId:e.id})}validateDirectionAndType(e,t,o,n,r,i){let a=!0;const s=t.nodeId===Wt?void 0:n.get(t.nodeId),d=o.nodeId===Wt?void 0:n.get(o.nodeId),l=e=>!0===e?.manifest.policies?.allowUndeclaredParameters;if("data"===e.type)!s||l(s)||this.hasPortDirection(s,t.port,"output")||(this.pushPortIssue(e,"source",t,s,r,i),a=!1),!d||l(d)||this.hasPortDirection(d,o.port,"input")||(this.pushPortIssue(e,"target",o,d,r,i),a=!1);else{if(!s||!d)return r.push({code:"edge.boundary-routing",path:i,message:`Connection edge '${e.id}' must connect two node connection ports; the workflow boundary only routes data`,edgeId:e.id}),!1;if(!(l(s)||l(d)||this.hasPortDirection(s,t.port,"connection")&&this.hasPortDirection(d,o.port,"connection")))return r.push({code:"edge.type-mismatch",path:i,message:`Connection edge '${e.id}' endpoints must both be connection ports`,edgeId:e.id,details:{sourcePort:t.port,targetPort:o.port}}),!1}return a}hasPortDirection(e,t,o){return("input"===o?e.manifest.inputs:"output"===o?e.manifest.outputs:e.manifest.connections??[]).some(e=>e.id===t)}pushPortIssue(e,t,o,n,r,i){const a="source"===t?"output":"input";r.push({code:"data"===e.type?"edge.invalid-direction":"edge.type-mismatch",path:`${i}.${t}`,message:`Edge '${e.id}' ${t} port '${o.port}' on node '${o.nodeId}' is not an ${a} port of kind '${n.manifest.kind}'`,edgeId:e.id,nodeId:o.nodeId,details:{port:o.port,expected:a}})}}class wn{validate(e,t){this.validateDuplicates(e.edges,t),this.validatePolicies(e,t)}validateDuplicates(e,t){const o=new Map;for(const n of e){const e=`${n.sourceNodeId}:${n.sourcePort}->${n.targetNodeId}:${n.targetPort}`,r=o.get(e);r?t.push({code:"connection.duplicate-edge",path:`edges[${n.id}]`,message:`Edge '${n.id}' duplicates the routing of edge '${r.id}' (${e})`,edgeId:n.id,details:{duplicateOf:r.id,routing:e}}):o.set(e,n)}}validatePolicies(e,t){const o=new Map;for(const t of e.edges){if("connection"!==t.type)continue;const e=`${t.targetNodeId}:${t.targetPort}`,n=o.get(e)??[];n.push(t),o.set(e,n)}for(const o of e.edges){if("connection"!==o.type)continue;const n=e.nodeById.get(o.targetNodeId),r=n?.manifest.connections?.find(e=>e.id===o.targetPort)?.connectionPolicy;this.validateEdgePolicy(o,e.nodeById,r,t)}for(const[n,r]of o){const o=n.lastIndexOf(":"),i=n.slice(0,o),a=n.slice(o+1),s=e.nodeById.get(i),d=s?.manifest.connections?.find(e=>e.id===a)?.connectionPolicy;if(!d)continue;const l=void 0!==d.maxConnections?d.maxConnections:!1===d.allowMultiple?1:1/0;r.length>l&&t.push({code:"connection.max-connections",path:`edges[${r[r.length-1].id}]`,message:`Connection port '${a}' on node '${i}' accepts at most ${l} connection(s) but has ${r.length}`,nodeId:i,edgeId:r[r.length-1].id,details:{port:a,max:l,actual:r.length}})}}validateEdgePolicy(e,t,o,n){if(e.sourceNodeId===e.targetNodeId&&!o?.allowSelf)return void n.push({code:"connection.self-connection",path:`edges[${e.id}]`,message:`Edge '${e.id}' connects node '${e.sourceNodeId}' to itself, which the target port policy does not allow`,edgeId:e.id,nodeId:e.sourceNodeId});if(!o)return;const r=t.get(e.sourceNodeId),i=r?.manifest.kind;if(!o.allowedNodeKinds?.length||i&&o.allowedNodeKinds.includes(i)||n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source kind '${i??"unknown"}' is not in the allowed node kinds of target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{allowedNodeKinds:o.allowedNodeKinds}}),i&&o.blockedNodeKinds?.includes(i)&&n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source kind '${i}' is blocked by target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{blockedNodeKinds:o.blockedNodeKinds}}),o.allowedPortCategories?.length){const t=r?.manifest.connections?.find(t=>t.id===e.sourcePort)?.category;t&&o.allowedPortCategories.includes(t)||n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source port '${e.sourcePort}' category '${t??"unknown"}' is not in the allowed port categories of target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{allowedPortCategories:o.allowedPortCategories}})}}}class bn{constructor(e){this.authorizer=e}async validate(e,t,o,n){const r=this.collectReferences(e,t);for(const i of t.credentials??[]){const a=r.find(e=>void 0===e.credentialType||e.credentialType===i.type);if(a){if(this.checkType(a,i))o.push({code:"credential.type-mismatch",path:n,message:`Node '${e.id}' credential '${a.credentialId}' has type '${a.credentialType}' but kind '${t.kind}' requires '${i.type}'`,nodeId:e.id,details:{credentialType:a.credentialType??"",requiredType:i.type}});else if(this.authorizer){if(!await this.authorizer.hasCredential(a)){o.push({code:"credential.not-found",path:n,message:`Node '${e.id}' references credential '${a.credentialId}' which does not exist`,nodeId:e.id,details:{credentialId:a.credentialId}});continue}await this.authorizer.authorize(a,i)||o.push({code:"credential.unauthorized",path:n,message:`Node '${e.id}' is not authorized to use credential '${a.credentialId}'`,nodeId:e.id,details:{credentialId:a.credentialId}})}}else!1!==i.required&&o.push({code:"credential.missing",path:n,message:`Node '${e.id}' does not provide the required credential of type '${i.type}'`,nodeId:e.id,details:{credentialType:i.type}})}this.scanPlainSecrets(e,o,n)}collectReferences(e,t){const o=[];for(const n of t.parameters){if("credential"!==n.type)continue;const t=(e.parameters??{})[n.id];Yo(t)&&o.push(this.normalize(t,n.credentialType))}const n=(e.metadata??{}).credentials;if(n&&"object"==typeof n&&!Array.isArray(n))for(const e of Object.values(n))Yo(e)&&o.push(this.normalize(e));return o}normalize(e,t){return"string"==typeof e?{credentialId:e,credentialType:t??""}:{credentialId:e.credentialId,credentialType:e.credentialType??t??""}}checkType(e,t){return void 0!==e.credentialType&&e.credentialType!==t.type}scanPlainSecrets(e,t,o){const n=new Set(Zo);for(const[r,i]of Object.entries(e.parameters??{}))this.scanPlainSecretValue(i,[r],e,o+".parameters",n,t);for(const[r,i]of Object.entries(e.metadata??{}))this.scanPlainSecretValue(i,[r],e,o+".metadata",n,t)}scanPlainSecretValue(e,t,o,n,r,i,a=0){const s=t[t.length-1];if(r.has(s))i.push({code:"credential.plain-secret",path:`${n}.${t.join(".")}`,message:`Node '${o.id}' carries plain secret material in '${t.join(".")}'; workflow documents may only hold credential references`,nodeId:o.id});else if(8>a&&null!==e)if(Array.isArray(e))for(const s of e)this.scanPlainSecretValue(s,[...t,"[]"],o,n,r,i,a+1);else if("object"==typeof e)for(const[s,d]of Object.entries(e))this.scanPlainSecretValue(d,[...t,s],o,n,r,i,a+1)}}class vn extends A{constructor(e,t=[]){super(e),this.issues=t,this.name=vn.name}}class In extends A{constructor(e,t){super(e),this.edgeId=t,this.name=In.name}}class En extends U{constructor(e){super(e),this.name=En.name}}const Nn={maxDocumentBytes:2e6,maxNestingDepth:10,maxNodes:500,maxEdges:1e3},On=["node","definition","executor","execute","ports","component"];function kn(e){if(!e||"object"!=typeof e)return!1;const t=e;return pt(t.document)&&Array.isArray(t.nodes)&&Array.isArray(t.edges)&&t.nodeById instanceof Map&&t.incomingByNode instanceof Map&&t.outgoingByNode instanceof Map&&t.nodes.every(e=>null!==e&&"object"==typeof e&&"object"==typeof e.instance&&"object"==typeof e.manifest&&"object"==typeof e.executor)}function An(e,t){const o=[];for(const n of Object.keys(e))On.includes(n)&&o.push({code:"document.forbidden-field",path:`${t}.${n}`,message:`Field '${n}' is not accepted in a canonical workflow document: node, definition, executor, execute, ports and component fields are rejected`,details:{field:n}});return o}class xn{constructor(e){this.options=e,this.parameterValidator=new en,this.edgeValidator=new yn,this.connectionPolicyValidator=new wn,this.nodeValidator=new gn(e.catalogue),this.credentialValidator=new bn(e.credentialAuthorizer)}async validateOrThrow(e,...t){const o=await this.validate(e,0,...t);if(!o.valid||!o.resolved)throw new vn(`Graph workflow document '${e.id}' failed validation with ${o.issues.length} issue(s)`,o.issues);return o.resolved}async validate(e,t=0,...o){const n=[],r={...Nn,...this.options.limits};if(!await this.validateStructure(e,r,t,n,...o))return{valid:!1,issues:n};const i=await this.nodeValidator.resolveNodes(e.nodes,n,this.options.resolutionContext,...o),a=e.nodes.filter(e=>i.has(e.id)).map(e=>i.get(e.id)),s=(e=>{const t=new Map;for(const o of e.edges??[]){if("data"!==o.type)continue;const e=o.target;if("node"!==e.scope)continue;const n=t.get(e.nodeId)??new Set;n.add(e.port),t.set(e.nodeId,n)}return t})(e);for(const e of a)this.parameterValidator.validate(e.instance,e.manifest,n,`nodes[${e.instance.id}]`,s.get(e.instance.id));for(const e of a)this.nodeValidator.validateEffectivePorts(e.instance,e.manifest,n,`nodes[${e.instance.id}]`);const d=this.edgeValidator.resolveEdges(e,i,n),l=new Map,c=new Map;for(const e of d){if(e.targetNodeId!==Wt){const t=l.get(e.targetNodeId)??[];t.push(e),l.set(e.targetNodeId,t)}if(e.sourceNodeId!==Wt){const t=c.get(e.sourceNodeId)??[];t.push(e),c.set(e.sourceNodeId,t)}}this.connectionPolicyValidator.validate({edges:d,nodeById:i},n),this.validateAcyclicity(a,d,e,n),mn(e,n);for(const e of a)this.parameterValidator.validateBindingSatisfaction(e.instance,e.manifest,l.get(e.instance.id)??[],n,`nodes[${e.instance.id}]`,{allowLiteralAndEdgeBindings:this.options.allowLiteralAndEdgeBindings});this.validateRequiredWorkflowOutputs(e,c,n);for(const e of a)await this.credentialValidator.validate(e.instance,e.manifest,n,`nodes[${e.instance.id}]`);return this.validateCapabilities(a,n),n.length>0?{valid:!1,issues:n}:{valid:!0,issues:n,resolved:{document:e,nodes:a,edges:d,nodeById:i,incomingByNode:l,outgoingByNode:c}}}async validateStructure(e,t,o,n,...r){if(!pt(e))return n.push({code:"document.shape",path:"$",message:"Payload is not a canonical GraphWorkflowDocument: id and name must be strings and inputs, outputs, nodes and edges must be arrays"}),!1;if(e.id&&e.id.trim()||n.push({code:"document.empty-id",path:"$.id",message:"Workflow document id must be a non-empty string"}),!Ue(e))return n.push({code:"document.json-unsafe",path:"$",message:"Document contains JSON-unsafe values: functions, class instances, undefined, NaN/Infinity, symbol keys and unsafe prototype keys are rejected"}),!1;n.push(...An(e,"$"));for(const t of[...e.inputs,...e.outputs])n.push(...An(t,"ports"));for(const t of e.nodes)n.push(...An(t,`nodes[${t.id}]`));for(const t of e.edges)n.push(...An(t,`edges[${t.id}]`));this.validateUniqueIds(e,n),this.validateLimits(e,t,o,n);try{ot(e)}catch(e){n.push({code:"document.structure",path:"$",message:e instanceof Error?e.message:e+""})}return await this.validateNestedBodies(e,o,n,...r),!0}validateUniqueIds(e,t){const o=new Set,n=new Set;for(const[r,i]of[["input",e.inputs],["output",e.outputs]]){const e="input"===r?o:n;for(const o of i)e.has(o.id)?t.push({code:"document.duplicate-port-id",path:`${"input"===r?"inputs":"outputs"}[${o.id}]`,message:`Workflow ${r} port '${o.id}' is declared more than once; workflow port ids must be unique`}):e.add(o.id)}const r=new Set;for(const o of e.nodes)r.has(o.id)?t.push({code:"document.duplicate-node-id",path:`nodes[${o.id}]`,message:`Node '${o.id}' is declared more than once; node ids must be unique`,nodeId:o.id}):r.add(o.id);const i=new Set;for(const o of e.edges)i.has(o.id)?t.push({code:"document.duplicate-edge-id",path:`edges[${o.id}]`,message:`Edge '${o.id}' is declared more than once; edge ids must be unique`,edgeId:o.id}):i.add(o.id)}validateLimits(e,t,o,n){e.nodes.length>t.maxNodes&&n.push({code:"document.limit.nodes",path:"$.nodes",message:`Document declares ${e.nodes.length} nodes; at most ${t.maxNodes} are allowed`,details:{count:e.nodes.length,limit:t.maxNodes}}),e.edges.length>t.maxEdges&&n.push({code:"document.limit.edges",path:"$.edges",message:`Document declares ${e.edges.length} edges; at most ${t.maxEdges} are allowed`,details:{count:e.edges.length,limit:t.maxEdges}}),o>t.maxNestingDepth&&n.push({code:"document.limit.depth",path:"$",message:`Document nests loop bodies ${o} levels deep; at most ${t.maxNestingDepth} levels are allowed`,details:{depth:o,limit:t.maxNestingDepth}});const r=Buffer.byteLength(JSON.stringify(e),"utf8");r>t.maxDocumentBytes&&n.push({code:"document.limit.size",path:"$",message:`Document serializes to ${r} bytes; at most ${t.maxDocumentBytes} bytes are allowed`,details:{bytes:r,limit:t.maxDocumentBytes}})}async validateNestedBodies(e,t,o,...n){for(const r of e.nodes){const e=[["loop.body",r.loop?.body],["errorBoundary.try",r.errorBoundary?.try],["errorBoundary.catch",r.errorBoundary?.catch],["errorBoundary.finally",r.errorBoundary?.finally]];for(const[i,a]of e){if(!a)continue;const e=await this.validate(a,t+1,...n);for(const t of e.issues)o.push({...t,path:`nodes[${r.id}].${i}.${t.path}`,nodeId:t.nodeId??r.id})}}}validateAcyclicity(e,t,o,n){const r=new Set(e.map(e=>e.instance.id)),i=new Map(e.map(e=>[e.instance.id,0]));for(const e of t)r.has(e.sourceNodeId)&&i.has(e.targetNodeId)&&i.set(e.targetNodeId,(i.get(e.targetNodeId)??0)+1);const a=[...i.entries()].filter(([,e])=>0===e).map(([e])=>e),s=[];for(;a.length>0;){const e=a.shift();s.push(e);for(const o of t){if(o.sourceNodeId!==e)continue;if(!i.has(o.targetNodeId))continue;const t=(i.get(o.targetNodeId)??1)-1;i.set(o.targetNodeId,t),0===t&&a.push(o.targetNodeId)}}if(s.length!==i.size){const e=[...i.keys()].filter(e=>!s.includes(e));n.push({code:"topology.cycle",path:"$.edges",message:`Workflow '${o.id}' contains an unsupported cycle involving node(s): ${e.join(", ")}`,details:{cyclicNodes:e}})}}validateRequiredWorkflowOutputs(e,t,o){const n=new Set;for(const e of t.values())for(const t of e)t.targetNodeId===Wt&&n.add(t.targetPort);for(const t of e.outputs)!0===t.required&&void 0===t.defaultValue&&(n.has(t.id)||o.push({code:"topology.required-output-unsatisfiable",path:`outputs[${t.id}]`,message:`Required workflow output '${t.id}' has no incoming edge from any node`}))}validateCapabilities(e,t){for(const o of e){const e=o.manifest;for(const n of e.capabilities??[])gt(n)||t.push({code:"capability.invalid",path:`nodes[${o.instance.id}]`,message:`Kind '${e.kind}' declares unknown capability '${n+""}'`,nodeId:o.instance.id,details:{capability:n+""}});!0!==e.policies?.allowUndeclaredParameters&&o.instance.loop&&((e.capabilities??[]).includes("loop")||t.push({code:"capability.loop-not-supported",path:`nodes[${o.instance.id}].loop`,message:`Node '${o.instance.id}' carries loop configuration but kind '${e.kind}' does not declare the 'loop' capability`,nodeId:o.instance.id}))}}}let _n=class extends B{constructor(){super()}async plan(e,...t){const{log:o}=(await this.logCtx(t,"plan",!0)).for(this.plan);if(o.debug(`Planning resolved workflow '${e?.document?.id??"unknown"}'`),!kn(e))throw new lo("GraphExecutionPlanner.plan accepts only a GraphResolvedWorkflow produced by the nine-stage validation gate; raw workflow definitions and inline node definitions are rejected",{received:(n=e,n&&"object"==typeof n?{reason:"input is not a GraphResolvedWorkflow",looksLikeWorkflowDefinition:"nodes"in n&&"relations"in n&&!("nodeById"in n),hasResolvedNodes:Array.isArray(n.nodes)}:{reason:"input is not an object"})});var n;const r=this.buildPlanNodes(e),i=this.buildPlanEdges(e),a=this.buildIncomingMap(i),s=this.buildOutgoingMap(i),d=this.topologicalLayers(r,i);return{resolved:e,workflowId:e.document.id||e.document.name,nodes:r,edges:i,layers:d,incomingByNode:a,outgoingByNode:s}}buildPlanNodes(e){return e.nodes.map(e=>({id:e.instance.id,kind:e.manifest.kind,instance:e.instance,manifest:e.manifest,executor:e.executor,inputPorts:e.manifest.inputs.map(e=>e.id),outputPorts:e.manifest.outputs.map(e=>e.id),connectionPorts:(e.manifest.connections??[]).map(e=>e.id),metadata:e.instance.metadata}))}buildPlanEdges(e){return e.edges.map(e=>({id:e.id,type:e.type,sourceNodeId:e.sourceNodeId,sourcePort:e.sourcePort,targetNodeId:e.targetNodeId,targetPort:e.targetPort,...void 0!==e.label?{label:e.label}:{},metadata:e.metadata}))}buildIncomingMap(e){const t=new Map;for(const o of e){if(o.targetNodeId===Wt)continue;const e=t.get(o.targetNodeId)??[];e.push(o),t.set(o.targetNodeId,e)}return t}buildOutgoingMap(e){const t=new Map;for(const o of e){if(o.sourceNodeId===Wt)continue;const e=t.get(o.sourceNodeId)??[];e.push(o),t.set(o.sourceNodeId,e)}return t}topologicalLayers(e,t){const o=e.filter(e=>e.id!==Wt),n=new Set(o.map(e=>e.id)),r=t.filter(e=>n.has(e.sourceNodeId)&&n.has(e.targetNodeId)),i=new Map;for(const e of o)i.set(e.id,0);for(const e of r)i.set(e.targetNodeId,(i.get(e.targetNodeId)??0)+1);const a=[],s=new Set;let d=o.filter(e=>0===(i.get(e.id)??0)),l=0;for(;d.length>0;){const e={index:l++,nodes:d};a.push(e);const t=[];for(const e of d){s.add(e.id);const n=r.filter(t=>t.sourceNodeId===e.id);for(const e of n){const n=(i.get(e.targetNodeId)??1)-1;if(i.set(e.targetNodeId,n),0===n&&!s.has(e.targetNodeId)){const n=o.find(t=>t.id===e.targetNodeId);n&&t.push(n)}}}d=t}if(s.size!==o.length){const e=o.filter(e=>!s.has(e.id)).map(e=>e.id);throw new oo({unplannedNodes:e,workflowId:o[0]?.manifest.kind})}return a}};_n=S([F(),D("design:paramtypes",[])],_n);const Sn=new Set(["engine","valueAdapter","codeSandboxEvaluator","workflowStore"]);function Dn(e,t){const o={};for(const[n,r]of Object.entries(e??{}))Sn.has(n)&&!t.has(n)||(o[n]=r);return o}class Pn extends W{constructor(){super()}async initialize(...e){const t=e[0];if(!t||"object"!=typeof t||!t.registry)return this._config=void 0,this._client=void 0,{config:void 0,client:void 0};const o=t.catalogue??t.registry.catalog,n=t.valueAdapter??q.current;if(!n)throw new to("GraphExecutionEngine requires a Decaf adapter for cached/pinned values: pass `valueAdapter` or configure one via `Adapter.setCurrent(...)`","GRAPH_VALUE_ADAPTER_MISSING");const r=t.backend??Mo.current??new fn,i={registry:t.registry,catalogue:o,planner:t.planner??new _n,backend:r,valueAdapter:n,eventEmitter:t.eventEmitter??new ho,documentValidator:t.documentValidator??new xn({catalogue:o,limits:t.documentLimits,credentialAuthorizer:t.credentialAuthorizer}),authValidator:new So({enabled:!0===t.authEnabled,...t.authMatch?{match:t.authMatch}:{}}),...t.codeSandboxEvaluator?{codeSandboxEvaluator:t.codeSandboxEvaluator}:{}};this._config=t,this._client=i;const a=new Set(["engine","valueAdapter"]);t.codeSandboxEvaluator&&a.add("codeSandboxEvaluator"),t.workflowStore&&a.add("workflowStore");const s=Dn(r.config,a);return await r.initialize({...s,valueAdapter:n,...t.codeSandboxEvaluator?{codeSandboxEvaluator:t.codeSandboxEvaluator}:{},...t.workflowStore?{workflowStore:t.workflowStore}:{},engine:this}),await(t.onEngineCreated?.(this)),{config:t,client:i}}get codeSandboxEvaluator(){return this.client.codeSandboxEvaluator}get emitter(){return this.client.eventEmitter}get planner(){return this.client.planner}get valueAdapter(){return this.client.valueAdapter}get defaultOptions(){return this.config.defaultOptions??{}}get documentValidator(){return this.client.documentValidator}observe(e){return this.emitter.observe(e)}unObserve(e){this.emitter.unObserve(e)}async dispatchEvent(e){await this.emitter.updateObservers(e)}async execute(e,t={},o={},...n){const{log:r,ctx:i}=(await this.logCtx(n,"execute",!0)).for(this.execute);r.debug(`Executing workflow '${e.id||e.name}'`);const a=this.mergeOptions(o);this.assertNotAborted(a);const s=_o(Ao(i),a.auth);a.auth=s,a.metadata={...a.metadata??{},...s};const d=a.runId??this.generateRunId();a.runId=d;const l=a.path??[],c=new fo,u=sn(this.valueAdapter);u.seedWorkflowInputs(this.withWorkflowInputDefaults(e,t));const p=new To(this.emitter,c,{runId:d,parentRunId:a.parentRunId,workflowId:e.id||e.name,path:l,engine:this,...this.codeSandboxEvaluator?{codeSandboxEvaluator:this.codeSandboxEvaluator}:{}});await p.emit({type:ce.VALIDATION_STARTED,status:se.PLANNING});const h=await this.documentValidator.validate(e,0,i);if(!h.valid||!h.resolved)throw await p.emit({type:ce.VALIDATION_FAILED,status:se.FAILED,payload:{issues:h.issues}}),new vn(`Graph workflow document '${e.id}' failed validation with ${h.issues.length} issue(s)`,h.issues);await p.emit({type:ce.VALIDATION_COMPLETED,status:se.PLANNING,payload:{issues:h.issues.length}}),this.assertNotAborted(a);const f=await this.planner.plan(h.resolved);this.client.authValidator.validate(e,f,s,r),r.debug(`Authorized workflow '${e.id||e.name}' for user ${s.user??"anonymous"}`),this.assertCodeModeSupported(e);const g=new $o(d,f,u,c);return p.bindFrame(g),await p.emit({type:ce.WORKFLOW_STARTED,runId:d,parentRunId:a.parentRunId,workflowId:f.workflowId,path:l,status:se.RUNNING,payload:{inputs:t}}),await p.emit({type:ce.WORKFLOW_PLANNED,runId:d,parentRunId:a.parentRunId,workflowId:f.workflowId,path:l,status:se.PLANNING,payload:{layers:f.layers.length,nodes:f.nodes.length}}),await this.client.backend.execute({document:e,plan:f,inputs:t,options:a,events:p},...n)}get backend(){return this.client.backend}get backendCapabilities(){return Lo(this.client.backend)}async listWorkflows(...e){const t=this.client.backend;if("supported"!==Lo(t).workflows.list||"function"!=typeof t.listWorkflows)throw new to(`Graph execution backend '${this.backendName}' does not support workflow listing`,"GRAPH_BACKEND_WORKFLOWS_NOT_SUPPORTED",{backend:this.backendName});return await t.listWorkflows(...e)}async getWorkflow(e,...t){const o=this.client.backend;if("supported"!==Lo(o).workflows.get||"function"!=typeof o.getWorkflow)throw new to(`Graph execution backend '${this.backendName}' does not support workflow lookup`,"GRAPH_BACKEND_WORKFLOWS_NOT_SUPPORTED",{backend:this.backendName,workflowId:e});return await o.getWorkflow(e,...t)}async listEngineWorkflows(e,...t){const o=Mo.getOrFail(e);if("supported"!==Lo(o).workflows.list||"function"!=typeof o.listWorkflows)throw new to(`Graph execution backend '${e}' does not support workflow listing`,"GRAPH_BACKEND_WORKFLOWS_NOT_SUPPORTED",{backend:e});return await o.listWorkflows(...t)}async getEngineWorkflow(e,t,...o){const n=Mo.getOrFail(e);if("supported"!==Lo(n).workflows.get||"function"!=typeof n.getWorkflow)throw new to(`Graph execution backend '${e}' does not support workflow lookup`,"GRAPH_BACKEND_WORKFLOWS_NOT_SUPPORTED",{backend:e,workflowId:t});return await n.getWorkflow(t,...o)}get backendName(){return this.client.backend.constructor?.name??"GraphExecutionBackend"}assertCodeModeSupported(e){const t=this.client.backend;if(t.local)return;const o=Vo(e);if(0!==o.length){if("unsupported"===t.codeMode)throw new to(`Graph execution backend '${this.backendName}' does not support code-mode workflows`,"GRAPH_CODE_MODE_UNSUPPORTED_BACKEND",{backend:this.backendName,surfaces:o});if(!this.codeSandboxEvaluator)throw new to("Code-mode workflows require a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator","GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{backend:this.backendName,surfaces:o})}}async pinNode(e){const t=this.createPinningService();await t.pinNode(e),await this.emitPinningEvent(e.nodeId,ce.NODE_PINNED)}async unpinNode(e){const t=this.createPinningService();await t.unpinNode(e),await this.emitPinningEvent(e.nodeId,ce.NODE_UNPINNED)}createPinningService(){const e=sn(this.valueAdapter);return new ln(e,new pn,new hn)}async emitPinningEvent(e,t){const o=(new fo).create({id:"",sequence:0,timestamp:new Date,runId:"pinning",workflowId:"",type:t,nodeId:e,path:[]});await this.emitter.updateObservers(o)}withWorkflowInputDefaults(e,t){const o={...t};for(const t of e.inputs)void 0===o[t.id]&&void 0!==t.defaultValue&&(o[t.id]=t.defaultValue);return o}mergeOptions(e){return{concurrency:4,failFast:!0,validateInputs:!0,validateOutputs:!0,maxLoopIterations:zt,maxForeachIterations:Jt,usePinnedValues:!0,writeThroughCache:!1,path:[],metadata:{},...this.defaultOptions,...e}}assertNotAborted(e){if(!0===e.abortSignal?.aborted)throw new uo(e.runId??"unknown")}generateRunId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new to("Cannot generate a graph run id: crypto.randomUUID is unavailable in this runtime","GRAPH_RUN_ID_ERROR",{runtime:typeof globalThis.crypto});return e.randomUUID()}}const Rn=new Set(["process","require","module","exports","global","globalThis","Function","eval","fetch","XMLHttpRequest","WebSocket","Worker","Deno","Bun","__dispatch"]);class $n extends W{constructor(){super()}async initialize(...e){const t=e[0]??{},o=t&&"object"==typeof t?t:{};return this._config=o,this._client=V,{config:o,client:V}}get defaultTimeoutMs(){return this.config.timeoutMs??1e3}get defaultMemoryMb(){return this.config.memoryMb??32}async evaluate(e,...t){(await this.logCtx(t,"evaluate",!0)).for(this.evaluate);const o=e.code;if(!o||"string"!=typeof o||0===o.trim().length)throw new to("Code sandbox received empty code","GRAPH_CODE_SANDBOX_EMPTY_CODE");const n=((e,t)=>"javascript"===t?e:X.transpileModule(e,{compilerOptions:{target:X.ScriptTarget.ES2022,module:X.ModuleKind.None,strict:!0,noEmitHelpers:!0,importHelpers:!1}}).outputText.replace(/^"use strict";\s*/,""))(o,e.language??"javascript");(e=>{if(e.length>1e5)throw new to("Code exceeds the maximum length of 100000 characters","GRAPH_CODE_SANDBOX_CODE_TOO_LONG",{length:e.length});let t;try{t=z.parse(`async function __validate() {\n${e}\n}`,{ecmaVersion:"latest",sourceType:"script"})}catch{try{t=z.parse(e,{ecmaVersion:"latest",sourceType:"module"})}catch(t){throw new to("Code failed to parse: "+t.message,"GRAPH_CODE_SANDBOX_PARSE_ERROR",{code:e,error:t.message})}}J.full(t,e=>{const t=e;if("ImportDeclaration"===t.type)throw new to("Imports are not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"import"});if("ExportNamedDeclaration"===t.type||"ExportDefaultDeclaration"===t.type)throw new to("Exports are not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"export"});if("Identifier"===t.type&&"string"==typeof t.name&&Rn.has(t.name))throw new to(`Identifier "${t.name}" is not allowed in Code nodes.`,"GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:t.name});if("NewExpression"===t.type&&"Function"===t.callee?.name)throw new to("new Function() is not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"Function"});if("CallExpression"===t.type&&"eval"===t.callee?.name)throw new to("eval() is not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"eval"})})})(n);const r=!(e=>/\breturn\b[\s;]/.test(e))(n),i=r?n.replace(/[\s;]+$/,""):n,a={$input:e.input??{},$vars:e.vars??{},$item:e.item,$index:e.index,$node:e.nodes??{},$output:void 0},s=Object.keys(a),d=r?`return (${i});`:i,l=`"use strict";\nasync function __userFunction(${s.join(", ")}) {\n${d}\n}\n__userFunction(${s.join(", ")}).then(function(__r) { return JSON.stringify({ v: __r }); });`,c=new V.Isolate({memoryLimit:this.defaultMemoryMb}),u=await c.createContext();try{const t=u.global;e.logger&&await this.injectConsole(u,e.logger);for(const[e,o]of Object.entries(a))await t.set(e,new V.ExternalCopy(void 0===o?null:o).copyInto());let o;try{o=await c.compileScript(l,{filename:"graph-code-node.js"})}catch(e){if(!r)throw new to("Code failed to compile: "+e.message,"GRAPH_CODE_SANDBOX_COMPILE_ERROR",{code:n,error:e.message});{const e=i,t=`"use strict";\nasync function __userFunction(${s.join(", ")}) {\n${e}\n}\n__userFunction(${s.join(", ")}).then(function(__r) { return JSON.stringify({ v: __r }); });`;try{o=await c.compileScript(t,{filename:"graph-code-node.js"})}catch(e){throw new to("Code failed to compile: "+e.message,"GRAPH_CODE_SANDBOX_COMPILE_ERROR",{code:n,error:e.message})}}}const d=e.timeoutMs??this.defaultTimeoutMs;let p;try{p=await this.runBounded(o,u,d,e.abortSignal)}catch(e){if(e instanceof to)throw e;const t=e.message;if(t.includes("timed out")||t.includes("timeout"))throw new to(`Code execution timed out after ${d} ms`,"GRAPH_CODE_SANDBOX_TIMEOUT",{timeoutMs:d});if(t.includes("memory")||t.includes("heap"))throw new to(`Code exceeded the memory limit of ${this.defaultMemoryMb} MB`,"GRAPH_CODE_SANDBOX_MEMORY_LIMIT",{memoryMb:this.defaultMemoryMb});throw new to("Code execution failed: "+t,"GRAPH_CODE_SANDBOX_RUNTIME_ERROR",{code:n,error:t})}if("string"!=typeof p)throw new to("Code sandbox returned an unexpected non-string result","GRAPH_CODE_SANDBOX_UNEXPECTED_RESULT",{result:p});return JSON.parse(p).v}finally{u.release(),c.dispose()}}async runBounded(e,t,o,n){const r=e.run(t,{timeout:o,promise:!0});r.catch(()=>{});const i=[r];let a,s;try{return i.push(new Promise((e,t)=>{a=setTimeout(()=>{t(new to(`Code execution timed out after ${o} ms`,"GRAPH_CODE_SANDBOX_TIMEOUT",{timeoutMs:o}))},o+100)})),n&&i.push(new Promise((e,t)=>{const r=()=>{const e="timeout"===n.reason;t(new to(e?`Code execution timed out after ${o} ms`:"Code execution aborted",e?"GRAPH_CODE_SANDBOX_TIMEOUT":"GRAPH_CODE_SANDBOX_ABORTED",{timeoutMs:o,reason:n.reason}))};n.aborted?r():(n.addEventListener("abort",r,{once:!0}),s=()=>n.removeEventListener("abort",r))})),await Promise.race(i)}finally{a&&clearTimeout(a),s?.()}}async injectConsole(e,t){const o=new V.Reference((e,o)=>{let n;try{n=JSON.parse(o)}catch{n=[o]}const r=n.map(e=>"string"==typeof e?e:JSON.stringify(e)).join(" "),i=1===n.length?n[0]:n;switch(e){case"log":case"info":default:t.info(r,i);break;case"warn":t.warn(r,i);break;case"error":t.error(r,i);break;case"debug":case"dir":case"dirxml":case"table":t.debug(r,i);break;case"trace":t.trace(r,i);break;case"group":case"groupCollapsed":t.debug("[group] "+r,i);break;case"groupEnd":t.debug("[groupEnd]",void 0);break;case"time":case"timeEnd":case"timeLog":case"count":case"countReset":t.debug(`[${e}] ${r}`,i);break;case"assert":n[0]||t.error("Assertion failed: "+r,i);case"clear":}});await e.evalClosure("\n function __ser() {\n var out = [];\n for (var i = 0; i < arguments.length; i++) {\n var a = arguments[i];\n try { out.push(typeof a === 'object' ? JSON.parse(JSON.stringify(a)) : a); }\n catch (e) { out.push(String(a)); }\n }\n return JSON.stringify(out);\n }\n function __call(level) {\n return function() {\n $0.applySync(undefined, [level, __ser.apply(null, arguments)]);\n };\n }\n globalThis.console = {\n log: __call('log'),\n info: __call('info'),\n warn: __call('warn'),\n error: __call('error'),\n debug: __call('debug'),\n trace: __call('trace'),\n dir: __call('dir'),\n dirxml: __call('dirxml'),\n table: __call('table'),\n group: __call('group'),\n groupCollapsed: __call('groupCollapsed'),\n groupEnd: __call('groupEnd'),\n time: __call('time'),\n timeEnd: __call('timeEnd'),\n timeLog: __call('timeLog'),\n assert: __call('assert'),\n count: __call('count'),\n countReset: __call('countReset'),\n clear: __call('clear')\n };\n ",[o]),o.release()}}class Cn extends x{constructor(e){super(e,Cn.name,500)}}class Tn extends _{constructor(e){super(e),this.name=Tn.name}}class Ln extends _{constructor(e){super(e),this.name=Ln.name}}class Mn{constructor(e,t,o={}){this.kind=e,this.declarations=new Map,this.implementations=new Map;for(const e of t){if("string"!=typeof e?.name||!e.name)throw new Cn(`Method declaration for kind '${this.kind}' is missing a name`);if(this.declarations.has(e.name))throw new Cn(`Kind '${this.kind}' declares duplicate method '${e.name}'`);this.declarations.set(e.name,e)}for(const[e,t]of Object.entries(o)){if("function"!=typeof t)throw new Cn(`Method implementation '${e}' for kind '${this.kind}' is not a function`);if(!this.declarations.has(e))throw new Cn(`Kind '${this.kind}' implements method '${e}' which is not declared by its manifest`);this.implementations.set(e,t)}for(const e of this.declarations.keys())if(!this.implementations.has(e))throw new Cn(`Kind '${this.kind}' declares method '${e}' with no implementation`)}has(e){return this.declarations.has(e)}getDeclaration(e){const t=this.declarations.get(e);if(!t)throw new Ln(`Kind '${this.kind}' does not declare method '${e}'`);return t}get(e){return this.getDeclaration(e),this.implementations.get(e)}list(){return[...this.declarations.values()].sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}}function jn(e,t){if(!t)return;let o=e;for(const e of t.split(".")){if(!o||"object"!=typeof o)return;o=o[e]}return o}function Gn(e,t,o){const n=jn(t,e.itemIdPath),r=e.itemLabelPath?jn(t,e.itemLabelPath):void 0;return{id:"string"==typeof n&&n||"number"==typeof n&&Number.isFinite(n)&&n+""||o+"",label:"string"==typeof r?r:void 0}}function Un(e,t){switch(t){case"input":return e.inputs;case"output":return e.outputs;default:return e.connections}}function Fn(e,t){const o={inputs:[],outputs:[],connections:[]},n={input:new Set((e.inputs??[]).map(e=>e.id)),output:new Set((e.outputs??[]).map(e=>e.id)),connection:new Set((e.connections??[]).map(e=>e.id))},r=(e,t)=>{const o=n[e];return!o.has(t)&&(o.add(t),!0)};for(const n of e.dynamicPorts??[])if("repeatFromParameter"===n.type){const e=t[n.parameter];if(!Array.isArray(e))continue;const i=Un(o,n.direction);e.forEach((e,t)=>{const{id:o,label:a}=Gn(n,e,t),s=(d={id:o,index:t,label:a??o},n.portIdTemplate.replaceAll("${id}",d.id).replaceAll("${index}",d.index+"").replaceAll("${label}",d.label));var d;if(!r(n.direction,s))return;const l=n.defaultPort?Fe(n.defaultPort):{id:s,label:a??s,direction:n.direction};l.id=s,l.direction=n.direction,a&&(l.label=a),i.push(l)})}else if("togglePort"===n.type){if(t[n.parameter]!==n.equals)continue;const e=Fe(n.port);if(!r(e.direction,e.id))continue;Un(o,e.direction).push(e)}return o}function Bn(e,t){const o=Fn(e,t),n={kind:e.kind,display:e.display,inputs:[...e.inputs,...o.inputs],outputs:[...e.outputs,...o.outputs],parameters:e.parameters},r=[...e.connections??[],...o.connections];return r.length&&(n.connections=r),e.dynamicPorts?.length&&(n.dynamicPorts=e.dynamicPorts),e.credentials?.length&&(n.credentials=e.credentials),e.capabilities?.length&&(n.capabilities=e.capabilities),e.policies&&(n.policies=e.policies),e.metadata&&(n.metadata=e.metadata),e.namespaces?.length&&(n.namespaces=e.namespaces),Fe(n)}class Wn{async resolve(e,t,o,n,r){if(o){const i=await o(n,r);if(!(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.kind&&"object"==typeof t.display&&null!==t.display&&Array.isArray(t.inputs)&&Array.isArray(t.outputs)&&Array.isArray(t.parameters)})(i))throw new Cn(`resolveManifest provider for kind '${e}' returned a value that does not conform to GraphResolvedNodeManifest`);if(!Ue(i))throw new Cn(`resolveManifest provider for kind '${e}' returned a non-JSON-safe resolved manifest`);const a=Fe(i);return!a.namespaces?.length&&t.namespaces?.length&&(a.namespaces=t.namespaces.slice()),a}return Bn(t,n.parameters??{})}}const qn=["edge","literal","expression"];function Hn(e){return qn.includes(e)}function Kn(e,t,o){if("string"!=typeof o||!o)throw new Cn(`Manifest for kind '${e}' has a ${t} with an empty port id`);if(Le(o))throw new Cn(`Manifest for kind '${e}' has a ${t} with unsafe port id '${o}'`)}let Vn=class extends B{constructor(){super(),this.entries=new Map,this.resolver=new Wn,this.fallbackContext=new M}withContext(e){return e[e.length-1]instanceof M?e:[this.fallbackContext]}register(e,t={},...o){const{log:n}=this.logCtx(this.withContext(o),"register").for(this.register);n.debug(`Registering graph node kind '${e?.manifest?.kind??"unknown"}'`),(e=>{if(!e||"object"!=typeof e)throw new Cn("Graph node registration is required");if(!e.manifest||"object"!=typeof e.manifest)throw new Cn("Graph node registration is missing a manifest");if(!e.executor||"function"!=typeof e.executor.execute)throw new Cn(`Graph node registration for kind '${e.manifest?.kind+""}' is missing an executor`)})(e);const r=e.manifest;if("string"!=typeof r.kind||!r.kind.trim())throw new Cn("Graph node manifest kind is required and must be a non-empty string");const i=r.kind;if(this.entries.has(i)&&!t.replace)throw new Cn(`Graph node kind '${i}' is already registered; pass { replace: true } to replace it`);try{mt(r)}catch(e){throw new Cn(`Manifest for kind '${i}' is not JSON-serializable: ${e.message}`)}((e,t)=>{const o=[["input",t.inputs],["output",t.outputs],["connection",t.connections??[]]];for(const[t,n]of o){const o=new Set;for(const r of n){if(Kn(e,t+" port",r?.id),o.has(r.id))throw new Cn(`Manifest for kind '${e}' declares duplicate static ${t} port id '${r.id}'`);if(o.add(r.id),void 0!==r.defaultMode&&!Hn(r.defaultMode))throw new Cn(`Manifest for kind '${e}' declares invalid default binding mode '${r.defaultMode+""}' on ${t} port '${r.id}'`)}}})(i,r);const a=((e,t)=>{const o=new Set;for(const n of t.parameters){const t=n?.id;if("string"!=typeof t||!t)throw new Cn(`Manifest for kind '${e}' has a parameter with an empty id`);if(Le(t))throw new Cn(`Manifest for kind '${e}' has a parameter with unsafe id '${t}'`);if(o.has(t))throw new Cn(`Manifest for kind '${e}' declares duplicate parameter id '${t}'`);o.add(t)}return o})(i,r);((e,t,o)=>{for(const n of t.dynamicPorts??[]){if(!n||"string"!=typeof n.parameter||!n.parameter)throw new Cn(`Manifest for kind '${e}' has a dynamic-port rule without a parameter reference`);if(!o.has(n.parameter))throw new Cn(`Manifest for kind '${e}' has a dynamic-port rule referencing missing parameter '${n.parameter}'`);if("togglePort"===n.type){if(!n.port)throw new Cn(`Manifest for kind '${e}' has a togglePort rule without a port`);Kn(e,"togglePort rule port",n.port.id)}if("repeatFromParameter"===n.type&&"string"!=typeof n.portIdTemplate)throw new Cn(`Manifest for kind '${e}' has a repeatFromParameter rule without a portIdTemplate`)}})(i,r,a),((e,t)=>{for(const o of t.credentials??[]){if(!ht(o))throw new Cn(`Manifest for kind '${e}' has a malformed credential requirement`);if(!o.type)throw new Cn(`Manifest for kind '${e}' has a credential requirement with an empty type`)}})(i,r),((e,t)=>{for(const o of t.methods??[])if(!wt(o))throw new Cn(`Manifest for kind '${e}' has a malformed method declaration`)})(i,r);const s=new Mn(i,r.methods??[],e.methods??{});return this.entries.set(i,{registration:e,methods:s,placeholderManifest:!1}),this}registerExecutor(e,t,...o){const{log:n}=this.logCtx(this.withContext(o),"registerExecutor").for(this.registerExecutor);if(n.debug(`Registering graph executor for kind '${e}'`),"string"!=typeof e||!e.trim())throw new Cn("Graph executor kind is required");if(!t||"function"!=typeof t.execute)throw new Cn(`Executor registered for kind '${e}' is missing an execute method`);const r=this.entries.get(e);if(r)return r.registration={...r.registration,executor:t},this;const i={kind:e,display:{name:e},inputs:[],outputs:[],parameters:[],policies:{allowUndeclaredParameters:!0,allowUnknownOutputs:!0}};return this.entries.set(e,{registration:{manifest:i,executor:t},methods:new Mn(e,[],{}),placeholderManifest:!0}),this}unregister(e,...t){const{log:o}=this.logCtx(this.withContext(t),"unregister").for(this.unregister);return o.debug(`Unregistering graph node kind '${e}'`),this.entries.delete(e),this}has(e,...t){return this.logCtx(this.withContext(t),"has").for(this.has),this.entries.has(e)}entry(e){const t=this.entries.get(e);if(!t)throw new Tn(`No graph node kind '${e}' is registered in the catalogue`);return t}getManifest(e,...t){return this.logCtx(this.withContext(t),"getManifest").for(this.getManifest),Fe(this.entry(e).registration.manifest)}getExecutor(e,...t){return this.logCtx(this.withContext(t),"getExecutor").for(this.getExecutor),this.entry(e).registration.executor}getMethodDeclaration(e,t,...o){return this.logCtx(this.withContext(o),"getMethodDeclaration").for(this.getMethodDeclaration),this.entry(e).methods.getDeclaration(t)}getMethod(e,t,...o){return this.logCtx(this.withContext(o),"getMethod").for(this.getMethod),this.entry(e).methods.getDeclaration(t),this.entry(e).methods.get(t)}listMethodDeclarations(e,...t){return this.logCtx(this.withContext(t),"listMethodDeclarations").for(this.listMethodDeclarations),this.entry(e).methods.list()}listManifests(e,...t){this.logCtx(this.withContext(t),"listManifests").for(this.listManifests);const o=[...this.entries.keys()].sort(),n=e?.categories?.length?new Set(e.categories):void 0,r=e?.kinds?.length?new Set(e.kinds):void 0,i=[];for(const e of o){if(r&&!r.has(e))continue;const o=this.getManifest(e,...t);n&&!n.has(o.display.category??"")||i.push(o)}return i}listKinds(...e){return this.logCtx(this.withContext(e),"listKinds").for(this.listKinds),[...this.entries.keys()].sort()}get size(){return this.entries.size}async resolveManifest(e,t,o,...n){this.logCtx(this.withContext(n),"resolveManifest").for(this.resolveManifest);const r=this.entry(e);return this.resolver.resolve(e,r.registration.manifest,r.registration.resolveManifest,t,o)}};Vn=S([F(),D("design:paramtypes",[])],Vn);let zn=class extends B{constructor(e=new Vn){super(),this.catalogue=e}get catalog(){return this.catalogue}register(e,t,...o){const{log:n}=this.logCtx(o,"register").for(this.register);if(n.debug(`Registering graph executor for kind '${e}'`),!e)throw new to("Graph executor kind is required");return this.catalogue.registerExecutor(e,t,...o),this}unregister(e,...t){const{log:o}=this.logCtx(t,"unregister").for(this.unregister);return o.debug(`Unregistering graph executor for kind '${e}'`),this.catalogue.unregister(e,...t),this}has(e,...t){return this.logCtx(t,"has").for(this.has),this.catalogue.has(e,...t)}resolve(e,...t){this.logCtx(t,"resolve").for(this.resolve);try{return this.catalogue.getExecutor(e,...t)}catch(t){if(t instanceof Tn)throw new to(`No graph executor registered for kind '${e}'`,"GRAPH_EXECUTOR_NOT_FOUND",{kind:e});throw t}}};zn=S([F(),D("design:paramtypes",[Vn])],zn);let Jn=class extends B{constructor(e,t){super(),this.registry=e,this.defaultExecutor=t}resolve(e,...t){const{log:o}=this.logCtx(t,"resolve").for(this.resolve);return o.debug(`Resolving graph executor for kind '${e}'`),this.registry.has(e,...t)?this.registry.resolve(e,...t):this.defaultExecutor?this.defaultExecutor:this.registry.resolve(e,...t)}};function Xn(e){return e}function Yn(e){return e.methods??[]}function Qn(e){if(!e)return;const t={...e.metadata??{},...e.parameters??{},...e.state??{}};return e.loop&&(t.loop=e.loop),t}Jn=S([F(),D("design:paramtypes",[Function,Object])],Jn);class Zn extends w{constructor(e){super(),w.fromModel(this,e)}execute(e,t){throw new to(`Graph node kind '${this.constructor.name}' does not implement execute`,"GRAPH_NODE_EXECUTE_NOT_IMPLEMENTED",{kind:this.constructor.name})}static applyMetadata(e){return null}static instantiate(e){return new this(e)}}let er=class extends Zn{execute(e,t){throw new co(e.inputs.value)}};function tr(e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack,code:e.graphCode??("number"==typeof e.code?e.code+"":e.code)}:{name:"UnknownError",message:e+""}}S([b(),i("ngx-decaf-crud-field",{label:"graph.node.flow_control.break.fields.value.label",placeholder:"graph.node.flow_control.break.fields.value.placeholder",type:"textarea"}),Re({handle:"value"}),D("design:type",Object)],er.prototype,"value",void 0),er=S([De("core.flow.break",{kind:"core.flow.break",category:"Flow Control",color:"#f59e0b",icon:"ti-square-arrow-right",width:96,height:96,labels:["flow","break","loop","control"],metadata:{title:"graph.node.flow_control.break.name",description:"graph.node.flow_control.break.description"}}),E()],er);let or=class extends Zn{async execute(e,t){const o=t.node.errorBoundary;if(!o?.try)return{result:e.inputs.value??e.inputs};const n=t.engine;if(!n)throw new to("errorBoundary node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");try{const r=await n.execute(o.try,e.inputs,{parentRunId:t.runId,path:[...t.path,"try"]}),i=Object.values(r.nodeResults).find(e=>e.status===se.FAILED);if(i)throw new to(i.error?.message??"error boundary try body failed",i.error?.code??"GRAPH_ERROR_BOUNDARY",i.error?.details);return{result:r.outputs.result??r.outputs}}catch(r){let i=r;if(o.catch){const a=await n.execute(o.catch,{...e.inputs,error:tr(r)},{parentRunId:t.runId,path:[...t.path,"catch"]});i=a.outputs.error??a.outputs}return{error:i}}finally{o.finally&&await n.execute(o.finally,e.inputs,{parentRunId:t.runId,path:[...t.path,"finally"]})}}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.flow_control.error_boundary.fields.value.label",placeholder:"graph.node.flow_control.error_boundary.fields.value.placeholder",type:"textarea"}),Re({handle:"value"}),D("design:type",Object)],or.prototype,"value",void 0),S([$e({handle:"result"}),D("design:type",Object)],or.prototype,"result",void 0),S([$e({handle:"error"}),D("design:type",Object)],or.prototype,"error",void 0),or=S([De("core.flow.errorBoundary",{kind:"core.flow.errorBoundary",category:"Flow Control",color:"#f59e0b",icon:"ti-shield-check",width:96,height:96,labels:["flow","error","try-catch"],metadata:{title:"graph.node.flow_control.error_boundary.name",description:"graph.node.flow_control.error_boundary.description",finally:!1}}),E()],or);let nr=class extends Zn{execute(e){const t=e.inputs.value??e.inputs;return!1===this.approved?{rejected:t}:{approved:t}}};S([b(),Re({handle:"value"}),D("design:type",Object)],nr.prototype,"value",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.human_approval.fields.message.label",placeholder:"graph.node.flow_control.human_approval.fields.message.placeholder",type:"textarea"}),Re({handle:"message",userControlled:!0}),D("design:type",String)],nr.prototype,"message",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.human_approval.fields.approved.label",type:"checkbox"}),Re({handle:"approved",userControlled:!0}),D("design:type",Boolean)],nr.prototype,"approved",void 0),S([$e({handle:"approved"}),D("design:type",Object)],nr.prototype,"approvedOut",void 0),S([$e({handle:"rejected"}),D("design:type",Object)],nr.prototype,"rejectedOut",void 0),nr=S([De("core.flow.humanApproval",{kind:"core.flow.humanApproval",category:"Flow Control",color:"#f59e0b",icon:"ti-user-check",width:96,height:96,labels:["flow","approval","suspend"],metadata:{title:"graph.node.flow_control.human_approval.name",description:"graph.node.flow_control.human_approval.description",approvers:[],timeoutMs:864e5}}),E()],nr);let rr=class extends Zn{execute(e,t){const o=e.inputs,n=o.value??o;if(!this.condition)throw new to("If node has no condition configured","GRAPH_IF_NO_CONDITION",{input:o});if(Go(this.condition))return Fo(this.condition,o,t).then(e=>this.route(e,n));const r=Bo(this.condition,((e,t)=>t===e||"object"!=typeof t||null===t||Array.isArray(t)?e:{...t,...e})(o,n),"if");return this.route(r,n)}route(e,t){if(e)return{then:t};if(!0===this.else)return{else:t};throw new to("If node condition evaluated to false and the else branch is disabled","GRAPH_IF_ELSE_DISABLED",{condition:this.condition})}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.value.label",placeholder:"graph.node.flow_control.if.fields.value.placeholder",type:"textarea"}),Re({handle:"value"}),D("design:type",Object)],rr.prototype,"value",void 0),S([b(),$e({handle:"then"}),D("design:type",Object)],rr.prototype,"then",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.condition.label",placeholder:"graph.node.flow_control.if.fields.condition.placeholder",type:"code"}),Re({handle:"condition",userControlled:!0,type:"object"}),D("design:type",Object)],rr.prototype,"condition",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.else.label",type:"checkbox"}),Re({handle:"else",userControlled:!0}),D("design:type",Boolean)],rr.prototype,"else",void 0),rr=S([De("core.flow.if",{kind:"core.flow.if",category:"Flow Control",color:"#f59e0b",icon:"ti-arrows-split-2",width:96,height:96,labels:["flow","conditional","branch"],metadata:{title:"graph.node.flow_control.if.name",description:"graph.node.flow_control.if.description"}}),E()],rr);let ir=class extends Zn{async execute(e,t){const o=((e,t)=>{const o={cases:t.cases??[],defaultPort:t.defaultPort??"default",hasDefault:!0===t.hasDefault},n=e.node.metadata?.switch;return n&&Array.isArray(n.cases)?{cases:n.cases,defaultPort:n.defaultPort??o.defaultPort,hasDefault:!0===n.hasDefault||o.hasDefault}:o})(t,this),n=o.cases,r=e.inputs,i=r.value??r,a=((e,t)=>t===e||"object"!=typeof t||null===t||Array.isArray(t)?e:{...t,...e})(r,i);for(const e of n)if(await Wo(e.condition,{input:r,state:a,label:"switch case"},t))return{[e.outputPort]:i};if(!0!==o.hasDefault)throw new to("No switch case matched and default port is not enabled","GRAPH_SWITCH_NO_MATCH",{cases:n.map(e=>e.id)});const s=o.defaultPort??"default";return{[s]:i}}static applyMetadata(e){const t=xe(this),o=e.defaultPort??"default",n=!0===e.hasDefault,r=t.ports.filter(t=>!e.cases.some(e=>e.outputPort===t.property)),i=r.filter(e=>e.property!==o),a=r.find(e=>e.property===o),s=[...i,...e.cases.map(e=>({property:e.outputPort,name:e.label,direction:Z.OUTPUT,label:e.label,required:!1,hidden:!1,path:e.outputPort}))];return n&&a&&s.push(a),{ports:s,size:te(t,{cases:e.cases.length}),dataPatch:{switchMetadata:e}}}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.value.label",placeholder:"graph.node.flow_control.switch.fields.value.placeholder",type:"textarea"}),Re({handle:"value"}),D("design:type",Object)],ir.prototype,"value",void 0),S([b(),$e({handle:"default"}),D("design:type",Object)],ir.prototype,"default",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.cases.label",type:"collection"}),D("design:type",Object)],ir.prototype,"cases",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.hasDefault.label",type:"checkbox"}),D("design:type",Boolean)],ir.prototype,"hasDefault",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.defaultPort.label",type:"text"}),D("design:type",String)],ir.prototype,"defaultPort",void 0),ir=S([De("core.flow.switch",{kind:"core.flow.switch",category:"Flow Control",color:"#f59e0b",icon:"ti-arrows-shuffle",width:120,height:140,sizeRules:[{type:"parameterCount",parameter:"cases",dimension:"height",perItem:24}],labels:["flow","switch","multi-branch"],metadata:{title:"graph.node.flow_control.switch.name",description:"graph.node.flow_control.switch.description"}}),E()],ir);const ar={maxDocumentBytes:2e6,maxNestingDepth:10,maxNodes:500,maxEdges:1e3},sr=o.accumulate({graph:{workflows:{limits:{...ar},allowAnonymousAccess:!1},execution:{maxCodeTimeoutMs:Xt}}}),dr=1e3;function lr(e,t){const o="number"==typeof t?t:Number(t),n=Number.isFinite(o)&&o>0?o:Xt,r="number"==typeof e?e:Number(e);return Number.isFinite(r)&&r>0?Math.min(Math.floor(r),n):1e3}const cr=["javascript","typescript"],ur="javascript";let pr=class extends w{constructor(){super(...arguments),this.language=ur}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.utility.code.fields.language.label",type:"select"}),N([...cr]),v(String),D("design:type",String)],pr.prototype,"language",void 0),S([b(),i("code-editor",{label:"graph.node.utility.code.fields.code.label",placeholder:"graph.node.utility.code.fields.code.placeholder"}),Re({handle:"code"}),D("design:type",String)],pr.prototype,"code",void 0),S([d(),Re({handle:"data"}),D("design:type",Object)],pr.prototype,"data",void 0),pr=S([E()],pr);let hr=class extends Zn{async execute(e,t){const o=e.inputs,n=this.input,r=o.code??e.parameters?.code??n?.code??this.defaultCode,i=n?.language??ur;if(!r||"string"!=typeof r||0===r.trim().length)throw new no("Code node has no code to execute (input.code is empty)",{input:o});const a=t.engine?.codeSandboxEvaluator;if(!a)throw new to("Code node execution requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator","GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{code:r});const s=sr.graph.execution?.maxCodeTimeoutMs,d="number"==typeof s&&Number.isFinite(s)&&s>0?s:Xt,l=lr(this.timeoutMs,d),c=t.metadata,u={code:r,language:i,input:o,vars:c?.vars??void 0,item:c?.item,index:c?.index,nodes:c?.nodes??void 0,logger:t.logger,timeoutMs:l,abortSignal:t.abortSignal};await t.log("Executing code node",{language:i,length:r.length,timeoutMs:l});const p=await a.evaluate(u);return await t.log("Code node executed",{hasResult:void 0!==p}),{result:p}}};S([b(),Re({handle:"input",model:pr}),D("design:type",pr)],hr.prototype,"input",void 0),S([O(1),k(Xt),i("ngx-decaf-crud-field",{label:"graph.node.utility.code.fields.timeoutMs.label",type:"number"}),Re({handle:"timeoutMs"}),D("design:type",Number)],hr.prototype,"timeoutMs",void 0),S([i("code-editor",{label:"graph.node.utility.code.fields.defaultCode.label",placeholder:"graph.node.utility.code.fields.defaultCode.placeholder"}),Re({handle:"defaultCode",userControlled:!0}),D("design:type",String)],hr.prototype,"defaultCode",void 0),S([b(),$e({handle:"result"}),D("design:type",Object)],hr.prototype,"result",void 0),hr=S([De("core.utility.code",{kind:"core.utility.code",category:"Utility",color:"#0d9488",icon:"ti-code",width:96,height:96,labels:["utility","code","sandbox","transform"],metadata:{title:"graph.node.utility.code.name",description:"graph.node.utility.code.description"}}),E()],hr);let fr=class extends Zn{execute(e){return{value:e.inputs.value??e.inputs}}};S([b(),Re({handle:"value"}),D("design:type",Object)],fr.prototype,"value",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.utility.delay.fields.timeoutMs.label",type:"number"}),Re({handle:"timeoutMs"}),D("design:type",Number)],fr.prototype,"timeoutMs",void 0),S([b(),$e({handle:"value"}),D("design:type",Object)],fr.prototype,"valueOut",void 0),fr=S([De("core.flow.delay",{kind:"core.flow.delay",category:"Utility",color:"#0d9488",icon:"ti-clock-hour-4",width:96,height:96,labels:["flow","delay","wait"],metadata:{title:"graph.node.utility.delay.name",description:"graph.node.utility.delay.description"}}),E()],fr);let gr=class extends Zn{execute(e,t){const o=e.inputs.value,n=this.level??"info";return t.logger[n](this.message??"Log node",{value:o}),{value:o}}};S([b(),Re({handle:"value"}),D("design:type",Object)],gr.prototype,"value",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.utility.log.fields.message.label",placeholder:"graph.node.utility.log.fields.message.placeholder",type:"textarea"}),Re({handle:"message"}),D("design:type",String)],gr.prototype,"message",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.utility.log.fields.level.label",placeholder:"graph.node.utility.log.fields.level.placeholder",type:"text"}),Re({handle:"level",userControlled:!0}),D("design:type",String)],gr.prototype,"level",void 0),S([b(),$e({handle:"value"}),D("design:type",Object)],gr.prototype,"valueOut",void 0),gr=S([De("core.flow.log",{kind:"core.flow.log",category:"Utility",color:"#0d9488",icon:"ti-terminal",width:96,height:96,labels:["flow","log","debug","utility"],metadata:{title:"graph.node.utility.log.name",description:"graph.node.utility.log.description"}}),E()],gr);let mr=class extends Zn{execute(e){return{result:{mapped:e.inputs.value??e.inputs}}}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.utility.map.fields.value.label",placeholder:"graph.node.utility.map.fields.value.placeholder",type:"textarea"}),Re({handle:"value"}),D("design:type",Object)],mr.prototype,"value",void 0),S([b(),$e({handle:"result"}),D("design:type",Object)],mr.prototype,"result",void 0),mr=S([De("core.utility.map",{kind:"core.utility.map",category:"Utility",color:"#0d9488",icon:"ti-arrows-right-left",width:96,height:96,labels:["utility","map","transform"],metadata:{title:"graph.node.utility.map.name",description:"graph.node.utility.map.description",mapper:{}}}),E()],mr);let yr=class extends Zn{execute(e,t){const o=e.inputs.value,n=this.level??"info";return t.logger[n](this.message??"Log node",{value:o}),{value:o}}};S([b(),Re({handle:"value"}),D("design:type",Object)],yr.prototype,"value",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.utility.utility_log.fields.message.label",placeholder:"graph.node.utility.utility_log.fields.message.placeholder",type:"textarea"}),Re({handle:"message"}),D("design:type",String)],yr.prototype,"message",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.utility.utility_log.fields.level.label",placeholder:"graph.node.utility.utility_log.fields.level.placeholder"}),Re({handle:"level",userControlled:!0,type:"string"}),D("design:type",String)],yr.prototype,"level",void 0),S([b(),$e({handle:"value"}),D("design:type",Object)],yr.prototype,"valueOut",void 0),yr=S([De("core.utility.log",{kind:"core.utility.log",category:"Utility",color:"#0d9488",icon:"ti-terminal",width:96,height:96,labels:["utility","log","debug","observability"],metadata:{title:"graph.node.utility.utility_log.name",description:"graph.node.utility.utility_log.description"}}),E()],yr);let wr=class extends Zn{execute(e){return{message:e.inputs.message??null,sessionId:e.inputs.sessionId??null,userId:e.inputs.userId??null}}};S([b(),$e({handle:"message"}),D("design:type",String)],wr.prototype,"message",void 0),S([b(),$e({handle:"sessionId"}),D("design:type",String)],wr.prototype,"sessionId",void 0),S([b(),$e({handle:"userId"}),D("design:type",String)],wr.prototype,"userId",void 0),wr=S([De("core.trigger.chat",{kind:"core.trigger.chat",category:"Trigger",color:"#3b82f6",icon:"ti-message-circle",width:96,height:96,labels:["trigger","chat","entrypoint"],metadata:{title:"graph.node.trigger.chat.name",description:"graph.node.trigger.chat.description",trigger:{type:"chat"}}}),E()],wr);let br=class extends Zn{execute(e){return{payload:e.inputs.payload??null}}};S([b(),$e({handle:"payload"}),D("design:type",Object)],br.prototype,"payload",void 0),br=S([De("core.trigger.event",{kind:"core.trigger.event",category:"Trigger",color:"#3b82f6",icon:"ti-broadcast",width:96,height:96,labels:["trigger","event","bus"],metadata:{title:"graph.node.trigger.event.name",description:"graph.node.trigger.event.description",trigger:{type:"event",topic:"default"}}}),E()],br);let vr=class extends Zn{execute(e){return{payload:e.inputs.payload??null}}};S([b(),Re({handle:"schema"}),i("ngx-decaf-model-builder",{label:"graph.node.trigger.form.fields.schema.label",placeholder:"graph.node.trigger.form.fields.schema.placeholder"}),D("design:type",Object)],vr.prototype,"schema",void 0),S([b(),$e({handle:"payload"}),D("design:type",Object)],vr.prototype,"payload",void 0),vr=S([De("core.trigger.form",{kind:"core.trigger.form",category:"Trigger",color:"#3b82f6",icon:"ti-forms",width:96,height:96,labels:["trigger","form","public"],metadata:{title:"graph.node.trigger.form.name",description:"graph.node.trigger.form.description",trigger:{type:"form",fields:[]}}}),E()],vr);let Ir=class extends Zn{execute(e){return{payload:e.inputs.payload??null}}};S([b(),$e({handle:"payload"}),D("design:type",Object)],Ir.prototype,"payload",void 0),Ir=S([De("core.trigger.manual",{kind:"core.trigger.manual",category:"Trigger",color:"#3b82f6",icon:"ti-hand-click",width:96,height:96,labels:["trigger","manual","entrypoint"],metadata:{title:"graph.node.trigger.manual.name",description:"graph.node.trigger.manual.description",trigger:{type:"manual",inputSchema:{}}}}),E()],Ir);let Er=class extends Zn{execute(e){return{payload:e.inputs.payload??null}}};S([b(),Re({handle:"cron"}),i("app-cron-selector-field",{label:"graph.node.trigger.schedule.fields.cron.label",placeholder:"graph.node.trigger.schedule.fields.cron.placeholder"}),D("design:type",String)],Er.prototype,"cron",void 0),S([b(),$e({handle:"payload"}),D("design:type",Object)],Er.prototype,"payload",void 0),Er=S([De("core.trigger.schedule",{kind:"core.trigger.schedule",category:"Trigger",color:"#3b82f6",icon:"ti-calendar-time",width:96,height:96,labels:["trigger","schedule","cron"],metadata:{title:"graph.node.trigger.schedule.name",description:"graph.node.trigger.schedule.description",trigger:{type:"schedule",schedule:"0 * * * *",timezone:"UTC"}}}),E()],Er);let Nr=class extends Zn{execute(e){return{payload:e.inputs.payload??null}}};S([b(),Re({handle:"schema"}),i("ngx-decaf-model-builder",{label:"graph.node.trigger.webhook.fields.schema.label",placeholder:"graph.node.trigger.webhook.fields.schema.placeholder"}),D("design:type",Object)],Nr.prototype,"schema",void 0),S([b(),$e({handle:"payload"}),D("design:type",Object)],Nr.prototype,"payload",void 0),Nr=S([De("core.trigger.webhook",{kind:"core.trigger.webhook",category:"Trigger",color:"#3b82f6",icon:"ti-webhook",width:96,height:96,labels:["trigger","webhook","http"],metadata:{title:"graph.node.trigger.webhook.name",description:"graph.node.trigger.webhook.description",trigger:{type:"webhook",path:"/webhook",method:"POST",auth:"none",responseMode:"onReceived"}}}),E()],Nr);let Or=class extends Zn{execute(e){return{response:"[Agent response] "+(e.inputs.prompt??""),actions:[]}}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.agent.agent.fields.prompt.label",placeholder:"graph.node.agent.agent.fields.prompt.placeholder",type:"textarea"}),Re({handle:"prompt"}),D("design:type",String)],Or.prototype,"prompt",void 0),S([b(),$e({handle:"response"}),D("design:type",String)],Or.prototype,"response",void 0),S([b(),$e({handle:"actions"}),D("design:type",Array)],Or.prototype,"actions",void 0),S([Ce({category:"model",handle:"model"}),D("design:type",Object)],Or.prototype,"model",void 0),S([Ce({category:"memory",handle:"memory"}),D("design:type",Object)],Or.prototype,"memory",void 0),S([Ce({category:"workspace",handle:"workspace"}),D("design:type",Object)],Or.prototype,"workspace",void 0),Or=S([De("core.agent",{kind:"core.agent",category:"Agent",width:140,height:120,labels:["agent","ai","orchestrator"],metadata:{title:"graph.node.agent.agent.name",description:"graph.node.agent.agent.description",shape:"rectangle"}}),E()],Or);const kr=[Or];function Ar(e,t,o,n){const r=t??o;if(null==e)return Math.min(o,r);const i=Number(e);if(!Number.isFinite(i)||0>=i)throw new no(n+" loop maxIterations must be a positive finite number");return Math.min(Math.floor(i),r)}function xr(e,t,o){const n=t.node.loop,r=t.metadata?.loop;if(!n?.body&&!r?.body)throw new no(o+" node is missing loop configuration (instance.loop.body)");const i=t=>{const o=e[t]??n?.[t]??r?.[t],i=Number(o);return void 0!==o&&Number.isFinite(i)?i:void 0},a=t=>{const o=e[t]??r?.[t];return"string"==typeof o?o:void 0};return{body:n?.body??r?.body,maxIterations:i("maxIterations"),timeoutMs:i("timeoutMs"),concurrency:i("concurrency"),condition:e.condition??r?.condition,inputPort:a("inputPort"),outputPort:a("outputPort"),itemPort:a("itemPort"),resultPort:a("resultPort"),statePort:a("statePort"),slice:i("slice")}}let _r=class extends Zn{async execute(e,t){const o=xr(this,t,"foreach"),n=e.inputs,r=n.items,i=Ar(o.maxIterations,t.limits?.maxForeachIterations,1e3,"foreach");if(!Array.isArray(r))throw new no("foreach input 'items' must be an array");const a=t.engine;if(!a)throw new to("foreach node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");const s=Number(n.slice??o.slice??1),d=Number.isFinite(s)&&s>0?Math.floor(s):1,l=d>1?Math.ceil(r.length/d):r.length;if(l>i)throw new ro(`foreach exceeded max iterations (${l} > ${i})`);const c=o.itemPort??"item",u=o.resultPort??"result",p=o.statePort??"state",h=o.body,f=[];let g=n.state,m=!1;await t.emit({type:ce.LOOP_STARTED});for(let e=0;l>e;e++){await t.emit({type:ce.LOOP_ITERATION_STARTED,iteration:e});const o=d>1?r.slice(e*d,e*d+d):r[e],n={[c]:o,index:e};d>1&&(n.slice=o),void 0!==g&&(n[p]=g);try{const r=await a.execute(h,n,{parentRunId:t.runId,path:[...t.path,"iteration:"+e],metadata:{item:o,index:e,slice:d},auth:t.auth},t);f.push(r.outputs[u]),void 0!==r.outputs[p]&&(g=r.outputs[p])}catch(o){if(o instanceof co){const n=o.details?.value;void 0!==n&&f.push(n),m=!0,await t.emit({type:ce.LOOP_ITERATION_COMPLETED,iteration:e,metadata:{broken:!0}});break}throw o}await t.emit({type:ce.LOOP_ITERATION_COMPLETED,iteration:e})}await t.emit({type:ce.LOOP_COMPLETED,metadata:{broken:m}});const y={results:f,completed:f,iterations:f.length,broken:m};return void 0!==g&&(y[p]=g),y}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.items.label",placeholder:"graph.node.loop.foreach.fields.items.placeholder",type:"textarea"}),Re({handle:"items"}),D("design:type",Array)],_r.prototype,"items",void 0),S([b(),i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.slice.label",placeholder:"graph.node.loop.foreach.fields.slice.placeholder",type:"number"}),Re({handle:"slice"}),D("design:type",Number)],_r.prototype,"slice",void 0),S([b(),$e({handle:"item"}),D("design:type",Object)],_r.prototype,"item",void 0),S([b(),Ce({handle:"loop",connectionRules:{allowSelf:!0,maxConnections:1}}),D("design:type",Object)],_r.prototype,"loop",void 0),S([b(),$e({handle:"completed"}),D("design:type",Array)],_r.prototype,"completed",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.maxIterations.label",type:"number"}),Re({handle:"maxIterations",userControlled:!0}),D("design:type",Number)],_r.prototype,"maxIterations",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.condition.label",type:"code"}),Re({handle:"condition",userControlled:!0}),D("design:type",Object)],_r.prototype,"condition",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.itemPort.label",type:"text"}),Re({handle:"itemPort",userControlled:!0}),D("design:type",String)],_r.prototype,"itemPort",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.resultPort.label",type:"text"}),Re({handle:"resultPort",userControlled:!0}),D("design:type",String)],_r.prototype,"resultPort",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.statePort.label",type:"text"}),Re({handle:"statePort",userControlled:!0}),D("design:type",String)],_r.prototype,"statePort",void 0),_r=S([De("graph-foreach-loop-node",{kind:"core.loop.foreach",category:"Loop",color:"#eab308",icon:"ti-repeat",width:120,height:140,labels:["loop","iteration","foreach"],metadata:{title:"graph.node.loop.foreach.name",description:"graph.node.loop.foreach.description",loop:{maxIterations:100,itemPort:"item",resultPort:"result",slice:1}}}),E()],_r);class Sr{constructor(){this.expressionEvaluator=new jo}evaluate(e,t){if(this.isConditionExpression(e))return this.expressionEvaluator.evaluate(e,t);const o=this.resolveValue(e.left,t),n=e.right;switch(e.type){case Zt.TRUTHY:return!!o;case Zt.FALSY:return!o;case Zt.EQUALS:return o===n;case Zt.NOT_EQUALS:return o!==n;case Zt.GREATER_THAN:return Number(o)>Number(n);case Zt.GREATER_THAN_OR_EQUAL:return Number(o)>=Number(n);case Zt.LESS_THAN:return Number(n)>Number(o);case Zt.LESS_THAN_OR_EQUAL:return Number(n)>=Number(o);case Zt.EXISTS:return null!=o;case Zt.CUSTOM:throw new to("Custom condition evaluators are not supported in v1","GRAPH_CUSTOM_CONDITION_UNSUPPORTED");default:throw new to(`Unknown condition type '${e.type}'`,"GRAPH_UNKNOWN_CONDITION_TYPE",{condition:e})}}async evaluateAsync(e,t,o,n){return Go(e)?Fo(e,n,o):this.evaluate(e,t)}resolveValue(e,t){if(!e)return t;const o=e.split(".");let n=t;for(const e of o){if(null==n)return;n=n[e]}return n}isConditionExpression(e){return"string"==typeof e.op}}let Dr=class extends Zn{async execute(e,t){const o=xr(this,t,"until"),n=e.inputs,r=Ar(o.maxIterations,t.limits?.maxLoopIterations,100,"until"),i=o.condition;if(!i)throw new no("until node is missing a condition");const a=o.statePort??"state",s=o.inputPort??a,d=o.outputPort??a,l=o.body,c=t.engine;if(!c)throw new to("until node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");let u=n.state,p=0;await t.emit({type:ce.LOOP_STARTED});let h=!1;do{if(p>=r)throw await t.emit({type:ce.LOOP_LIMIT_REACHED,iteration:p}),new ro(`until loop exceeded max iterations (${r})`);await t.emit({type:ce.LOOP_ITERATION_STARTED,iteration:p}),u=(await c.execute(l,{[s]:u,iteration:p},{parentRunId:t.runId,path:[...t.path,"iteration:"+p],auth:t.auth},t)).outputs[d],await t.emit({type:ce.LOOP_ITERATION_COMPLETED,iteration:p});const e=await(new Sr).evaluateAsync(i,u,t,{...n,state:u});await t.emit({type:ce.LOOP_CONDITION_EVALUATED,iteration:p,payload:{result:e}}),p++,h=e}while(!h);return await t.emit({type:ce.LOOP_COMPLETED}),{state:u,iterations:p}}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.state.label",placeholder:"graph.node.loop.until.fields.state.placeholder",type:"textarea"}),Re({handle:"state"}),D("design:type",Object)],Dr.prototype,"state",void 0),S([b(),$e({handle:"state"}),D("design:type",Object)],Dr.prototype,"stateOut",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.maxIterations.label",type:"number"}),Re({handle:"maxIterations",userControlled:!0}),D("design:type",Number)],Dr.prototype,"maxIterations",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.condition.label",type:"code"}),Re({handle:"condition",userControlled:!0}),D("design:type",Object)],Dr.prototype,"condition",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.statePort.label",type:"text"}),Re({handle:"statePort",userControlled:!0}),D("design:type",String)],Dr.prototype,"statePort",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.inputPort.label",type:"text"}),Re({handle:"inputPort",userControlled:!0}),D("design:type",String)],Dr.prototype,"inputPort",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.outputPort.label",type:"text"}),Re({handle:"outputPort",userControlled:!0}),D("design:type",String)],Dr.prototype,"outputPort",void 0),Dr=S([De("graph-until-loop-node",{kind:"core.loop.until",category:"Loop",color:"#eab308",icon:"ti-player-stop",width:96,height:96,labels:["loop","conditional","until"],metadata:{title:"graph.node.loop.until.name",description:"graph.node.loop.until.description",loop:{maxIterations:50,statePort:"state",condition:{type:"greaterThanOrEqual",left:"iteration",right:2}}}}),E()],Dr);let Pr=class extends Zn{async execute(e,t){const o=xr(this,t,"while"),n=e.inputs,r=Ar(o.maxIterations,t.limits?.maxLoopIterations,100,"while"),i=o.condition;if(!i)throw new no("while node is missing a condition");const a=o.statePort??"state",s=o.inputPort??a,d=o.outputPort??a,l=o.body,c=t.engine;if(!c)throw new to("while node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");let u=n.state,p=0;for(await t.emit({type:ce.LOOP_STARTED});await(new Sr).evaluateAsync(i,u,t,{...n,state:u});){if(p>=r)throw await t.emit({type:ce.LOOP_LIMIT_REACHED,iteration:p}),new ro(`while loop exceeded max iterations (${r})`);await t.emit({type:ce.LOOP_CONDITION_EVALUATED,iteration:p,payload:{result:!0}}),await t.emit({type:ce.LOOP_ITERATION_STARTED,iteration:p}),u=(await c.execute(l,{[s]:u,iteration:p},{parentRunId:t.runId,path:[...t.path,"iteration:"+p],auth:t.auth},t)).outputs[d],await t.emit({type:ce.LOOP_ITERATION_COMPLETED,iteration:p}),p++}return await t.emit({type:ce.LOOP_COMPLETED}),{state:u,iterations:p}}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.state.label",placeholder:"graph.node.loop.while.fields.state.placeholder",type:"textarea"}),Re({handle:"state"}),D("design:type",Object)],Pr.prototype,"state",void 0),S([b(),$e({handle:"state"}),D("design:type",Object)],Pr.prototype,"stateOut",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.maxIterations.label",type:"number"}),Re({handle:"maxIterations",userControlled:!0}),D("design:type",Number)],Pr.prototype,"maxIterations",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.condition.label",type:"code"}),Re({handle:"condition",userControlled:!0}),D("design:type",Object)],Pr.prototype,"condition",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.statePort.label",type:"text"}),Re({handle:"statePort",userControlled:!0}),D("design:type",String)],Pr.prototype,"statePort",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.inputPort.label",type:"text"}),Re({handle:"inputPort",userControlled:!0}),D("design:type",String)],Pr.prototype,"inputPort",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.outputPort.label",type:"text"}),Re({handle:"outputPort",userControlled:!0}),D("design:type",String)],Pr.prototype,"outputPort",void 0),Pr=S([De("graph-while-loop-node",{kind:"core.loop.while",category:"Loop",color:"#eab308",icon:"ti-arrows-loop",width:96,height:96,labels:["loop","conditional","while"],metadata:{title:"graph.node.loop.while.name",description:"graph.node.loop.while.description",loop:{maxIterations:50,statePort:"state",condition:{type:"lessThan",left:"iteration",right:3}}}}),E()],Pr);let Rr=class extends Zn{execute(e){const t=e.inputs;return{value:t?.value??null}}};S([$e({handle:"value",connectionRules:{allowMultiple:!0}}),D("design:type",Object)],Rr.prototype,"value",void 0),Rr=S([De("graph-input-value-node",{kind:"value",category:"Boundary",color:"#0f766e",icon:"ti-circle-plus",labels:["workflow","input","value"],metadata:{title:"graph.node.boundary.input.name",description:"graph.node.boundary.input.description"}}),E()],Rr);let $r=class extends Zn{execute(e){return{}}};function Cr(e,t,o,n={}){return{id:e,label:t,direction:o,...n}}function Tr(e){const t=e,o=ve(t),n=o?.metadata?.title;return Tt(t,n?{name:n}:{})}S([b(),Re({handle:"value"}),D("design:type",Object)],$r.prototype,"value",void 0),$r=S([De("graph-output-value-node",{kind:"result",category:"Boundary",color:"#0f766e",icon:"ti-circle-minus",width:96,height:96,labels:["workflow","output","value"],metadata:{title:"graph.node.boundary.output.name",description:"graph.node.boundary.output.description"}}),E()],$r);const Lr={kind:"core.loop.foreach",capabilities:["loop"],display:{name:"graph.node.loop.foreach.name",description:"graph.node.loop.foreach.description",category:"Loop",color:"#eab308",icon:{type:"catalogue",name:"ti-repeat"},width:120,height:140,labels:["loop","iteration","foreach"]},inputs:[Cr("items","graph.node.loop.foreach.ports.input.items.label","input",{required:!0,schema:{type:"array",items:{type:"any"}}}),Cr("slice","graph.node.loop.foreach.ports.input.slice.label","input",{schema:{type:"number",integer:!0,min:1}}),Cr("state","graph.node.loop.foreach.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[Cr("results","graph.node.loop.foreach.ports.output.results.label","output",{schema:{type:"array",items:{type:"any"}}}),Cr("completed","graph.node.loop.foreach.ports.output.completed.label","output",{schema:{type:"array",items:{type:"any"}}}),Cr("iterations","graph.node.loop.foreach.ports.output.iterations.label","output",{schema:{type:"number",integer:!0,min:0}}),Cr("broken","graph.node.loop.foreach.ports.output.broken.label","output",{schema:{type:"boolean"}}),Cr("state","graph.node.loop.foreach.ports.output.state.label","output",{schema:{type:"any"}})],parameters:[{type:"number",id:"maxIterations",label:"graph.node.loop.foreach.fields.maxIterations.label",integer:!0,min:1},{type:"object",id:"condition",label:"graph.node.loop.foreach.fields.condition.label"},{type:"string",id:"itemPort",label:"graph.node.loop.foreach.fields.itemPort.label"},{type:"string",id:"resultPort",label:"graph.node.loop.foreach.fields.resultPort.label"},{type:"string",id:"statePort",label:"graph.node.loop.foreach.fields.statePort.label"},{type:"number",id:"slice",label:"graph.node.loop.foreach.fields.slice.label",integer:!0,min:1}]},Mr={kind:"core.loop.while",capabilities:["loop"],display:{name:"graph.node.loop.while.name",description:"graph.node.loop.while.description",category:"Loop",color:"#eab308",icon:{type:"catalogue",name:"ti-arrows-loop"},width:120,height:140,labels:["loop","conditional","while"]},inputs:[Cr("state","graph.node.loop.while.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[Cr("state","graph.node.loop.while.ports.output.state.label","output",{schema:{type:"any"}}),Cr("iterations","graph.node.loop.while.ports.output.iterations.label","output",{schema:{type:"number",integer:!0,min:0}})],parameters:[{type:"number",id:"maxIterations",label:"graph.node.loop.while.fields.maxIterations.label",integer:!0,min:1},{type:"object",id:"condition",label:"graph.node.loop.while.fields.condition.label",required:!0},{type:"string",id:"statePort",label:"graph.node.loop.while.fields.statePort.label"},{type:"string",id:"inputPort",label:"graph.node.loop.while.fields.inputPort.label"},{type:"string",id:"outputPort",label:"graph.node.loop.while.fields.outputPort.label"}]},jr={kind:"core.loop.until",capabilities:["loop"],display:{name:"graph.node.loop.until.name",description:"graph.node.loop.until.description",category:"Loop",color:"#eab308",icon:{type:"catalogue",name:"ti-player-stop"},width:120,height:140,labels:["loop","conditional","until"]},inputs:[Cr("state","graph.node.loop.until.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[Cr("state","graph.node.loop.until.ports.output.state.label","output",{schema:{type:"any"}}),Cr("iterations","graph.node.loop.until.ports.output.iterations.label","output",{schema:{type:"number",integer:!0,min:0}})],parameters:[{type:"number",id:"maxIterations",label:"graph.node.loop.until.fields.maxIterations.label",integer:!0,min:1},{type:"object",id:"condition",label:"graph.node.loop.until.fields.condition.label",required:!0},{type:"string",id:"statePort",label:"graph.node.loop.until.fields.statePort.label"},{type:"string",id:"inputPort",label:"graph.node.loop.until.fields.inputPort.label"},{type:"string",id:"outputPort",label:"graph.node.loop.until.fields.outputPort.label"}]},Gr=[Tr(Rr),Tr($r),Tr(Ir),Tr(Nr),Tr(Er),Tr(br),Tr(vr),Tr(wr),(Ur=Tr(rr),{...Ur,dynamicPorts:[{type:"togglePort",parameter:"else",equals:!0,port:{id:"else",label:"graph.node.flow_control.if.ports.output.else.label",direction:"output",schema:{type:"any"}}}]}),(e=>({...e,outputs:[],parameters:[...e.parameters,{type:"collection",id:"cases",label:"graph.node.flow_control.switch.fields.cases.label",required:!0,itemIdPath:"outputPort",itemLabelPath:"label"},{type:"boolean",id:"hasDefault",label:"graph.node.flow_control.switch.fields.hasDefault.label",defaultValue:!1},{type:"object",id:"switch",label:"graph.node.flow_control.switch.fields.switch.label",required:!1}],dynamicPorts:[{type:"repeatFromParameter",parameter:"cases",itemIdPath:"outputPort",itemLabelPath:"label",direction:"output",portIdTemplate:"${id}",defaultPort:{id:"case",label:"graph.node.flow_control.switch.ports.output.case.label",direction:"output",schema:{type:"any"}}},{type:"togglePort",parameter:"hasDefault",equals:!0,port:{id:"default",label:"graph.node.flow_control.switch.ports.output.default.label",direction:"output",schema:{type:"any"}}}]}))(Tr(ir)),Tr(mr),Tr(fr),Tr(or),Tr(nr),Tr(hr),Tr(gr),Tr(yr),Tr(er),Tr(Or),Lr,Mr,jr];var Ur;const Fr=Object.fromEntries(Gr.map(e=>[e.kind,e])),Br=[Ir,Nr,Er,br,vr,wr],Wr=[rr,ir,fr,or,nr,gr,er],qr=[hr,mr,yr],Hr=[_r,Pr,Dr],Kr=[Rr,$r],Vr={value:Rr,result:$r,"core.trigger.manual":Ir,"core.trigger.webhook":Nr,"core.trigger.schedule":Er,"core.trigger.event":br,"core.trigger.form":vr,"core.trigger.chat":wr,"core.flow.if":rr,"core.flow.switch":ir,"core.utility.map":mr,"core.flow.delay":fr,"core.flow.errorBoundary":or,"core.flow.humanApproval":nr,"core.utility.code":hr,"core.flow.log":gr,"core.utility.log":yr,"core.flow.break":er,"core.agent":Or,"core.loop.foreach":_r,"core.loop.while":Pr,"core.loop.until":Dr};function zr(e){return{execute:(t,o)=>e.instantiate({...Qn(o.node),...t.parameters,...o.node.state??{}}).execute(t,o)}}function Jr(){const e=[];for(const[t,o]of Object.entries(Fr)){const n=Vr[t];n&&e.push(Xn({manifest:o,executor:zr(n)}))}return e}function Xr(e,...t){for(const o of Jr())e.register(o,{},...t);return e}class Yr{resolve(e){const t=this.createValidator(e);return{name:e.name,required:e.required,validate:t}}resolveAll(e){const t={};for(const o of e)t[o.name]=this.resolve(o);return t}createValidator(e){switch((e.type??e.designType??"").toLowerCase()){case"string":return e=>"string"==typeof e;case"number":return e=>"number"==typeof e;case"boolean":return e=>"boolean"==typeof e;case"date":return e=>e instanceof Date||"string"==typeof e&&!isNaN(Date.parse(e));case"array":return e=>Array.isArray(e);case"bigint":return e=>"bigint"==typeof e;default:return()=>!0}}}class Qr{constructor(e){this.resolver=e}validateWorkflowInputs(e,t){this.validatePorts(e.inputs,t,"workflow input")}validateWorkflowOutputs(e,t){this.validatePorts(e.outputs,t,"workflow output")}validateNodeInputs(e,t){const o=(e.ports??[]).filter(e=>"input"===e.direction);this.validatePorts(o,t,`node '${e.name}' input`)}validateNodeOutputs(e,t){const o=(e.ports??[]).filter(e=>"output"===e.direction);this.validatePorts(o,t,`node '${e.name}' output`)}validatePorts(e,t,o){if(e)for(const n of e){const e=Object.prototype.hasOwnProperty.call(t,n.name);if(n.required&&!e)throw new no(`Missing required ${o} port '${n.name}'`);if(e&&!this.resolver.resolve(n).validate(t[n.name]))throw new no(`Invalid value for ${o} port '${n.name}'`)}}}const Zr=["node","definition","executor","execute","ports","component"];function ei(e,t,o,n){return{code:e,path:t,message:o,...void 0!==n?.nodeId?{nodeId:n.nodeId}:{},...void 0!==n?.edgeId?{edgeId:n.edgeId}:{},...n?.details?{details:n.details}:{}}}function ti(e,t){const o=[];for(const n of Object.keys(e))Zr.includes(n)&&o.push(ei("document.forbidden-field",`${t}.${n}`,`Field '${n}' is not accepted in a canonical workflow document: node, definition, executor, execute, ports and component fields are rejected at the boundary`,{details:{field:n}}));return o}function oi(e,t){t.push(...ti(e,"$")),e.inputs.forEach((e,o)=>t.push(...ti(e,`inputs[${o}]`))),e.outputs.forEach((e,o)=>t.push(...ti(e,`outputs[${o}]`)));for(const o of e.nodes)t.push(...ti(o,`nodes[${o.id}]`)),o.loop&&(t.push(...ti(o.loop,`nodes[${o.id}].loop`)),oi(o.loop.body,t));for(const o of e.edges)t.push(...ti(o,`edges[${o.id}]`))}function ni(e,t){const o=[];e.nodes.length>t.maxNodes&&o.push(ei("document.limit.nodes","$.nodes",`Document declares ${e.nodes.length} nodes; at most ${t.maxNodes} are allowed`,{details:{count:e.nodes.length,limit:t.maxNodes}})),e.edges.length>t.maxEdges&&o.push(ei("document.limit.edges","$.edges",`Document declares ${e.edges.length} edges; at most ${t.maxEdges} are allowed`,{details:{count:e.edges.length,limit:t.maxEdges}}));const n=ri(e);n>t.maxNestingDepth&&o.push(ei("document.limit.depth","$.nodes",`Document nests loop bodies ${n} levels deep; at most ${t.maxNestingDepth} levels are allowed`,{details:{depth:n,limit:t.maxNestingDepth}}));const r=Buffer.byteLength(JSON.stringify(e),"utf8");return r>t.maxDocumentBytes&&o.push(ei("document.limit.size","$",`Document serializes to ${r} bytes; at most ${t.maxDocumentBytes} bytes are allowed`,{details:{bytes:r,limit:t.maxDocumentBytes}})),o}function ri(e,t=0){let o=t;for(const n of e.nodes)n.loop?.body&&(o=Math.max(o,ri(n.loop.body,t+1)));return o}async function ii(e,t,...o){const n=[];for(const r of e.nodes)t.has(r.kind,...o)||n.push(ei("node.unknown-kind",`nodes[${r.id}].kind`,`Node '${r.id}' references kind '${r.kind}' which is not registered in the backend catalogue`,{nodeId:r.id,details:{kind:r.kind}})),r.loop?.body&&n.push(...await ii(r.loop.body,t,...o));return n}async function ai(e,t={},...o){const n={...ar,...t.limits},r=[];if(!pt(e))return r.push(ei("document.shape","$","Payload is not a canonical GraphWorkflowDocument: id and name must be strings and inputs, outputs, nodes and edges must be arrays")),{valid:!1,issues:r};if(!Ue(e))return r.push(ei("document.json-unsafe","$","Document contains JSON-unsafe values: functions, class instances, undefined, NaN/Infinity, symbol keys and unsafe prototype keys (__proto__/prototype/constructor) are rejected")),{valid:!1,issues:r};oi(e,r),r.push(...(e=>{const t=[],o=new Set;for(const n of[...e.inputs,...e.outputs])o.has(n.id)?t.push(ei("document.duplicate-port-id",`ports[${n.id}]`,`Workflow port '${n.id}' is declared more than once; workflow port ids must be unique`)):o.add(n.id);const n=new Set;for(const o of e.nodes)n.has(o.id)?t.push(ei("document.duplicate-node-id",`nodes[${o.id}]`,`Node '${o.id}' is declared more than once; node ids must be unique`,{nodeId:o.id})):n.add(o.id);const r=new Set;for(const o of e.edges)r.has(o.id)?t.push(ei("document.duplicate-edge-id",`edges[${o.id}]`,`Edge '${o.id}' is declared more than once; edge ids must be unique`,{edgeId:o.id})):r.add(o.id);return t})(e)),r.push(...ni(e,n)),mn(e,r);try{ot(e)}catch(e){const t=e instanceof A?e.message:e+"";r.push(ei("document.structure","$",t))}return t.catalogue&&r.push(...await ii(e,t.catalogue,...o)),{valid:0===r.length,issues:r}}class si{constructor(e,t){this.iteration=e,this.metadata=t}}function di(e,t,o={}){const n=e?.owner??null;return!n||n===t||(null==t||""===t)&&!0===o.allowAnonymousAccess}function li(e,t){return(e?.owner??null)===(t??null)}function ci(e,t,o){if(!li(e,t))throw new L(`${o.resourceKind} '${o.resourceId}' is owned by another user`)}function ui(e,t,o){if(!di(e,t,o))throw new L(`${o.resourceKind} '${o.resourceId}' is owned by another user`)}function pi(e){if(null===e||"object"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(e=>pi(e)).join(",")}]`;const t=e;return`{${Object.keys(t).filter(e=>void 0!==t[e]).sort().map(e=>`${JSON.stringify(e)}:${pi(t[e])}`).join(",")}}`}function hi(e){return Y("sha256").update(pi(e)).digest("hex")}class fi{constructor(e={}){this.events=new Map,this.listeners=new Map,this.limits={...ue,...e}}async append(e){let t=this.events.get(e.runId);t||(t=[],this.events.set(e.runId,t)),t.push(e),this.enforceRetention(t);for(const t of this.listeners.get(e.runId)??[])try{t(e)}catch{}}async listAfter(e,t){const o=this.events.get(e);return o?o.filter(e=>e.sequence>t):[]}subscribe(e,t){let o=this.listeners.get(e);return o||(o=new Set,this.listeners.set(e,o)),o.add(t),()=>{o.delete(t),0===o.size&&this.listeners.delete(e)}}release(e){this.events.delete(e),this.listeners.delete(e)}enforceRetention(e){const t=this.limits.maxEventsPerRun;for(;e.length>t;){const t=e.findIndex(e=>!he(e.type));if(-1===t)break;e.splice(t,1)}}}function gi(e){return new jt({runId:e.runId,workflowId:e.workflowId,...e.ownerUser?{owner:e.ownerUser}:{},status:e.status,...e.documentFingerprint?{documentFingerprint:e.documentFingerprint}:{},...void 0!==e.result?{result:mi(e.result)}:{},...e.error?{error:mi(e.error)}:{},createdAt:new Date(e.createdAt),...e.startedAt?{startedAt:new Date(e.startedAt)}:{},...e.finishedAt?{finishedAt:new Date(e.finishedAt)}:{}})}function mi(e){if(null!=e)return JSON.parse(JSON.stringify(e))}class yi{constructor(){this.runs=new Map}async saveRun(e){this.runs.set(e.runId,{...e})}async readRun(e){const t=this.runs.get(e);return t?{...t}:null}async listRuns(e){return[...this.runs.values()].filter(t=>t.workflowId===e).map(e=>gi(e))}release(e){this.runs.delete(e)}}class wi{constructor(e,t={}){this.sequences=new Map,this.chains=new Map,this.store=e,this.limits={...ue,...t}}async publish(e){const t=e.runId,o=(this.sequences.get(t)??0)+1;this.sequences.set(t,o);const n={...e,payload:this.limitPayload(e.payload),sequence:o,timestamp:(new Date).toISOString()},r=(this.chains.get(t)??Promise.resolve()).then(()=>this.store.append(n));return this.chains.set(t,r.catch(()=>{})),await r,n}lastSequence(e){return this.sequences.get(e)??0}release(e){this.sequences.delete(e),this.chains.delete(e)}limitPayload(e){if(void 0===e)return;let t;try{t=JSON.stringify(e)}catch{return{nonSerializable:!0}}return t.length>this.limits.maxEventPayloadBytes?{truncated:!0,reason:"event payload exceeds the configured byte limit",bytes:t.length}:e}}class bi{constructor(e,t,o,n={},r={}){this.controllers=new Map,this.completions=new Map,this.timeouts=new Map,this.engine=e,this.runStore=t,this.publisher=o,this.hooks=n,this.limits={...ue,...r}}begin(e){const t=this.controllers.get(e);if(t)return t;const o=new AbortController;return this.controllers.set(e,o),o}abort(e,t){const o=this.controllers.get(e);return!!o&&(o.signal.aborted||o.abort(t),!0)}isAborted(e){return!0===this.controllers.get(e)?.signal.aborted}abortReason(e){const t=this.controllers.get(e)?.signal;if(t?.aborted)return"timeout"===t.reason?"timeout":"user"}waitFor(e){return this.completions.get(e)}schedule(e,t,o,...n){const r=this.completions.get(e.runId);if(r)return r;const i=this.runExecution({...e},t,o,...n).catch(async t=>{const o=vi(t);try{await this.emitTerminal({...e},ce.WORKFLOW_FAILED,o)}catch{}return await this.finalize({...e},"failed",void 0,o,...n)});return this.completions.set(e.runId,i),i}release(e){this.controllers.delete(e),this.completions.delete(e);const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.publisher.release(e)}armTimeout(e){const t=setTimeout(()=>{this.timeouts.delete(e),this.abort(e,"timeout")},this.limits.executionTimeoutMs);this.timeouts.set(e,t)}async runExecution(e,t,o,...n){const r=e.runId;let i,a,s=!1;const d=this.engine.observe({refresh:async t=>{t.runId===r&&(t.error&&(i=t.error),he((await this.publisher.publish(this.envelopeOf(e,t))).type)?s=!0:t.type===ce.WORKFLOW_STARTED&&"validating"===e.status&&(e.status="running",await this.persist(e,...n)))}});this.armTimeout(r);try{if(this.isAborted(r)){const t={name:"GraphRunCancelledError",message:`Graph run '${r}' was cancelled before execution started`,code:"GRAPH_RUN_CANCELLED"};return i=t,await this.emitTerminal(e,ce.WORKFLOW_CANCELLED,t),s=!0,await this.finalize(e,"cancelled",void 0,t,...n)}let d,l;e.status="validating",e.startedAt=(new Date).toISOString(),await this.persist(e,...n);try{({document:d,fingerprint:l}=await t(...n)),e.documentFingerprint=l,await this.persist(e,...n)}catch(t){const o=vi(t);return i=o,s||(await this.emitTerminal(e,ce.WORKFLOW_FAILED,o),s=!0),await this.finalize(e,"failed",void 0,o,...n)}if(this.isAborted(r)){const t={name:"GraphRunCancelledError",message:`Graph run '${r}' was cancelled before execution started`,code:"GRAPH_RUN_CANCELLED"};return i=t,s||(await this.emitTerminal(e,ce.WORKFLOW_CANCELLED,t),s=!0),await this.finalize(e,"cancelled",void 0,t,...n)}try{a=await this.engine.execute(d,o,{runId:r,abortSignal:this.controllers.get(r)?.signal,metadata:{documentFingerprint:l}},...n)}catch(e){i=vi(e)}const c=this.abortReason(r);let u,p;return"timeout"===c?(u="failed",p=i??{name:"GraphRunTimeoutError",message:`Graph run '${r}' exceeded the configured execution timeout of ${this.limits.executionTimeoutMs}ms`,code:"GRAPH_RUN_TIMEOUT"}):"user"===c?(u="cancelled",p=i):a?.status===se.SUCCEEDED?u="succeeded":a?.status===se.CANCELLED?(u="cancelled",p=i):(u="failed",p=i??vi(new to(a?`Graph run '${r}' failed`:`Graph run '${r}' failed without a result`,"GRAPH_RUN_FAILED",{runId:r}))),s||await this.emitTerminal(e,"succeeded"===u?ce.WORKFLOW_COMPLETED:"cancelled"===u?ce.WORKFLOW_CANCELLED:ce.WORKFLOW_FAILED,p),await this.finalize(e,u,a,p,...n)}finally{d();const e=this.timeouts.get(r);e&&(clearTimeout(e),this.timeouts.delete(r))}}async emitTerminal(e,t,o){await this.publisher.publish({runId:e.runId,workflowId:e.workflowId,type:t,error:o})}async finalize(e,t,o,n,...r){e.status=t,o&&(e.result=o),n&&(e.error=n),e.startedAt||(e.startedAt=(new Date).toISOString()),e.finishedAt=(new Date).toISOString(),await this.persist(e,...r);try{await(this.hooks.onRunCompleted?.(e,o))}catch{}return e}async persist(e,...t){await this.runStore.saveRun({...e},...t)}envelopeOf(e,t){return{runId:e.runId,workflowId:t.workflowId??e.workflowId,type:t.type,nodeId:t.nodeId,edgeId:t.edgeId,payload:void 0===t.payload?void 0:Ge(t.payload)?t.payload:{nonSerializable:!0},error:t.error,parentRunId:t.parentRunId,path:t.path}}}function vi(e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack,code:e.graphCode??("number"==typeof e.code?e.code+"":e.code)}:{name:"UnknownError",message:e+""}}class Ii{constructor(e,t,o,n={}){this.activeByCaller=new Map,this.callerKeysByRun=new Map,this.releaseTimers=new Map,this.engine=e,this.runStore=t,this.eventStore=o,this.publisher=new wi(o,n.limits),this.executor=new bi(e,t,this.publisher,{onRunCompleted:n.onRunCompleted},n.limits),this.options={...n,limits:{...ue,...n.limits}}}get limits(){return this.options.limits}async createRun(e,t,o,...n){this.validateCreateRequest(e);const r=e.workflowId??e.workflow?.id??"";if(!r)throw new A("Graph run request must carry a workflow document with an id or a saved workflowId");if(e.workflowId&&!this.options.documentResolver)throw new A("Graph run requests by workflowId require a document resolver");const i=o??t??"anonymous",a=this.activeByCaller.get(i)??new Set;if(a.size>=this.options.limits.maxConcurrentRuns)throw new A(`Graph run rejected: the configured limit of ${this.options.limits.maxConcurrentRuns} concurrent runs per caller is exhausted`);const s=this.generateRunId(),d={runId:s,workflowId:r,ownerUser:t,status:"queued",createdAt:(new Date).toISOString()};this.executor.begin(s),await this.runStore.saveRun({...d},...n);const l=this.documentProviderFor(e,t);return a.add(s),this.activeByCaller.set(i,a),this.callerKeysByRun.set(s,i),this.executor.schedule(d,l,e.inputs??{},...n).catch(()=>{}).finally(()=>this.finishActiveRun(s)),d}async getRun(e,t,...o){const n=await this.runStore.readRun(e,...o);if(!n)throw new _(`No graph run found for runId '${e}'`);return this.assertOwnership(n,t),n}async listRunsByWorkflow(e,t,...o){return(await this.runStore.listRuns(e,...o)).filter(e=>di({owner:e.owner},t,{allowAnonymousAccess:!0===this.options.allowAnonymousAccess})).sort((e,t)=>{const o=e.updatedAt instanceof Date?e.updatedAt.getTime():NaN,n=t.updatedAt instanceof Date?t.updatedAt.getTime():NaN;return(Number.isFinite(n)?n:0)-(Number.isFinite(o)?o:0)})}async cancelRun(e,t,...o){const n=await this.runStore.readRun(e,...o);if(!n)throw new _(`No graph run found for runId '${e}'`);return this.assertWriteOwnership(n,t),"succeeded"===(r=n.status)||"failed"===r||"cancelled"===r||(this.executor.abort(e,"user"),n.status="cancelled",n.finishedAt=(new Date).toISOString(),await this.runStore.saveRun({...n},...o)),n;var r}async resumeRun(e,t,o,...n){const r=await this.runStore.readRun(e,...n);if(!r)throw new _(`No graph run found for runId '${e}'`);this.assertWriteOwnership(r,o);const i=this.engine.backend,a=i.resume;if("function"!=typeof a)throw new to(`Graph execution backend '${i.constructor?.name??"GraphExecutionBackend"}' does not support resume`,"GRAPH_RESUME_UNSUPPORTED_BACKEND",{runId:e});let s;try{s=await a.call(i,e,t,...n)}catch(e){throw(d=e)instanceof to?new to(d.message,d.graphCode):d}var d;const l={...s,runId:e,caller:o};return await this.publisher.publish({runId:e,workflowId:r.workflowId,type:ce.WORKFLOW_RESUMED,payload:l}),l}async listEvents(e,t,o,...n){return await this.getRun(e,o,...n),this.eventStore.listAfter(e,t)}async subscribeEvents(e,t,o,...n){return await this.getRun(e,t,...n),this.eventStore.subscribe(e,o)}subscribeRunEvents(e,t){return this.eventStore.subscribe(e.runId,t)}async waitForRun(e,t,...o){const n=this.executor.waitFor(e);return n&&await n,this.getRun(e,t,...o)}async executeAndWait(e,t,o,...n){const r=await this.createRun(e,t,o,...n);return this.waitForRun(r.runId,t,...n)}release(e){this.finishActiveRun(e);const t=this.releaseTimers.get(e);t&&(clearTimeout(t),this.releaseTimers.delete(e)),this.executor.release(e),this.eventStore.release?.(e)}finishActiveRun(e){const t=this.callerKeysByRun.get(e);if(void 0!==t){this.callerKeysByRun.delete(e);const o=this.activeByCaller.get(t);o&&(o.delete(e),0===o.size&&this.activeByCaller.delete(t))}if(this.releaseTimers.has(e))return;const o=setTimeout(()=>{this.releaseTimers.delete(e),this.release(e)},this.options.limits.eventReplayWindowMs);o.unref?.(),this.releaseTimers.set(e,o)}validateCreateRequest(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new A("Graph run request must be an object carrying either a workflow document or a workflowId plus inputs");const t=void 0!==e.workflow,o=void 0!==e.workflowId;if(t&&o)throw new A("Graph run request is ambiguous: supply either an unsaved workflow document or a saved workflowId, not both");if(!t&&!o)throw new A("Graph run request must supply either an unsaved workflow document or a saved workflowId");if(t&&!pt(e.workflow))throw new A("Graph run request carries a payload that is not a canonical GraphWorkflowDocument");if(void 0!==e.inputs&&!Ue(e.inputs))throw new A("Graph run inputs must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys and unsafe prototype keys (__proto__/prototype/constructor) are rejected");const n=(e=>{try{return JSON.stringify(e)?.length??0}catch{return Number.MAX_SAFE_INTEGER}})(e);if(n>this.options.limits.maxRequestBytes)throw new A(`Graph run request of ${n} bytes exceeds the configured limit of ${this.options.limits.maxRequestBytes} bytes`)}documentProviderFor(e,t){if(e.workflow){const t=e.workflow;return async()=>({document:t,fingerprint:hi(t)})}const o=e.workflowId;return async(...e)=>{const n=this.options.documentResolver;if(!n)throw new A("Graph run requests by workflowId require a document resolver");const r=await n.resolve(o,t,...e);return{document:r,fingerprint:hi(r)}}}assertOwnership(e,t){ui({owner:e.ownerUser},t,{allowAnonymousAccess:!0===this.options.allowAnonymousAccess,resourceKind:"Graph run",resourceId:e.runId})}assertWriteOwnership(e,t){ci({owner:e.ownerUser},t,{resourceKind:"Graph run",resourceId:e.runId})}generateRunId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new so("Cannot generate a graph run id: crypto.randomUUID is unavailable in this runtime",{runtime:typeof globalThis.crypto});return e.randomUUID()}}function Ei(e){if(!e)return;let t;try{t=e.cache?.user}catch{t=void 0}if(null==t)try{t=e.get("user")}catch{t=void 0}return"string"==typeof t&&t.length>0?t:void 0}function Ni(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&pt(e.document)&&!pt(e)}function Oi(e){return JSON.parse(JSON.stringify(e))}function ki(e){if(null==e)return 0;let t;try{t=e.getTime()}catch{return 0}return Number.isFinite(t)?t:0}let Ai=class extends H{constructor(e){super(Gt),this.catalogue=e}get limits(){return{...ar,...sr.graph.workflows.limits??{}}}get allowAnonymousAccess(){return!0===sr.graph.workflows.allowAnonymousAccess}async saveDocument(e,t,...o){const{ctx:n,ctxArgs:r}=(await this.logCtx(o,"saveDocument",!0)).for(this.saveDocument);if(!pt(t))throw new A("Payload is not a canonical GraphWorkflowDocument: id and name must be strings and inputs, outputs, nodes and edges must be arrays");if(t.id!==e)throw new A(`Document id '${t.id}' does not match the workflow id '${e}' from the request path`);const i=await this.validateDocument(t,n);if(!i.valid)throw new po(i.issues);const a=Ei(n),s=await this.readExistingForWrite(e,r);s&&this.assertWriteOwnership(e,s,a);const d=new Date;if(s)return s.name=t.name,s.document=Oi(t),s.updatedAt=d,this.update(s,...r);const l=new Gt({workflowId:e,name:t.name,document:Oi(t),...a?{owner:a}:{},updatedAt:d});return this.create(l,...r)}async getDocument(e,...t){const{ctx:o,ctxArgs:n}=(await this.logCtx(t,"getDocument",!0)).for(this.getDocument);let r;try{r=await this.read(e,...n)}catch{r=null}if(!r)throw new _(`No graph workflow found for workflowId '${e}'`);if(this.assertOwnership(e,r,Ei(o)),r.document)return Oi(r.document);throw new _(`Graph workflow '${e}' has no canonical document; legacy definition/state snapshots are no longer supported (DECAF-50 \xa74.26 R2-2)`)}async listWorkflows(...e){const{ctx:t,ctxArgs:o}=(await this.logCtx(e,"listWorkflows",!0)).for(this.listWorkflows),n=await this.listBy("workflowId",K.ASC,...o),r=Ei(t);return n.filter(e=>di(e,r,{allowAnonymousAccess:this.allowAnonymousAccess})).sort((e,t)=>ki(t.updatedAt)-ki(e.updatedAt))}async assertAccess(e,...t){const{ctx:o,ctxArgs:n}=(await this.logCtx(t,"assertAccess",!0)).for(this.assertAccess);let r;try{r=await this.read(e,...n)}catch{r=null}if(!r)throw new _(`No graph workflow found for workflowId '${e}'`);return this.assertOwnership(e,r,Ei(o)),r}async validateDocument(e,...t){const{ctx:o}=(await this.logCtx(t,"validateDocument",!0)).for(this.validateDocument);return await ai(e,{limits:this.limits,...this.catalogue?{catalogue:this.catalogue}:{}},o)}async saveSnapshot(e,t,...o){const{ctx:n,ctxArgs:r}=(await this.logCtx(o,"saveSnapshot",!0)).for(this.saveSnapshot);if(!Ue(t))throw new A("Workflow snapshot payload must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys and unsafe prototype keys (__proto__/prototype/constructor) are rejected");if(!Ni(t))throw new A("Workflow snapshots must wrap a canonical GraphWorkflowDocument ({ document, editor?, metadata? }): legacy definition/state snapshots are no longer accepted; save canonical documents via PUT /graph/workflows/{workflowId}");const i=Ei(n),a=await this.readExistingForWrite(e,r);a&&this.assertWriteOwnership(e,a,i);const s=new Date;if(a)return a.snapshot=t,await this.applyCanonicalWrapper(a,t,n),a.updatedAt=s,this.update(a,...r);const d=new Gt({workflowId:e,snapshot:t,...i?{owner:i}:{},updatedAt:s});return await this.applyCanonicalWrapper(d,t,n),this.create(d,...r)}async loadSnapshot(e,...t){const{ctx:o,ctxArgs:n}=(await this.logCtx(t,"loadSnapshot",!0)).for(this.loadSnapshot);try{const t=await this.read(e,...n);return this.assertOwnership(e,t,Ei(o)),t}catch{return null}}async readExistingForWrite(e,t){try{return await this.read(e,...t)}catch(e){if(e instanceof _)return null;throw e}}assertOwnership(e,t,o){ui(t??null,o??null,{allowAnonymousAccess:this.allowAnonymousAccess,resourceKind:"Graph workflow",resourceId:e})}assertWriteOwnership(e,t,o){ci(t??null,o??null,{resourceKind:"Graph workflow",resourceId:e})}async applyCanonicalWrapper(e,t,o){if(!Ni(t))return;if(t.document.id!==e.workflowId)throw new A(`Document id '${t.document.id}' does not match the workflow id '${e.workflowId}' from the request path`);const n=await ai(t.document,{limits:this.limits,...this.catalogue?{catalogue:this.catalogue}:{}},o);if(!n.valid)throw new po(n.issues);e.document=Oi(t.document),e.name=t.document.name}};Ai=S([F(Gt),D("design:paramtypes",[Function])],Ai);let xi=class extends H{constructor(){super(jt)}async saveRun(e,...t){const{ctxArgs:o}=(await this.logCtx(t,"saveRun",!0)).for(this.saveRun),n=gi(e);let r;try{r=await super.read(e.runId,...o)}catch{r=null}if(r)return r.workflowId=n.workflowId,r.owner=n.owner,r.status=n.status,r.documentFingerprint=n.documentFingerprint,r.result=n.result,r.error=n.error,r.startedAt=n.startedAt,r.finishedAt=n.finishedAt,void await this.update(r,...o);await this.create(n,...o)}async readRun(e,...t){const{ctxArgs:o}=(await this.logCtx(t,"readRun",!0)).for(this.readRun);try{return(e=>{const t=e.result;return{runId:e.runId,workflowId:e.workflowId,ownerUser:e.owner??null,status:(o=e.status,"string"==typeof o&&["queued","validating","running","succeeded","failed","cancelled"].includes(o)?e.status:"failed"),createdAt:e.createdAt.toISOString(),...e.startedAt?{startedAt:e.startedAt.toISOString()}:{},...e.finishedAt?{finishedAt:e.finishedAt.toISOString()}:{},...t?{result:t}:{},...e.error?{error:e.error}:{},...e.documentFingerprint?{documentFingerprint:e.documentFingerprint}:{}};var o})(await super.read(e,...o))}catch{return null}}async listRuns(e,...t){const{ctxArgs:o}=(await this.logCtx(t,"listRuns",!0)).for(this.listRuns);return await this.findBy("workflowId",e,...o)}};xi=S([F(jt),D("design:paramtypes",[])],xi);class _i{map(e){const t={};for(const[o,n]of Object.entries(e.nodeResults))t[o]={status:n.status,startedAt:n.startedAt?.toISOString(),finishedAt:n.finishedAt?.toISOString(),error:n.error,outputs:n.outputs,fromCache:n.fromCache,pinned:n.pinned};const o={};for(const t of e.events)t.edgeId&&"edge.valueRouted"===t.type&&(o[t.edgeId]={status:se.SUCCEEDED,lastValue:t.payload?.value,updatedAt:t.timestamp.toISOString()});const n=[...e.events];return{runId:e.runId,status:e.status,nodes:t,edges:o,outputs:e.outputs,events:n}}}export{Or as AgentNode,er as BreakFlowNode,wr as ChatTriggerNode,pr as CodeInputSchema,hr as CodeNode,jo as ConditionExpressionEvaluator,ar as DEFAULT_GRAPH_WORKFLOW_DOCUMENT_LIMITS,Nn as DEFAULT_GRAPH_WORKFLOW_VALIDATION_LIMITS,cn as DEFAULT_PINNING_METADATA,fr as DelayFlowNode,or as ErrorBoundaryFlowNode,br as EventTriggerNode,vr as FormTriggerNode,kr as GRAPH_AGENT_NODES,Kr as GRAPH_BOUNDARY_NODES,Vr as GRAPH_BUILT_IN_NODE_CLASSES_BY_KIND,Gr as GRAPH_BUILT_IN_NODE_MANIFESTS,Fr as GRAPH_BUILT_IN_NODE_MANIFESTS_BY_KIND,ur as GRAPH_CODE_DEFAULT_LANGUAGE,dr as GRAPH_CODE_DEFAULT_TIMEOUT_MS,cr as GRAPH_CODE_LANGUAGES,Xt as GRAPH_CODE_MAX_TIMEOUT_MS,Ht as GRAPH_DEFAULT_CONCURRENCY,Vt as GRAPH_DEFAULT_MAX_FOREACH_ITERATIONS,Kt as GRAPH_DEFAULT_MAX_LOOP_ITERATIONS,On as GRAPH_DOCUMENT_FORBIDDEN_FIELD_KEYS,Wr as GRAPH_FLOW_CONTROL_NODES,qt as GRAPH_LOCAL_EXECUTION_BACKEND,eo as GRAPH_LOOP_KIND,Hr as GRAPH_LOOP_NODES,Jt as GRAPH_MAX_FOREACH_ITERATIONS,zt as GRAPH_MAX_LOOP_ITERATIONS,Yt as GRAPH_PINNING_METADATA_KEY,Zo as GRAPH_PLAIN_SECRET_KEYS,Br as GRAPH_TRIGGER_NODES,qr as GRAPH_UTILITY_NODES,Wt as GRAPH_WORKFLOW_BOUNDARY,Zr as GRAPH_WORKFLOW_FORBIDDEN_FIELD_KEYS,So as GraphAuthValidator,co as GraphBreakSignal,Sr as GraphConditionEvaluator,Zt as GraphConditionType,wn as GraphConnectionPolicyValidator,In as GraphConnectionValidationError,En as GraphCredentialAuthorizationError,bn as GraphCredentialReferenceValidator,oo as GraphCycleError,vn as GraphDocumentValidationError,yn as GraphEdgeInstanceValidator,To as GraphEngineEventSink,sr as GraphEnvironment,Mo as GraphExecutionBackendRegistry,Ro as GraphExecutionContext,Pn as GraphExecutionEngine,to as GraphExecutionError,ho as GraphExecutionEventEmitter,fo as GraphExecutionEventFactory,$o as GraphExecutionFrame,_n as GraphExecutionPlanner,_i as GraphExecutionSnapshotMapper,_r as GraphForeachLoopNode,no as GraphInputError,Rr as GraphInputValueNode,si as GraphLoopExecutionContext,ro as GraphLoopLimitError,Zn as GraphNode,Vn as GraphNodeCatalogue,zn as GraphNodeExecutorRegistry,Jn as GraphNodeExecutorResolver,gn as GraphNodeInstanceValidator,Wn as GraphNodeManifestResolver,Ln as GraphNodeMethodNotFoundError,Mn as GraphNodeMethodRegistry,Tn as GraphNodeNotFoundError,Cn as GraphNodeRegistrationError,$r as GraphOutputValueNode,en as GraphParameterValidator,hn as GraphPinningDependencyResolver,io as GraphPinningError,pn as GraphPinningPolicy,ln as GraphPinningService,Qt as GraphPinningStrategy,ao as GraphPortError,Yr as GraphPortSchemaResolver,uo as GraphRunCancelledError,wi as GraphRunEventPublisher,bi as GraphRunExecutor,xi as GraphRunModelService,Ii as GraphRunService,so as GraphStoreError,dn as GraphTopology,lo as GraphTopologyError,Dr as GraphUntilLoopNode,tn as GraphValueModel,an as GraphValueRepository,Qr as GraphValueValidator,Pr as GraphWhileLoopNode,po as GraphWorkflowDocumentRejectedError,xn as GraphWorkflowDocumentValidator,Ai as GraphWorkflowService,nr as HumanApprovalFlowNode,rr as IfFlowNode,fi as InMemoryGraphRunEventStore,yi as InMemoryGraphRunStore,$n as IsolatedVmCodeSandboxEvaluator,fn as LocalGraphExecutionBackend,gr as LogFlowNode,Ir as ManualTriggerNode,mr as MapNode,Er as ScheduleTriggerNode,ir as SwitchFlowNode,yr as UtilityLogNode,Nr as WebhookTriggerNode,ui as assertGraphResourceOwnership,ci as assertGraphResourceWriteOwnership,Co as buildGraphExecutionResult,Jr as builtInGraphNodeRegistrations,di as canAccessGraphResource,li as canAccessGraphResourcePayload,Jo as checkGraphValueAgainstSchema,lr as clampGraphCodeTimeoutMs,mn as collectLooseNodeIssues,mo as composeGraphNamespace,sn as createGraphValueRepository,Yn as declaredGraphNodeMethods,go as decomposeGraphNamespace,xo as decomposeGraphNamespaces,Xn as defineGraphNode,Vo as detectGraphCodeModeSurfaces,Fo as evaluateCodeCondition,Wo as evaluateCondition,Bo as evaluateConditionSync,Io as findMalformedGraphNamespaces,vo as findUngrantedGraphNamespaces,ko as graphAuthDataFromRecord,Ao as graphAuthDataOf,zo as graphDocumentHasCodeMode,bo as graphNamespaceCovers,wo as graphNamespacePartsOf,Qn as graphNodeConfig,Eo as graphRolesFromNamespaces,hi as graphRunDocumentFingerprint,Ei as graphWorkflowOwnerOf,Go as isCodeCondition,Uo as isConditionExpression,Yo as isGraphCredentialReferenceLike,yo as isGraphNamespaceCacheEntryValid,kn as isGraphResolvedWorkflow,un as isPinnable,_o as mergeGraphAuthData,Xr as registerBuiltInGraphNodes,Lo as resolveGraphBackendCapabilities,Fn as resolveGraphDynamicPorts,Bn as resolveGraphNodeManifest,on as serializeGraphValueKey,Dn as stripFacadeOwnedBackendConfig,ai as validateGraphWorkflowDocumentAtBoundary};
2
2
  //# sourceMappingURL=as-graph.js.map