@codemation/core 0.0.5 → 0.0.11

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 (215) hide show
  1. package/dist/{InMemoryLiveWorkflowRepository-DL7LmC9S.d.ts → InMemoryLiveWorkflowRepository-DxoualoC.d.ts} +6 -2
  2. package/dist/{InMemoryLiveWorkflowRepository-D6eiiXxF.d.cts → InMemoryLiveWorkflowRepository-orY1VsWG.d.cts} +6 -2
  3. package/dist/{RunIntentService-NKobsfMQ.d.cts → RunIntentService-ByuUYsAL.d.cts} +8 -3
  4. package/dist/{RunIntentService-BFVbsOcg.js → RunIntentService-CYnn140t.js} +9 -4
  5. package/dist/RunIntentService-CYnn140t.js.map +1 -0
  6. package/dist/{RunIntentService-2ivFmNQh.cjs → RunIntentService-DlQH5eZ2.cjs} +9 -4
  7. package/dist/RunIntentService-DlQH5eZ2.cjs.map +1 -0
  8. package/dist/{WorkflowSnapshotCodec-DTdWkoW_.d.cts → WorkflowSnapshotCodec-DSEzKyt3.d.cts} +2 -2
  9. package/dist/bootstrap/index.cjs +133 -4
  10. package/dist/bootstrap/index.cjs.map +1 -1
  11. package/dist/bootstrap/index.d.cts +4 -3
  12. package/dist/bootstrap/index.d.ts +3 -2
  13. package/dist/bootstrap/index.js +133 -4
  14. package/dist/bootstrap/index.js.map +1 -1
  15. package/dist/{index-9g6Pfe9Z.d.ts → index-CTjfVHJh.d.ts} +8 -3
  16. package/dist/index.cjs +1 -1
  17. package/dist/index.d.cts +3 -3
  18. package/dist/index.d.ts +3 -3
  19. package/dist/index.js +1 -1
  20. package/dist/testing.d.cts +2 -2
  21. package/dist/testing.d.ts +1 -1
  22. package/package.json +6 -1
  23. package/src/bootstrap/runtime/EngineRuntimeRegistrar.ts +10 -2
  24. package/src/contracts/runtimeTypes.ts +5 -0
  25. package/src/execution/NodeActivationRequestComposer.ts +15 -4
  26. package/src/orchestration/Engine.ts +12 -1
  27. package/src/orchestration/NodeExecutionRequestHandlerService.ts +179 -0
  28. package/src/runtime/EngineFactory.ts +13 -0
  29. package/dist/EngineExecutionLimitsPolicy-8MEFIYx1.d.cts +0 -160
  30. package/dist/EngineExecutionLimitsPolicy-BWAXW9D6.d.cts +0 -160
  31. package/dist/EngineExecutionLimitsPolicy-Bp8PS1Ss.d.cts +0 -159
  32. package/dist/EngineExecutionLimitsPolicy-CLxcN-D2.d.ts +0 -159
  33. package/dist/EngineExecutionLimitsPolicy-DZXuix51.d.ts +0 -160
  34. package/dist/EngineExecutionLimitsPolicy-Gfz6ngFd.d.ts +0 -160
  35. package/dist/EngineFactory-CBnntY3J.cjs +0 -3152
  36. package/dist/EngineFactory-CBnntY3J.cjs.map +0 -1
  37. package/dist/EngineFactory-Cwn3R2YA.js +0 -3087
  38. package/dist/EngineFactory-Cwn3R2YA.js.map +0 -1
  39. package/dist/EngineFactory-DWCnNocp.js +0 -3063
  40. package/dist/EngineFactory-DWCnNocp.js.map +0 -1
  41. package/dist/EngineFactory-DhPFou4p.cjs +0 -3188
  42. package/dist/EngineFactory-DhPFou4p.cjs.map +0 -1
  43. package/dist/EngineFactory-l_9xmBtv.cjs +0 -3190
  44. package/dist/EngineFactory-l_9xmBtv.cjs.map +0 -1
  45. package/dist/EngineFactory-w-aOWuqh.js +0 -3089
  46. package/dist/EngineFactory-w-aOWuqh.js.map +0 -1
  47. package/dist/InMemoryLiveWorkflowRepository-1J9MHN_I.js +0 -18
  48. package/dist/InMemoryLiveWorkflowRepository-1J9MHN_I.js.map +0 -1
  49. package/dist/InMemoryLiveWorkflowRepository-CULNqv96.d.ts +0 -1300
  50. package/dist/InMemoryLiveWorkflowRepository-D7l8cjdZ.d.cts +0 -1130
  51. package/dist/InMemoryLiveWorkflowRepository-jnv-OnOP.d.ts +0 -1300
  52. package/dist/InMemoryLiveWorkflowRepository-xny1_Z6i.cjs +0 -24
  53. package/dist/InMemoryLiveWorkflowRepository-xny1_Z6i.cjs.map +0 -1
  54. package/dist/InMemoryLiveWorkflowRepository-xr7b4kvi.d.ts +0 -1338
  55. package/dist/InMemoryWorkflowCatalog-BIdFpwbK.d.ts +0 -1205
  56. package/dist/InMemoryWorkflowCatalog-BW00_3N3.d.cts +0 -12
  57. package/dist/InMemoryWorkflowCatalog-BiYHGoPw.cjs +0 -24
  58. package/dist/InMemoryWorkflowCatalog-BiYHGoPw.cjs.map +0 -1
  59. package/dist/InMemoryWorkflowCatalog-BrG0ApMO.d.cts +0 -1115
  60. package/dist/InMemoryWorkflowCatalog-BzrAr--Y.js +0 -139
  61. package/dist/InMemoryWorkflowCatalog-BzrAr--Y.js.map +0 -1
  62. package/dist/InMemoryWorkflowCatalog-C-EJlJ7y.d.cts +0 -1120
  63. package/dist/InMemoryWorkflowCatalog-C4482bpw.cjs +0 -24
  64. package/dist/InMemoryWorkflowCatalog-C4482bpw.cjs.map +0 -1
  65. package/dist/InMemoryWorkflowCatalog-CZ0kZpOv.d.ts +0 -1289
  66. package/dist/InMemoryWorkflowCatalog-C_ACeLyW.d.cts +0 -1119
  67. package/dist/InMemoryWorkflowCatalog-CiHWIu5E.d.cts +0 -12
  68. package/dist/InMemoryWorkflowCatalog-CkH7gkya.js +0 -18
  69. package/dist/InMemoryWorkflowCatalog-CkH7gkya.js.map +0 -1
  70. package/dist/InMemoryWorkflowCatalog-CnpZVJM9.d.ts +0 -1205
  71. package/dist/InMemoryWorkflowCatalog-Cu68S8YR.js +0 -18
  72. package/dist/InMemoryWorkflowCatalog-Cu68S8YR.js.map +0 -1
  73. package/dist/InMemoryWorkflowCatalog-D2w9nMj2.cjs +0 -151
  74. package/dist/InMemoryWorkflowCatalog-D2w9nMj2.cjs.map +0 -1
  75. package/dist/InMemoryWorkflowCatalog-D5eMxEf7.js +0 -18
  76. package/dist/InMemoryWorkflowCatalog-D5eMxEf7.js.map +0 -1
  77. package/dist/InMemoryWorkflowCatalog-D5nCp2yZ.d.ts +0 -1267
  78. package/dist/InMemoryWorkflowCatalog-DIq0bjqN.d.ts +0 -12
  79. package/dist/InMemoryWorkflowCatalog-DLgaEaw_.d.ts +0 -1288
  80. package/dist/InMemoryWorkflowCatalog-DNBFdK-x.d.cts +0 -1120
  81. package/dist/InMemoryWorkflowCatalog-DQBkCzb7.cjs +0 -24
  82. package/dist/InMemoryWorkflowCatalog-DQBkCzb7.cjs.map +0 -1
  83. package/dist/InMemoryWorkflowCatalog-DS4-eX6i.d.cts +0 -1118
  84. package/dist/InMemoryWorkflowCatalog-DdVfy8MY.d.ts +0 -12
  85. package/dist/InMemoryWorkflowCatalog-DeVZu3g8.d.ts +0 -12
  86. package/dist/InMemoryWorkflowCatalog-GxkQjvt5.d.ts +0 -1200
  87. package/dist/InMemoryWorkflowCatalog-qaVRn1Lc.d.cts +0 -1115
  88. package/dist/InMemoryWorkflowCatalog-z1aIT4TC.d.cts +0 -12
  89. package/dist/InMemoryWorkflowRegistry-BBuOovLL.d.ts +0 -1007
  90. package/dist/InMemoryWorkflowRegistry-BIFnSl3k.d.ts +0 -1201
  91. package/dist/InMemoryWorkflowRegistry-BnGilthz.d.ts +0 -1137
  92. package/dist/InMemoryWorkflowRegistry-CEp5I8No.d.ts +0 -1146
  93. package/dist/InMemoryWorkflowRegistry-CHyMB9jW.d.cts +0 -976
  94. package/dist/InMemoryWorkflowRegistry-CUN7K86m.d.cts +0 -1061
  95. package/dist/InMemoryWorkflowRegistry-CVfHyELh.d.cts +0 -971
  96. package/dist/InMemoryWorkflowRegistry-CXXJrwAr.d.cts +0 -1052
  97. package/dist/InMemoryWorkflowRegistry-DDGfPTJy.d.ts +0 -1013
  98. package/dist/InMemoryWorkflowRegistry-DnYSOoT5.d.ts +0 -1120
  99. package/dist/InMemoryWorkflowRegistry-Dp5GiFF2.d.cts +0 -1035
  100. package/dist/InMemoryWorkflowRegistry-DypDBeOw.d.cts +0 -1116
  101. package/dist/InMemoryWorkflowRegistry-SzwJCAxT.d.ts +0 -1012
  102. package/dist/InMemoryWorkflowRegistry-jupvqyGc.d.cts +0 -977
  103. package/dist/InMemoryWorkflowRegistry-rAdKVWYT.d.ts +0 -1117
  104. package/dist/InProcessRetryRunner-BBNPkXjy.d.cts +0 -292
  105. package/dist/PersistedWorkflowSnapshotFactory-7RkOL3Kg.d.ts +0 -14
  106. package/dist/PersistedWorkflowSnapshotFactory-BmANa46W.cjs +0 -141
  107. package/dist/PersistedWorkflowSnapshotFactory-BmANa46W.cjs.map +0 -1
  108. package/dist/PersistedWorkflowSnapshotFactory-Bwb_etSt.js +0 -118
  109. package/dist/PersistedWorkflowSnapshotFactory-Bwb_etSt.js.map +0 -1
  110. package/dist/PersistedWorkflowSnapshotFactory-CRkKGNV6.js +0 -123
  111. package/dist/PersistedWorkflowSnapshotFactory-CRkKGNV6.js.map +0 -1
  112. package/dist/PersistedWorkflowSnapshotFactory-CZolnGy5.js +0 -101
  113. package/dist/PersistedWorkflowSnapshotFactory-CZolnGy5.js.map +0 -1
  114. package/dist/PersistedWorkflowSnapshotFactory-Ca_oysOv.cjs +0 -131
  115. package/dist/PersistedWorkflowSnapshotFactory-Ca_oysOv.cjs.map +0 -1
  116. package/dist/PersistedWorkflowSnapshotFactory-CqIcShnX.js +0 -103
  117. package/dist/PersistedWorkflowSnapshotFactory-CqIcShnX.js.map +0 -1
  118. package/dist/PersistedWorkflowSnapshotFactory-D-tBk4_G.js +0 -119
  119. package/dist/PersistedWorkflowSnapshotFactory-D-tBk4_G.js.map +0 -1
  120. package/dist/PersistedWorkflowSnapshotFactory-D4cXl2e2.cjs +0 -131
  121. package/dist/PersistedWorkflowSnapshotFactory-D4cXl2e2.cjs.map +0 -1
  122. package/dist/PersistedWorkflowSnapshotFactory-DINoP12r.cjs +0 -131
  123. package/dist/PersistedWorkflowSnapshotFactory-DINoP12r.cjs.map +0 -1
  124. package/dist/PersistedWorkflowSnapshotFactory-DJAwSuHU.js +0 -103
  125. package/dist/PersistedWorkflowSnapshotFactory-DJAwSuHU.js.map +0 -1
  126. package/dist/PersistedWorkflowSnapshotFactory-DSUjVCcf.cjs +0 -131
  127. package/dist/PersistedWorkflowSnapshotFactory-DSUjVCcf.cjs.map +0 -1
  128. package/dist/PersistedWorkflowSnapshotFactory-DdHuhkDb.cjs +0 -107
  129. package/dist/PersistedWorkflowSnapshotFactory-DdHuhkDb.cjs.map +0 -1
  130. package/dist/PersistedWorkflowSnapshotFactory-Dqc6NHis.js +0 -119
  131. package/dist/PersistedWorkflowSnapshotFactory-Dqc6NHis.js.map +0 -1
  132. package/dist/PersistedWorkflowSnapshotFactory-Dxa2dSrw.cjs +0 -130
  133. package/dist/PersistedWorkflowSnapshotFactory-Dxa2dSrw.cjs.map +0 -1
  134. package/dist/PersistedWorkflowSnapshotFactory-Ep79Ah1G.js +0 -123
  135. package/dist/PersistedWorkflowSnapshotFactory-Ep79Ah1G.js.map +0 -1
  136. package/dist/PersistedWorkflowSnapshotFactory-GyLfRuiJ.js +0 -119
  137. package/dist/PersistedWorkflowSnapshotFactory-GyLfRuiJ.js.map +0 -1
  138. package/dist/PersistedWorkflowSnapshotFactory-HTpBsBzn.js +0 -102
  139. package/dist/PersistedWorkflowSnapshotFactory-HTpBsBzn.js.map +0 -1
  140. package/dist/PersistedWorkflowSnapshotFactory-LVmaaf3t.cjs +0 -141
  141. package/dist/PersistedWorkflowSnapshotFactory-LVmaaf3t.cjs.map +0 -1
  142. package/dist/PersistedWorkflowSnapshotFactory-PZCpo2ZS.js +0 -119
  143. package/dist/PersistedWorkflowSnapshotFactory-PZCpo2ZS.js.map +0 -1
  144. package/dist/PersistedWorkflowSnapshotFactory-UjQ1SJev.cjs +0 -109
  145. package/dist/PersistedWorkflowSnapshotFactory-UjQ1SJev.cjs.map +0 -1
  146. package/dist/PersistedWorkflowSnapshotFactory-Y8kCrhcy.cjs +0 -109
  147. package/dist/PersistedWorkflowSnapshotFactory-Y8kCrhcy.cjs.map +0 -1
  148. package/dist/PersistedWorkflowSnapshotFactory-Z_nB-fmB.cjs +0 -108
  149. package/dist/PersistedWorkflowSnapshotFactory-Z_nB-fmB.cjs.map +0 -1
  150. package/dist/RunIntentService-1EE6N8ZL.cjs +0 -963
  151. package/dist/RunIntentService-1EE6N8ZL.cjs.map +0 -1
  152. package/dist/RunIntentService-2ivFmNQh.cjs.map +0 -1
  153. package/dist/RunIntentService-B0sUL5q-.js +0 -761
  154. package/dist/RunIntentService-B0sUL5q-.js.map +0 -1
  155. package/dist/RunIntentService-BFVbsOcg.js.map +0 -1
  156. package/dist/RunIntentService-BsBOwpVN.cjs +0 -1051
  157. package/dist/RunIntentService-BsBOwpVN.cjs.map +0 -1
  158. package/dist/RunIntentService-CSk3ETyn.js +0 -858
  159. package/dist/RunIntentService-CSk3ETyn.js.map +0 -1
  160. package/dist/RunIntentService-Ckn3u3tA.d.cts +0 -326
  161. package/dist/RunIntentService-DEo6GTTo.d.cts +0 -289
  162. package/dist/RunIntentService-DKrGtL0B.js +0 -782
  163. package/dist/RunIntentService-DKrGtL0B.js.map +0 -1
  164. package/dist/RunIntentService-DNOJc1R7.cjs +0 -942
  165. package/dist/RunIntentService-DNOJc1R7.cjs.map +0 -1
  166. package/dist/RunIntentService-Dq3pV53j.d.cts +0 -289
  167. package/dist/WorkflowSnapshotCodec-C3fuuS_R.d.cts +0 -22
  168. package/dist/WorkflowSnapshotCodec-CUudUo6f.js +0 -123
  169. package/dist/WorkflowSnapshotCodec-CUudUo6f.js.map +0 -1
  170. package/dist/WorkflowSnapshotCodec-CuCPQZTc.cjs +0 -129
  171. package/dist/WorkflowSnapshotCodec-CuCPQZTc.cjs.map +0 -1
  172. package/dist/WorkflowSnapshotCodec-DLiXQNvV.d.cts +0 -22
  173. package/dist/WorkflowSnapshotCodec-DNtdrZ7l.d.cts +0 -22
  174. package/dist/credentialTypes-B5h3dI7r.d.cts +0 -1107
  175. package/dist/credentialTypes-B9okPCVo.d.cts +0 -963
  176. package/dist/credentialTypes-BFL70rgZ.d.cts +0 -964
  177. package/dist/credentialTypes-BGkh1O07.d.ts +0 -1010
  178. package/dist/credentialTypes-BNLi4Q7u.d.ts +0 -1030
  179. package/dist/credentialTypes-CeSoZGj3.d.cts +0 -994
  180. package/dist/credentialTypes-CpHc32Ig.d.cts +0 -984
  181. package/dist/credentialTypes-D0m7MQQl.d.cts +0 -1107
  182. package/dist/credentialTypes-D4nL2sUd.d.ts +0 -1000
  183. package/dist/credentialTypes-DBYK2Qbu.d.ts +0 -999
  184. package/dist/credentialTypes-DMJVy0r1.d.ts +0 -1000
  185. package/dist/credentialTypes-DhUAjYQp.d.ts +0 -1020
  186. package/dist/credentialTypes-gGITj5KL.d.cts +0 -964
  187. package/dist/credentialTypes-r3KVBJBE.d.cts +0 -974
  188. package/dist/diTokens-ClO27tjK.cjs +0 -34
  189. package/dist/diTokens-ClO27tjK.cjs.map +0 -1
  190. package/dist/diTokens-CoHBkwG6.js +0 -28
  191. package/dist/diTokens-CoHBkwG6.js.map +0 -1
  192. package/dist/index-6Doxmfnd.d.ts +0 -857
  193. package/dist/index-AZ72Ej-K.d.ts +0 -920
  194. package/dist/index-BEk9V-q-.d.ts +0 -667
  195. package/dist/index-Bjt7_7oS.d.ts +0 -1192
  196. package/dist/index-CFGxsYXy.d.ts +0 -708
  197. package/dist/index-C_u8xFgn.d.ts +0 -690
  198. package/dist/index-CpbfsvOJ.d.ts +0 -1192
  199. package/dist/index-CsReNJN_.d.ts +0 -859
  200. package/dist/index-D5iNnXaW.d.ts +0 -667
  201. package/dist/index-DD_Eft1q.d.ts +0 -708
  202. package/dist/index-DiSYUe0G.d.ts +0 -1192
  203. package/dist/index-gIcH60sp.d.ts +0 -674
  204. package/dist/runtime-BIvd-1JA.cjs +0 -4112
  205. package/dist/runtime-BIvd-1JA.cjs.map +0 -1
  206. package/dist/runtime-D3eWKSQK.cjs +0 -3986
  207. package/dist/runtime-D3eWKSQK.cjs.map +0 -1
  208. package/dist/runtime-Dvp4xAjg.js +0 -3799
  209. package/dist/runtime-Dvp4xAjg.js.map +0 -1
  210. package/dist/runtime-vc76SSAa.js +0 -3685
  211. package/dist/runtime-vc76SSAa.js.map +0 -1
  212. package/dist/runtimeTypes-BK0b8SaG.d.cts +0 -884
  213. package/dist/runtimeTypes-CoYZkYQq.d.cts +0 -851
  214. package/dist/runtimeTypes-D-Pm0Uas.d.cts +0 -849
  215. package/dist/types-Cb5UK7Y6.d.ts +0 -857
@@ -1,3190 +0,0 @@
1
- const require_PersistedWorkflowSnapshotFactory = require('./PersistedWorkflowSnapshotFactory-UjQ1SJev.cjs');
2
-
3
- //#region src/diTokens/index.ts
4
- const CoreTokens = {
5
- PersistedWorkflowTokenRegistry: Symbol.for("codemation.core.PersistedWorkflowTokenRegistry"),
6
- CredentialSessionService: Symbol.for("codemation.core.CredentialSessionService"),
7
- CredentialTypeRegistry: Symbol.for("codemation.core.CredentialTypeRegistry"),
8
- WorkflowRunnerService: Symbol.for("codemation.core.WorkflowRunnerService"),
9
- WorkflowRunnerResolver: Symbol.for("codemation.core.WorkflowRunnerResolver"),
10
- WorkflowCatalog: Symbol.for("codemation.core.WorkflowCatalog"),
11
- WorkflowRepository: Symbol.for("codemation.core.WorkflowRepository"),
12
- ServiceContainer: Symbol.for("codemation.core.ServiceContainer"),
13
- NodeResolver: Symbol.for("codemation.core.NodeResolver"),
14
- RunIdFactory: Symbol.for("codemation.core.RunIdFactory"),
15
- ActivationIdFactory: Symbol.for("codemation.core.ActivationIdFactory"),
16
- RunStateStore: Symbol.for("codemation.core.RunStateStore"),
17
- TriggerSetupStateStore: Symbol.for("codemation.core.TriggerSetupStateStore"),
18
- NodeActivationScheduler: Symbol.for("codemation.core.NodeActivationScheduler"),
19
- RunDataFactory: Symbol.for("codemation.core.RunDataFactory"),
20
- ExecutionContextFactory: Symbol.for("codemation.core.ExecutionContextFactory"),
21
- RunEventBus: Symbol.for("codemation.core.RunEventBus"),
22
- BinaryStorage: Symbol.for("codemation.core.BinaryStorage"),
23
- WebhookBasePath: Symbol.for("codemation.core.WebhookBasePath"),
24
- EngineExecutionLimitsPolicy: Symbol.for("codemation.core.EngineExecutionLimitsPolicy"),
25
- WorkflowActivationPolicy: Symbol.for("codemation.core.WorkflowActivationPolicy")
26
- };
27
-
28
- //#endregion
29
- //#region src/engine/materialization/MissingRuntimeTriggerToken.ts
30
- var MissingRuntimeTriggerToken = class {};
31
-
32
- //#endregion
33
- //#region src/engine/materialization/MissingRuntimeNodeToken.ts
34
- var MissingRuntimeNodeToken = class {};
35
-
36
- //#endregion
37
- //#region src/engine/policies/EngineExecutionLimitsPolicy.ts
38
- /** Framework defaults for {@link EngineExecutionLimitsPolicy} (merged with host `runtime.engineExecutionLimits`). */
39
- const ENGINE_EXECUTION_LIMITS_DEFAULTS = {
40
- defaultMaxNodeActivations: 1e5,
41
- hardMaxNodeActivations: 1e5,
42
- defaultMaxSubworkflowDepth: 32,
43
- hardMaxSubworkflowDepth: 32
44
- };
45
- /**
46
- * Resolves per-run execution limits: defaults, hard ceilings, and subworkflow depth for new runs.
47
- */
48
- var EngineExecutionLimitsPolicy = class {
49
- constructor(config = ENGINE_EXECUTION_LIMITS_DEFAULTS) {
50
- this.config = config;
51
- }
52
- /**
53
- * Effective options for a new root run (depth 0): defaults merged with engine ceilings.
54
- * Replaces a separate one-method factory for root-run bootstrap.
55
- */
56
- createRootExecutionOptions() {
57
- return this.mergeExecutionOptionsForNewRun(void 0, void 0);
58
- }
59
- mergeExecutionOptionsForNewRun(parent, user) {
60
- const subworkflowDepth = parent === void 0 ? 0 : (parent.subworkflowDepth ?? 0) + 1;
61
- const inheritedMaxNode = parent?.engineMaxNodeActivations;
62
- const inheritedMaxSub = parent?.engineMaxSubworkflowDepth;
63
- const maxNodeActivations = this.capNumber(user?.maxNodeActivations ?? inheritedMaxNode, this.config.defaultMaxNodeActivations, this.config.hardMaxNodeActivations);
64
- const maxSubworkflowDepth = this.capNumber(user?.maxSubworkflowDepth ?? inheritedMaxSub, this.config.defaultMaxSubworkflowDepth, this.config.hardMaxSubworkflowDepth);
65
- if (subworkflowDepth > maxSubworkflowDepth) throw new Error(`Subworkflow nesting depth ${subworkflowDepth} exceeds maxSubworkflowDepth ${maxSubworkflowDepth} (run would be a child of parent run).`);
66
- return {
67
- ...user,
68
- subworkflowDepth,
69
- maxNodeActivations,
70
- maxSubworkflowDepth
71
- };
72
- }
73
- capNumber(requested, defaultValue, hardCeiling) {
74
- const base = requested === void 0 ? defaultValue : requested;
75
- return Math.min(base, hardCeiling);
76
- }
77
- };
78
-
79
- //#endregion
80
- //#region src/workflow/WorkflowExecutableNodeClassifier.ts
81
- /**
82
- * Derives which workflow nodes participate in the main execution graph vs connection-only children.
83
- */
84
- var WorkflowExecutableNodeClassifier = class {
85
- connectionOwnedIds;
86
- constructor(workflow) {
87
- this.connectionOwnedIds = this.collectConnectionOwnedIds(workflow);
88
- }
89
- isConnectionOwnedNodeId(nodeId) {
90
- return this.connectionOwnedIds.has(nodeId);
91
- }
92
- isExecutableNodeId(nodeId) {
93
- return !this.connectionOwnedIds.has(nodeId);
94
- }
95
- filterExecutableNodeDefinitions(nodes) {
96
- return nodes.filter((n) => this.isExecutableNodeId(n.id));
97
- }
98
- collectConnectionOwnedIds(workflow) {
99
- const ids = /* @__PURE__ */ new Set();
100
- for (const connection of workflow.connections ?? []) for (const childId of connection.childNodeIds) ids.add(childId);
101
- return ids;
102
- }
103
- /**
104
- * Resolves the default start node: first trigger, else first executable node with no incoming edges from executable nodes.
105
- */
106
- findDefaultExecutableStartNodeId(workflow) {
107
- const firstTrigger = workflow.nodes.find((n) => n.kind === "trigger" && this.isExecutableNodeId(n.id))?.id;
108
- if (firstTrigger) return firstTrigger;
109
- const incoming = /* @__PURE__ */ new Map();
110
- for (const n of workflow.nodes) if (this.isExecutableNodeId(n.id)) incoming.set(n.id, 0);
111
- for (const e of workflow.edges) {
112
- if (!this.isExecutableNodeId(e.from.nodeId) || !this.isExecutableNodeId(e.to.nodeId)) continue;
113
- incoming.set(e.to.nodeId, (incoming.get(e.to.nodeId) ?? 0) + 1);
114
- }
115
- return workflow.nodes.find((n) => this.isExecutableNodeId(n.id) && (incoming.get(n.id) ?? 0) === 0)?.id ?? workflow.nodes.find((n) => this.isExecutableNodeId(n.id))?.id ?? (() => {
116
- throw new Error(`Workflow ${workflow.id} has no executable nodes`);
117
- })();
118
- }
119
- firstExecutableNodeIdInDefinitionOrder(workflow) {
120
- return workflow.nodes.find((n) => this.isExecutableNodeId(n.id))?.id;
121
- }
122
- lastExecutableNodeIdInDefinitionOrder(workflow) {
123
- for (let i = workflow.nodes.length - 1; i >= 0; i--) {
124
- const n = workflow.nodes[i];
125
- if (this.isExecutableNodeId(n.id)) return n.id;
126
- }
127
- throw new Error(`Workflow ${workflow.id} has no executable nodes`);
128
- }
129
- };
130
-
131
- //#endregion
132
- //#region src/workflow/workflowExecutableNodeClassifier.types.ts
133
- function createWorkflowExecutableNodeClassifier(workflow) {
134
- return new WorkflowExecutableNodeClassifier(workflow);
135
- }
136
-
137
- //#endregion
138
- //#region src/engine/api/Engine.ts
139
- /**
140
- * Runtime facade for orchestration, continuation, triggers, and webhook routing.
141
- * Prefer {@link import("../intents/RunIntentService").RunIntentService} for host/HTTP invocation boundaries.
142
- * The class token is exported from `@codemation/core/bootstrap` (not the main `@codemation/core` barrel).
143
- */
144
- var Engine = class {
145
- constructor(deps) {
146
- this.deps = deps;
147
- }
148
- loadWorkflows(workflows) {
149
- this.deps.tokenRegistry.registerFromWorkflows?.(workflows);
150
- this.deps.workflowCatalog.setWorkflows(workflows);
151
- this.deps.webhookTriggerMatcher.onEngineWorkflowsLoaded?.();
152
- }
153
- getTokenRegistry() {
154
- return this.deps.tokenRegistry;
155
- }
156
- resolveWorkflowSnapshot(args) {
157
- return this.deps.workflowSnapshotResolver.resolve(args);
158
- }
159
- async startTriggers() {
160
- return await this.deps.triggerRuntime.startTriggers();
161
- }
162
- async syncWorkflowTriggersForActivation(workflowId) {
163
- await this.deps.triggerRuntime.syncWorkflowTriggersForActivation(workflowId);
164
- this.deps.webhookTriggerMatcher.reloadWebhookRoutes?.();
165
- }
166
- async start(workflows) {
167
- await this.stop();
168
- this.loadWorkflows(workflows);
169
- await this.startTriggers();
170
- }
171
- async stop() {
172
- await this.deps.triggerRuntime.stop();
173
- this.deps.webhookTriggerMatcher.onEngineStopped?.();
174
- }
175
- resolveWebhookTrigger(args) {
176
- const entry = this.deps.webhookTriggerMatcher.lookup(args.endpointPath);
177
- if (!entry) return { status: "notFound" };
178
- if (!entry.methods.includes(args.method)) return {
179
- status: "methodNotAllowed",
180
- match: entry
181
- };
182
- return {
183
- status: "ok",
184
- match: entry
185
- };
186
- }
187
- async createTriggerTestItems(args) {
188
- return await this.deps.triggerRuntime.createTriggerTestItems(args);
189
- }
190
- async runWorkflow(wf, startAt, items, parent, executionOptions, persistedStateOverrides) {
191
- return await this.deps.workflowRunStarter.runWorkflow(wf, startAt, items, parent, executionOptions, persistedStateOverrides);
192
- }
193
- async runWorkflowFromState(request) {
194
- return await this.deps.currentStateRunStarter.runWorkflowFromState(request);
195
- }
196
- async markNodeRunning(args) {
197
- return await this.deps.runContinuationService.markNodeRunning(args);
198
- }
199
- async resumeFromNodeResult(args) {
200
- return await this.deps.runContinuationService.resumeFromNodeResult(args);
201
- }
202
- async resumeFromNodeError(args) {
203
- return await this.deps.runContinuationService.resumeFromNodeError(args);
204
- }
205
- async resumeFromStepResult(args) {
206
- return await this.deps.runContinuationService.resumeFromStepResult(args);
207
- }
208
- async resumeFromStepError(args) {
209
- return await this.deps.runContinuationService.resumeFromStepError(args);
210
- }
211
- async waitForCompletion(runId) {
212
- return await this.deps.runContinuationService.waitForCompletion(runId);
213
- }
214
- async waitForWebhookResponse(runId) {
215
- return await this.deps.runContinuationService.waitForWebhookResponse(runId);
216
- }
217
- };
218
-
219
- //#endregion
220
- //#region src/engine/materialization/MissingRuntimeNodeConfig.ts
221
- var MissingRuntimeNodeConfig = class {
222
- kind = "node";
223
- type = MissingRuntimeNodeToken;
224
- constructor(name, missingTokenId, missingRuntime = true) {
225
- this.name = name;
226
- this.missingTokenId = missingTokenId;
227
- this.missingRuntime = missingRuntime;
228
- }
229
- };
230
-
231
- //#endregion
232
- //#region src/engine/materialization/MissingRuntimeTriggerConfig.ts
233
- var MissingRuntimeTriggerConfig = class {
234
- kind = "trigger";
235
- type = MissingRuntimeTriggerToken;
236
- constructor(name, missingTokenId, missingRuntime = true) {
237
- this.name = name;
238
- this.missingTokenId = missingTokenId;
239
- this.missingRuntime = missingRuntime;
240
- }
241
- };
242
-
243
- //#endregion
244
- //#region src/engine/materialization/MissingRuntimeNodeDefinitionFactory.ts
245
- var MissingRuntimeNodeDefinitionFactory = class {
246
- create(snapshotNode) {
247
- if (snapshotNode.kind === "trigger") {
248
- const config$1 = new MissingRuntimeTriggerConfig(snapshotNode.name ?? snapshotNode.id, snapshotNode.nodeTokenId);
249
- return {
250
- id: snapshotNode.id,
251
- kind: "trigger",
252
- name: snapshotNode.name,
253
- type: MissingRuntimeTriggerToken,
254
- config: config$1
255
- };
256
- }
257
- const config = new MissingRuntimeNodeConfig(snapshotNode.name ?? snapshotNode.id, snapshotNode.nodeTokenId);
258
- return {
259
- id: snapshotNode.id,
260
- kind: "node",
261
- name: snapshotNode.name,
262
- type: MissingRuntimeNodeToken,
263
- config
264
- };
265
- }
266
- };
267
-
268
- //#endregion
269
- //#region src/engine/materialization/PersistedWorkflowConfigHydrator.ts
270
- var PersistedWorkflowConfigHydrator = class {
271
- constructor(tokenRegistry) {
272
- this.tokenRegistry = tokenRegistry;
273
- }
274
- hydrate(snapshotNode, liveConfig) {
275
- const hydrated = this.mergeValue(liveConfig, snapshotNode.config);
276
- const configToken = this.tokenRegistry.resolve(snapshotNode.configTokenId);
277
- Object.assign(hydrated, {
278
- type: configToken ?? liveConfig.type,
279
- kind: snapshotNode.kind
280
- });
281
- if (snapshotNode.name && !("name" in hydrated && hydrated.name)) Object.assign(hydrated, { name: snapshotNode.name });
282
- return hydrated;
283
- }
284
- mergeValue(liveValue, snapshotValue) {
285
- const liveRecord = this.asRecord(liveValue);
286
- const snapshotRecord = this.asRecord(snapshotValue);
287
- const hydrated = Object.create(liveValue && typeof liveValue === "object" ? Object.getPrototypeOf(liveValue) ?? Object.prototype : Object.prototype);
288
- for (const [key, value] of Object.entries(snapshotRecord)) hydrated[key] = this.mergeNestedValue(liveRecord[key], value);
289
- this.restoreNonSerializableProperties(liveRecord, hydrated);
290
- this.restoreTypeProperty(hydrated);
291
- return hydrated;
292
- }
293
- mergeNestedValue(liveValue, snapshotValue) {
294
- if (Array.isArray(snapshotValue)) {
295
- const liveArray = Array.isArray(liveValue) ? liveValue : [];
296
- return snapshotValue.map((entry, index) => this.mergeNestedValue(liveArray[index], entry));
297
- }
298
- if (snapshotValue && typeof snapshotValue === "object") return this.mergeValue(liveValue, snapshotValue);
299
- return snapshotValue;
300
- }
301
- restoreNonSerializableProperties(liveRecord, hydrated) {
302
- for (const [key, value] of Object.entries(liveRecord)) if (typeof value === "function" || typeof value === "symbol") hydrated[key] = value;
303
- }
304
- restoreTypeProperty(record) {
305
- const tokenId = typeof record.tokenId === "string" ? record.tokenId : void 0;
306
- if (!tokenId) return;
307
- const type = this.tokenRegistry.resolve(tokenId);
308
- if (type) record.type = type;
309
- }
310
- asRecord(value) {
311
- if (!value || typeof value !== "object" || Array.isArray(value)) return {};
312
- return { ...value };
313
- }
314
- };
315
-
316
- //#endregion
317
- //#region src/engine/materialization/PersistedWorkflowResolver.ts
318
- var PersistedWorkflowResolver = class {
319
- constructor(workflowRepository, tokenRegistry, configHydrator, missingNodeDefinitionFactory) {
320
- this.workflowRepository = workflowRepository;
321
- this.tokenRegistry = tokenRegistry;
322
- this.configHydrator = configHydrator;
323
- this.missingNodeDefinitionFactory = missingNodeDefinitionFactory;
324
- }
325
- resolve(args) {
326
- const liveWorkflow = this.workflowRepository.get(args.workflowId);
327
- if (!args.workflowSnapshot) return liveWorkflow;
328
- if (!liveWorkflow) return this.rebuildWorkflow(args.workflowSnapshot, void 0);
329
- return this.rebuildWorkflow(args.workflowSnapshot, liveWorkflow);
330
- }
331
- rebuildWorkflow(snapshot, liveWorkflow) {
332
- const liveNodesById = new Map((liveWorkflow?.nodes ?? []).map((node) => [node.id, node]));
333
- const nodes = snapshot.nodes.map((snapshotNode) => {
334
- const liveNode = liveNodesById.get(snapshotNode.id);
335
- if (!this.isCompatibleLiveNode(liveNode, snapshotNode)) return this.missingNodeDefinitionFactory.create(snapshotNode);
336
- return {
337
- id: snapshotNode.id,
338
- kind: snapshotNode.kind,
339
- name: snapshotNode.name ?? liveNode.name,
340
- type: liveNode.type,
341
- config: this.configHydrator.hydrate(snapshotNode, liveNode.config)
342
- };
343
- });
344
- const nodeIds = new Set(nodes.map((node) => node.id));
345
- const connectionsFromSnapshot = snapshot.connections?.map((connection) => ({
346
- ...connection,
347
- childNodeIds: connection.childNodeIds.filter((childId) => nodeIds.has(childId))
348
- })).filter((connection) => connection.childNodeIds.length > 0) ?? [];
349
- return {
350
- id: snapshot.id,
351
- name: snapshot.name,
352
- nodes,
353
- edges: snapshot.edges.filter((edge) => nodeIds.has(edge.from.nodeId) && nodeIds.has(edge.to.nodeId)),
354
- ...connectionsFromSnapshot.length > 0 ? { connections: connectionsFromSnapshot } : {},
355
- ...liveWorkflow?.discoveryPathSegments !== void 0 ? { discoveryPathSegments: liveWorkflow.discoveryPathSegments } : {}
356
- };
357
- }
358
- isCompatibleLiveNode(liveNode, snapshotNode) {
359
- if (!liveNode || liveNode.kind !== snapshotNode.kind) return false;
360
- if (!snapshotNode.nodeTokenId || !snapshotNode.configTokenId) throw new Error(`Persisted workflow snapshot node "${snapshotNode.id}" is missing stable token ids.`);
361
- const liveNodeTokenId = this.resolveLiveTokenId(liveNode.type);
362
- const liveConfigTokenId = this.resolveLiveTokenId(liveNode.config.type);
363
- return liveNodeTokenId === snapshotNode.nodeTokenId && liveConfigTokenId === snapshotNode.configTokenId;
364
- }
365
- resolveLiveTokenId(type) {
366
- const registeredTokenId = this.tokenRegistry.getTokenId(type);
367
- if (registeredTokenId) return registeredTokenId;
368
- if (typeof type === "function" && type.name) return type.name;
369
- if (typeof type === "string") return type;
370
- }
371
- };
372
-
373
- //#endregion
374
- //#region src/engine/state/InputPortMapFactory.ts
375
- var InputPortMap = class {
376
- static empty() {
377
- return {};
378
- }
379
- static fromRequest(request) {
380
- if (request.kind === "multi") return request.inputsByPort;
381
- return { in: request.input };
382
- }
383
- };
384
-
385
- //#endregion
386
- //#region src/engine/state/NodeSnapshotFactory.ts
387
- var NodeSnapshotFactory = class {
388
- static queued(args) {
389
- return {
390
- runId: args.runId,
391
- workflowId: args.workflowId,
392
- nodeId: args.nodeId,
393
- activationId: args.activationId,
394
- parent: args.parent,
395
- status: "queued",
396
- queuedAt: args.queuedAt,
397
- updatedAt: args.queuedAt,
398
- inputsByPort: args.inputsByPort
399
- };
400
- }
401
- static running(args) {
402
- return {
403
- runId: args.runId,
404
- workflowId: args.workflowId,
405
- nodeId: args.nodeId,
406
- activationId: args.activationId,
407
- parent: args.parent,
408
- status: "running",
409
- queuedAt: args.previous?.queuedAt,
410
- startedAt: args.startedAt,
411
- updatedAt: args.startedAt,
412
- inputsByPort: args.inputsByPort,
413
- outputs: args.previous?.outputs,
414
- error: void 0
415
- };
416
- }
417
- static completed(args) {
418
- const fromPinnedOutput = args.fromPinnedOutput ?? false;
419
- const startedAt = fromPinnedOutput ? args.previous?.startedAt ?? args.finishedAt : args.previous?.startedAt;
420
- return {
421
- runId: args.runId,
422
- workflowId: args.workflowId,
423
- nodeId: args.nodeId,
424
- activationId: args.activationId,
425
- parent: args.parent,
426
- status: "completed",
427
- queuedAt: args.previous?.queuedAt,
428
- startedAt,
429
- finishedAt: args.finishedAt,
430
- updatedAt: args.finishedAt,
431
- inputsByPort: args.inputsByPort,
432
- outputs: args.outputs,
433
- usedPinnedOutput: fromPinnedOutput,
434
- error: void 0
435
- };
436
- }
437
- static skipped(args) {
438
- return {
439
- runId: args.runId,
440
- workflowId: args.workflowId,
441
- nodeId: args.nodeId,
442
- activationId: args.activationId,
443
- parent: args.parent,
444
- status: "skipped",
445
- queuedAt: args.previous?.queuedAt,
446
- startedAt: args.previous?.startedAt,
447
- finishedAt: args.finishedAt,
448
- updatedAt: args.finishedAt,
449
- inputsByPort: args.inputsByPort,
450
- outputs: args.outputs,
451
- error: void 0
452
- };
453
- }
454
- static failed(args) {
455
- return {
456
- runId: args.runId,
457
- workflowId: args.workflowId,
458
- nodeId: args.nodeId,
459
- activationId: args.activationId,
460
- parent: args.parent,
461
- status: "failed",
462
- queuedAt: args.previous?.queuedAt,
463
- startedAt: args.previous?.startedAt,
464
- finishedAt: args.finishedAt,
465
- updatedAt: args.finishedAt,
466
- inputsByPort: args.inputsByPort,
467
- outputs: void 0,
468
- error: {
469
- message: args.error.message,
470
- name: args.error.name,
471
- stack: args.error.stack
472
- }
473
- };
474
- }
475
- };
476
-
477
- //#endregion
478
- //#region src/engine/execution/ActivationEnqueueService.ts
479
- var ActivationEnqueueService = class {
480
- constructor(activationScheduler, runStore, nodeEventPublisher) {
481
- this.activationScheduler = activationScheduler;
482
- this.runStore = runStore;
483
- this.nodeEventPublisher = nodeEventPublisher;
484
- }
485
- async enqueueActivation(args) {
486
- const { result, queuedSnapshot } = await this.enqueueActivationWithSnapshot(args);
487
- await this.nodeEventPublisher.publish("nodeQueued", queuedSnapshot);
488
- return result;
489
- }
490
- async enqueueActivationWithSnapshot(args) {
491
- const receipt = await this.activationScheduler.enqueue(args.request);
492
- const inputsByPort = InputPortMap.fromRequest(args.request);
493
- const itemsIn = args.request.kind === "multi" ? args.planner.sumItemsByPort(args.request.inputsByPort) : args.request.input.length;
494
- const enqueuedAt = (/* @__PURE__ */ new Date()).toISOString();
495
- const pending = {
496
- runId: args.runId,
497
- activationId: args.request.activationId,
498
- workflowId: args.workflowId,
499
- nodeId: args.request.nodeId,
500
- itemsIn,
501
- inputsByPort,
502
- receiptId: receipt.receiptId,
503
- queue: receipt.queue,
504
- batchId: args.request.batchId,
505
- enqueuedAt
506
- };
507
- const queuedSnapshot = NodeSnapshotFactory.queued({
508
- runId: args.runId,
509
- workflowId: args.workflowId,
510
- nodeId: args.request.nodeId,
511
- activationId: args.request.activationId,
512
- parent: args.parent,
513
- queuedAt: enqueuedAt,
514
- inputsByPort
515
- });
516
- await this.runStore.save({
517
- runId: args.runId,
518
- workflowId: args.workflowId,
519
- startedAt: args.startedAt,
520
- parent: args.parent,
521
- executionOptions: args.executionOptions,
522
- control: args.control,
523
- workflowSnapshot: args.workflowSnapshot,
524
- mutableState: args.mutableState,
525
- policySnapshot: args.policySnapshot,
526
- engineCounters: args.engineCounters,
527
- connectionInvocations: args.connectionInvocations ? [...args.connectionInvocations] : [],
528
- status: "pending",
529
- pending,
530
- queue: args.pendingQueue.map((entry) => ({ ...entry })),
531
- outputsByNode: args.request.ctx.data.dump(),
532
- nodeSnapshotsByNodeId: {
533
- ...args.previousNodeSnapshotsByNodeId,
534
- [args.request.nodeId]: queuedSnapshot
535
- }
536
- });
537
- this.notifyPendingStatePersisted(args.runId);
538
- return {
539
- result: {
540
- runId: args.runId,
541
- workflowId: args.workflowId,
542
- startedAt: args.startedAt,
543
- status: "pending",
544
- pending
545
- },
546
- queuedSnapshot
547
- };
548
- }
549
- notifyPendingStatePersisted(runId) {
550
- this.activationScheduler.notifyPendingStatePersisted?.(runId);
551
- }
552
- };
553
-
554
- //#endregion
555
- //#region src/engine/planning/DependencySatisfactionResolver.ts
556
- var DependencySatisfactionResolver = class {
557
- constructor(topology, currentState) {
558
- this.topology = topology;
559
- this.currentState = currentState;
560
- }
561
- isNodeSatisfied(nodeId) {
562
- return this.hasOutputs(nodeId) || this.hasCompletedSnapshot(nodeId);
563
- }
564
- isNodeSatisfiedByOutputsOnly(nodeId) {
565
- return this.hasOutputs(nodeId) && !this.hasCompletedSnapshot(nodeId);
566
- }
567
- isEdgeSatisfied(args) {
568
- const incomingEdge = (this.topology.incomingByNode.get(args.nodeId) ?? []).find((edge) => edge.input === args.input);
569
- if (!incomingEdge) return false;
570
- return this.hasOutputPort(incomingEdge.from.nodeId, incomingEdge.from.output);
571
- }
572
- resolveInput(args) {
573
- const incomingEdge = (this.topology.incomingByNode.get(args.nodeId) ?? []).find((edge) => edge.input === args.input);
574
- if (!incomingEdge) return [];
575
- return this.resolveOutputItems(incomingEdge.from.nodeId, incomingEdge.from.output);
576
- }
577
- hasOutputs(nodeId) {
578
- return Object.prototype.hasOwnProperty.call(this.currentState.outputsByNode, nodeId);
579
- }
580
- hasCompletedSnapshot(nodeId) {
581
- const snapshot = this.currentState.nodeSnapshotsByNodeId[nodeId];
582
- return snapshot?.status === "completed" || snapshot?.status === "skipped";
583
- }
584
- hasOutputPort(nodeId, output) {
585
- const outputs = this.currentState.outputsByNode[nodeId];
586
- if (!outputs) return false;
587
- return Object.prototype.hasOwnProperty.call(outputs, output);
588
- }
589
- resolveOutputItems(nodeId, output) {
590
- return this.currentState.outputsByNode[nodeId]?.[output] ?? [];
591
- }
592
- };
593
-
594
- //#endregion
595
- //#region src/engine/planning/FrontierQueueBuilder.ts
596
- var FrontierQueueBuilder = class {
597
- constructor(topology, satisfactionResolver) {
598
- this.topology = topology;
599
- this.satisfactionResolver = satisfactionResolver;
600
- }
601
- build(args) {
602
- const incomingEdges = this.topology.incomingByNode.get(args.nodeId) ?? [];
603
- if (incomingEdges.length === 0) return [];
604
- const expectedInputs = this.topology.expectedInputsByNode.get(args.nodeId) ?? [];
605
- if (expectedInputs.length !== 1 || expectedInputs[0] !== "in") {
606
- const received = {};
607
- for (const input$1 of expectedInputs) received[input$1] = this.satisfactionResolver.resolveInput({
608
- nodeId: args.nodeId,
609
- input: input$1
610
- });
611
- return [{
612
- nodeId: args.nodeId,
613
- input: [],
614
- batchId: "batch_1",
615
- collect: {
616
- expectedInputs,
617
- received
618
- }
619
- }];
620
- }
621
- const input = expectedInputs[0] ?? "in";
622
- const incomingEdge = incomingEdges.find((edge) => edge.input === input);
623
- return [{
624
- nodeId: args.nodeId,
625
- input: this.satisfactionResolver.resolveInput({
626
- nodeId: args.nodeId,
627
- input
628
- }),
629
- toInput: input,
630
- batchId: "batch_1",
631
- from: incomingEdge?.from
632
- }];
633
- }
634
- };
635
-
636
- //#endregion
637
- //#region src/engine/planning/PinnedOutputResolver.ts
638
- var PinnedOutputResolver = class {
639
- constructor(currentState) {
640
- this.currentState = currentState;
641
- }
642
- overlayPinnedOutputs() {
643
- const outputsByNode = { ...this.currentState.outputsByNode };
644
- for (const [nodeId, nodeState] of Object.entries(this.currentState.mutableState?.nodesById ?? {})) {
645
- const pinnedOutputs = this.resolvePinnedOutputs(nodeState);
646
- if (!pinnedOutputs) continue;
647
- outputsByNode[nodeId] = pinnedOutputs;
648
- }
649
- return {
650
- outputsByNode,
651
- nodeSnapshotsByNodeId: { ...this.currentState.nodeSnapshotsByNodeId },
652
- mutableState: this.currentState.mutableState
653
- };
654
- }
655
- hasPinnedOutputs(nodeId) {
656
- return this.getPinnedOutputs(nodeId) !== void 0;
657
- }
658
- getPinnedOutputs(nodeId) {
659
- const nodeState = this.currentState.mutableState?.nodesById?.[nodeId];
660
- return this.resolvePinnedOutputs(nodeState);
661
- }
662
- resolvePinnedOutputs(nodeState) {
663
- if (!nodeState) return;
664
- return nodeState.pinnedOutputsByPort;
665
- }
666
- };
667
-
668
- //#endregion
669
- //#region src/engine/planning/RequiredNodeCollector.ts
670
- var RequiredNodeCollector = class {
671
- requiredNodeIds = /* @__PURE__ */ new Set();
672
- constructor(topology, satisfactionResolver) {
673
- this.topology = topology;
674
- this.satisfactionResolver = satisfactionResolver;
675
- }
676
- collect(stopCondition) {
677
- if (stopCondition.kind === "workflowCompleted") {
678
- for (const nodeId of this.topology.defsById.keys()) if (!this.satisfactionResolver.isNodeSatisfied(nodeId)) this.collectNode(nodeId);
679
- return this.requiredNodeIds;
680
- }
681
- if (!this.topology.defsById.has(stopCondition.nodeId)) throw new Error(`Unknown stop nodeId: ${stopCondition.nodeId}`);
682
- this.collectNode(stopCondition.nodeId);
683
- return this.requiredNodeIds;
684
- }
685
- collectNode(nodeId) {
686
- if (this.requiredNodeIds.has(nodeId)) return;
687
- if (this.satisfactionResolver.isNodeSatisfied(nodeId) && !this.satisfactionResolver.isNodeSatisfiedByOutputsOnly(nodeId)) return;
688
- this.requiredNodeIds.add(nodeId);
689
- for (const edge of this.topology.incomingByNode.get(nodeId) ?? []) if (!this.satisfactionResolver.isEdgeSatisfied({
690
- nodeId,
691
- input: edge.input
692
- }) || this.satisfactionResolver.isNodeSatisfiedByOutputsOnly(edge.from.nodeId)) this.collectNode(edge.from.nodeId);
693
- }
694
- };
695
-
696
- //#endregion
697
- //#region src/engine/planning/RootNodeInputResolver.ts
698
- var RootNodeInputResolver = class {
699
- resolve(args) {
700
- if (args.items) return args.items;
701
- if (args.nodeKind === "trigger") return [];
702
- return [{ json: {} }];
703
- }
704
- };
705
-
706
- //#endregion
707
- //#region src/engine/planning/RunCurrentStateFactory.ts
708
- var RunCurrentStateFactory = class {
709
- static empty() {
710
- return {
711
- outputsByNode: {},
712
- nodeSnapshotsByNodeId: {},
713
- connectionInvocations: [],
714
- mutableState: void 0
715
- };
716
- }
717
- static clone(currentState) {
718
- if (!currentState) return this.empty();
719
- return {
720
- outputsByNode: { ...currentState.outputsByNode },
721
- nodeSnapshotsByNodeId: { ...currentState.nodeSnapshotsByNodeId },
722
- connectionInvocations: currentState.connectionInvocations ? [...currentState.connectionInvocations] : void 0,
723
- mutableState: currentState.mutableState
724
- };
725
- }
726
- };
727
-
728
- //#endregion
729
- //#region src/workflow/ConnectionNodeIdFactory.ts
730
- /**
731
- * Deterministic ids for workflow connection-owned child nodes (LLM slot, tools, etc.).
732
- * These are stable across loads.
733
- */
734
- var ConnectionNodeIdFactory = class {
735
- static connectionSegment = "__conn__";
736
- static languageModelConnectionNodeId(parentNodeId) {
737
- return `${parentNodeId}${this.connectionSegment}llm`;
738
- }
739
- static toolConnectionNodeId(parentNodeId, toolName) {
740
- const normalized = this.normalizeToolName(toolName);
741
- return `${parentNodeId}${this.connectionSegment}tool${this.connectionSegment}${normalized}`;
742
- }
743
- static isLanguageModelConnectionNodeId(nodeId) {
744
- return nodeId.endsWith(`${this.connectionSegment}llm`);
745
- }
746
- static isToolConnectionNodeId(nodeId) {
747
- return nodeId.includes(`${this.connectionSegment}tool${this.connectionSegment}`);
748
- }
749
- /** True when `nodeId` is a connection-owned child of `parentNodeId` (LLM or tool slot). */
750
- static isConnectionOwnedDescendantOf(parentNodeId, nodeId) {
751
- return nodeId.startsWith(`${parentNodeId}${this.connectionSegment}`);
752
- }
753
- /** Normalizes a tool display name to a stable id segment. */
754
- static normalizeToolName(toolName) {
755
- return toolName.trim().toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "") || "tool";
756
- }
757
- };
758
-
759
- //#endregion
760
- //#region src/engine/planning/RunStateResetter.ts
761
- var RunStateResetter = class {
762
- constructor(topology, pinnedOutputResolver) {
763
- this.topology = topology;
764
- this.pinnedOutputResolver = pinnedOutputResolver;
765
- }
766
- apply(args) {
767
- if (!args.reset) return {
768
- currentState: args.currentState,
769
- clearedNodeIds: [],
770
- preservedPinnedNodeIds: []
771
- };
772
- const outputsByNode = { ...args.currentState.outputsByNode };
773
- const nodeSnapshotsByNodeId = { ...args.currentState.nodeSnapshotsByNodeId };
774
- const clearedNodeIds = [];
775
- const preservedPinnedNodeIds = [];
776
- const descendants = this.collectDescendants(args.reset.clearFromNodeId);
777
- const runtimeDescendants = this.collectRuntimeDescendants(args.currentState, descendants);
778
- const clearedIdSet = new Set([...descendants, ...runtimeDescendants]);
779
- for (const nodeId of [...descendants, ...runtimeDescendants]) {
780
- if (this.pinnedOutputResolver.hasPinnedOutputs(nodeId)) {
781
- const pinnedOutputs = this.pinnedOutputResolver.getPinnedOutputs(nodeId);
782
- if (pinnedOutputs) outputsByNode[nodeId] = pinnedOutputs;
783
- delete nodeSnapshotsByNodeId[nodeId];
784
- preservedPinnedNodeIds.push(nodeId);
785
- continue;
786
- }
787
- delete outputsByNode[nodeId];
788
- delete nodeSnapshotsByNodeId[nodeId];
789
- clearedNodeIds.push(nodeId);
790
- }
791
- return {
792
- currentState: {
793
- outputsByNode,
794
- nodeSnapshotsByNodeId,
795
- connectionInvocations: this.filterConnectionInvocations(args.currentState.connectionInvocations, clearedIdSet),
796
- mutableState: args.currentState.mutableState
797
- },
798
- clearedNodeIds,
799
- preservedPinnedNodeIds
800
- };
801
- }
802
- filterConnectionInvocations(invocations, clearedIdSet) {
803
- if (!invocations || invocations.length === 0) return invocations;
804
- const kept = invocations.filter((inv) => !clearedIdSet.has(inv.parentAgentNodeId) && !clearedIdSet.has(inv.connectionNodeId));
805
- return kept.length === invocations.length ? invocations : kept;
806
- }
807
- collectDescendants(startNodeId) {
808
- const pendingNodeIds = [startNodeId];
809
- const descendants = /* @__PURE__ */ new Set();
810
- while (pendingNodeIds.length > 0) {
811
- const nodeId = pendingNodeIds.pop();
812
- if (!nodeId || descendants.has(nodeId)) continue;
813
- descendants.add(nodeId);
814
- for (const edge of this.topology.outgoingByNode.get(nodeId) ?? []) pendingNodeIds.push(edge.to.nodeId);
815
- }
816
- return [...descendants];
817
- }
818
- collectRuntimeDescendants(currentState, descendantNodeIds) {
819
- const descendantSet = new Set(descendantNodeIds);
820
- const runtimeNodeIds = /* @__PURE__ */ new Set();
821
- for (const nodeId of [
822
- ...Object.keys(currentState.outputsByNode),
823
- ...Object.keys(currentState.nodeSnapshotsByNodeId),
824
- ...Object.keys(currentState.mutableState?.nodesById ?? {})
825
- ]) {
826
- if (!this.isRuntimeDescendant(nodeId, descendantSet)) continue;
827
- runtimeNodeIds.add(nodeId);
828
- }
829
- return [...runtimeNodeIds];
830
- }
831
- isRuntimeDescendant(nodeId, descendantNodeIds) {
832
- for (const descendantNodeId of descendantNodeIds) {
833
- if (nodeId === descendantNodeId) return false;
834
- if (ConnectionNodeIdFactory.isConnectionOwnedDescendantOf(descendantNodeId, nodeId)) return true;
835
- }
836
- return false;
837
- }
838
- };
839
-
840
- //#endregion
841
- //#region src/engine/planning/CurrentStateFrontierPlanner.ts
842
- var CurrentStateFrontierPlanner = class CurrentStateFrontierPlanner {
843
- rootNodeInputResolver = new RootNodeInputResolver();
844
- constructor(topology) {
845
- this.topology = topology;
846
- }
847
- /** Composition-root-friendly factory (avoids `new` at orchestration call sites under ESLint manual-DI rules). */
848
- static createFromTopology(topology) {
849
- return new CurrentStateFrontierPlanner(topology);
850
- }
851
- plan(args) {
852
- const stopCondition = args.stopCondition ?? { kind: "workflowCompleted" };
853
- const normalizedState = new PinnedOutputResolver(RunCurrentStateFactory.clone(args.currentState)).overlayPinnedOutputs();
854
- const resetResult = new RunStateResetter(this.topology, new PinnedOutputResolver(normalizedState)).apply({
855
- currentState: normalizedState,
856
- reset: args.reset
857
- });
858
- const satisfactionResolver = new DependencySatisfactionResolver(this.topology, resetResult.currentState);
859
- const requiredNodeIds = new RequiredNodeCollector(this.topology, satisfactionResolver).collect(stopCondition);
860
- const satisfiedNodeIds = this.collectSatisfiedNodeIds(satisfactionResolver);
861
- const skippedNodeIds = [...new Set([...[...requiredNodeIds].filter((nodeId) => satisfactionResolver.isNodeSatisfied(nodeId)), ...resetResult.preservedPinnedNodeIds.filter((nodeId) => requiredNodeIds.has(nodeId))])];
862
- const frontierNodeIds = this.collectFrontierNodeIds(requiredNodeIds, satisfactionResolver);
863
- const rootNodeIds = frontierNodeIds.filter((nodeId) => (this.topology.incomingByNode.get(nodeId) ?? []).length === 0);
864
- if (rootNodeIds.length > 1) throw new Error(`Ambiguous execution frontier. Multiple root nodes require input: ${rootNodeIds.join(", ")}`);
865
- if (frontierNodeIds.length === 0) return {
866
- queue: [],
867
- currentState: resetResult.currentState,
868
- stopCondition,
869
- satisfiedNodeIds,
870
- skippedNodeIds,
871
- clearedNodeIds: resetResult.clearedNodeIds,
872
- preservedPinnedNodeIds: resetResult.preservedPinnedNodeIds
873
- };
874
- if (rootNodeIds.length === 1) {
875
- const rootNodeId = rootNodeIds[0];
876
- const definition = this.topology.defsById.get(rootNodeId);
877
- if (!definition) throw new Error(`Unknown frontier nodeId: ${rootNodeId}`);
878
- return {
879
- rootNodeId,
880
- rootNodeInput: this.rootNodeInputResolver.resolve({
881
- nodeKind: definition.kind,
882
- items: args.items
883
- }),
884
- queue: [],
885
- currentState: resetResult.currentState,
886
- stopCondition,
887
- satisfiedNodeIds,
888
- skippedNodeIds,
889
- clearedNodeIds: resetResult.clearedNodeIds,
890
- preservedPinnedNodeIds: resetResult.preservedPinnedNodeIds
891
- };
892
- }
893
- const queueBuilder = new FrontierQueueBuilder(this.topology, satisfactionResolver);
894
- const queue = [];
895
- for (const nodeId of frontierNodeIds) queue.push(...queueBuilder.build({ nodeId }));
896
- return {
897
- queue,
898
- currentState: resetResult.currentState,
899
- stopCondition,
900
- satisfiedNodeIds,
901
- skippedNodeIds,
902
- clearedNodeIds: resetResult.clearedNodeIds,
903
- preservedPinnedNodeIds: resetResult.preservedPinnedNodeIds
904
- };
905
- }
906
- collectSatisfiedNodeIds(satisfactionResolver) {
907
- const satisfiedNodeIds = [];
908
- for (const nodeId of this.topology.defsById.keys()) if (satisfactionResolver.isNodeSatisfied(nodeId)) satisfiedNodeIds.push(nodeId);
909
- return satisfiedNodeIds;
910
- }
911
- collectFrontierNodeIds(requiredNodeIds, satisfactionResolver) {
912
- const frontierNodeIds = [];
913
- for (const nodeId of this.topology.defsById.keys()) {
914
- if (!requiredNodeIds.has(nodeId) || satisfactionResolver.isNodeSatisfied(nodeId)) continue;
915
- if ((this.topology.incomingByNode.get(nodeId) ?? []).every((edge) => satisfactionResolver.isEdgeSatisfied({
916
- nodeId,
917
- input: edge.input
918
- }))) frontierNodeIds.push(nodeId);
919
- }
920
- return frontierNodeIds;
921
- }
922
- };
923
-
924
- //#endregion
925
- //#region src/engine/planning/WorkflowTopologyPlanner.ts
926
- var WorkflowTopology = class WorkflowTopology {
927
- constructor(defsById, outgoingByNode, incomingByNode, expectedInputsByNode, rootNodeIds) {
928
- this.defsById = defsById;
929
- this.outgoingByNode = outgoingByNode;
930
- this.incomingByNode = incomingByNode;
931
- this.expectedInputsByNode = expectedInputsByNode;
932
- this.rootNodeIds = rootNodeIds;
933
- }
934
- static fromWorkflow(wf) {
935
- const classifier = createWorkflowExecutableNodeClassifier(wf);
936
- const defs = /* @__PURE__ */ new Map();
937
- for (const n of wf.nodes) if (classifier.isExecutableNodeId(n.id)) defs.set(n.id, n);
938
- const outgoing = /* @__PURE__ */ new Map();
939
- for (const e of wf.edges) {
940
- if (!classifier.isExecutableNodeId(e.from.nodeId) || !classifier.isExecutableNodeId(e.to.nodeId)) continue;
941
- const list = outgoing.get(e.from.nodeId) ?? [];
942
- list.push({
943
- output: e.from.output,
944
- to: {
945
- nodeId: e.to.nodeId,
946
- input: e.to.input
947
- }
948
- });
949
- outgoing.set(e.from.nodeId, list);
950
- }
951
- const incomingByNode = /* @__PURE__ */ new Map();
952
- for (const e of wf.edges) {
953
- if (!classifier.isExecutableNodeId(e.from.nodeId) || !classifier.isExecutableNodeId(e.to.nodeId)) continue;
954
- const list = incomingByNode.get(e.to.nodeId) ?? [];
955
- list.push({
956
- from: {
957
- nodeId: e.from.nodeId,
958
- output: e.from.output
959
- },
960
- input: e.to.input
961
- });
962
- incomingByNode.set(e.to.nodeId, list);
963
- }
964
- const expected = /* @__PURE__ */ new Map();
965
- for (const [toNodeId, inputs] of incomingByNode.entries()) {
966
- const counts = /* @__PURE__ */ new Map();
967
- for (const edge of inputs) counts.set(edge.input, (counts.get(edge.input) ?? 0) + 1);
968
- for (const [k, n] of counts.entries()) if (n > 1) throw new Error(`Node ${toNodeId} has multiple edges into input '${k}'. Use a Merge node upstream.`);
969
- const order = [];
970
- const seen = /* @__PURE__ */ new Set();
971
- for (const edge of inputs) {
972
- if (seen.has(edge.input)) continue;
973
- seen.add(edge.input);
974
- order.push(edge.input);
975
- }
976
- expected.set(toNodeId, order);
977
- }
978
- return new WorkflowTopology(defs, outgoing, incomingByNode, expected, wf.nodes.filter((node) => classifier.isExecutableNodeId(node.id) && !incomingByNode.has(node.id)).map((node) => node.id));
979
- }
980
- };
981
-
982
- //#endregion
983
- //#region src/engine/policies/RunPolicySnapshotFactory.ts
984
- var RunPolicySnapshotFactory = class {
985
- static create(workflow, defaults) {
986
- const prune = workflow.prunePolicy;
987
- return {
988
- retentionSeconds: prune?.runDataRetentionSeconds ?? defaults?.retentionSeconds,
989
- binaryRetentionSeconds: prune?.binaryRetentionSeconds ?? defaults?.binaryRetentionSeconds,
990
- storagePolicy: typeof workflow.storagePolicy === "string" ? workflow.storagePolicy : defaults?.storagePolicy ?? "ALL"
991
- };
992
- }
993
- };
994
-
995
- //#endregion
996
- //#region src/engine/execution/CurrentStateRunStarter.ts
997
- var CurrentStateRunStarter = class {
998
- constructor(runIdFactory, runStore, runDataFactory, workflowSnapshotFactory, planningFactory, nodeStatePublisherFactory, runExecutionContextFactory, nodeActivationRequestComposer, activationEnqueueService, semantics, waiters, workflowPolicyRuntimeDefaults, executionLimitsPolicy) {
999
- this.runIdFactory = runIdFactory;
1000
- this.runStore = runStore;
1001
- this.runDataFactory = runDataFactory;
1002
- this.workflowSnapshotFactory = workflowSnapshotFactory;
1003
- this.planningFactory = planningFactory;
1004
- this.nodeStatePublisherFactory = nodeStatePublisherFactory;
1005
- this.runExecutionContextFactory = runExecutionContextFactory;
1006
- this.nodeActivationRequestComposer = nodeActivationRequestComposer;
1007
- this.activationEnqueueService = activationEnqueueService;
1008
- this.semantics = semantics;
1009
- this.waiters = waiters;
1010
- this.workflowPolicyRuntimeDefaults = workflowPolicyRuntimeDefaults;
1011
- this.executionLimitsPolicy = executionLimitsPolicy;
1012
- }
1013
- async runWorkflowFromState(request) {
1014
- const runId = this.runIdFactory.makeRunId();
1015
- const startedAt = (/* @__PURE__ */ new Date()).toISOString();
1016
- const workflowSnapshot = request.workflowSnapshot ?? this.workflowSnapshotFactory.create(request.workflow);
1017
- const mutableState = request.mutableState ?? request.currentState?.mutableState;
1018
- const policySnapshot = RunPolicySnapshotFactory.create(request.workflow, this.workflowPolicyRuntimeDefaults);
1019
- const control = { stopCondition: request.stopCondition ?? { kind: "workflowCompleted" } };
1020
- const mergedExecutionOptions = this.executionLimitsPolicy.mergeExecutionOptionsForNewRun(request.parent, request.executionOptions);
1021
- await this.runStore.createRun({
1022
- runId,
1023
- workflowId: request.workflow.id,
1024
- startedAt,
1025
- parent: request.parent,
1026
- executionOptions: mergedExecutionOptions,
1027
- control,
1028
- workflowSnapshot,
1029
- mutableState,
1030
- policySnapshot,
1031
- engineCounters: { completedNodeActivations: 0 }
1032
- });
1033
- const { topology, planner } = this.planningFactory.create(request.workflow);
1034
- const plan = CurrentStateFrontierPlanner.createFromTopology(topology).plan({
1035
- currentState: this.createRunCurrentState(request.currentState, mutableState),
1036
- stopCondition: control.stopCondition,
1037
- reset: request.reset,
1038
- items: request.items
1039
- });
1040
- const data = this.runDataFactory.create(plan.currentState.outputsByNode);
1041
- const base = this.runExecutionContextFactory.create({
1042
- runId,
1043
- workflowId: request.workflow.id,
1044
- nodeId: createWorkflowExecutableNodeClassifier(request.workflow).firstExecutableNodeIdInDefinitionOrder(request.workflow) ?? "unknown_node",
1045
- parent: request.parent,
1046
- subworkflowDepth: mergedExecutionOptions.subworkflowDepth ?? 0,
1047
- engineMaxNodeActivations: mergedExecutionOptions.maxNodeActivations,
1048
- engineMaxSubworkflowDepth: mergedExecutionOptions.maxSubworkflowDepth,
1049
- data,
1050
- nodeState: this.nodeStatePublisherFactory.create(runId, request.workflow.id, request.parent)
1051
- });
1052
- return await this.scheduleInitialPlan({
1053
- runId,
1054
- startedAt,
1055
- workflow: request.workflow,
1056
- workflowSnapshot,
1057
- mutableState,
1058
- policySnapshot,
1059
- executionOptions: mergedExecutionOptions,
1060
- control,
1061
- parent: request.parent,
1062
- planner,
1063
- plan,
1064
- base,
1065
- data
1066
- });
1067
- }
1068
- createRunCurrentState(currentState, mutableState) {
1069
- return {
1070
- outputsByNode: { ...currentState?.outputsByNode ?? {} },
1071
- nodeSnapshotsByNodeId: { ...currentState?.nodeSnapshotsByNodeId ?? {} },
1072
- connectionInvocations: currentState?.connectionInvocations ? [...currentState.connectionInvocations] : void 0,
1073
- mutableState: mutableState ?? currentState?.mutableState
1074
- };
1075
- }
1076
- async scheduleInitialPlan(args) {
1077
- const initialNodeSnapshotsByNodeId = this.semantics.applySkippedSnapshots({
1078
- runId: args.runId,
1079
- workflowId: args.workflow.id,
1080
- parent: args.parent,
1081
- currentState: args.plan.currentState,
1082
- skippedNodeIds: args.plan.skippedNodeIds,
1083
- preservedPinnedNodeIds: args.plan.preservedPinnedNodeIds,
1084
- finishedAt: args.startedAt
1085
- });
1086
- if (args.plan.rootNodeId) {
1087
- const startDef = WorkflowTopology.fromWorkflow(args.workflow).defsById.get(args.plan.rootNodeId);
1088
- if (!startDef) throw new Error(`Unknown frontier nodeId: ${args.plan.rootNodeId}`);
1089
- const startItems = args.plan.rootNodeInput ?? [];
1090
- if (startDef.kind === "trigger") {
1091
- const request$1 = this.nodeActivationRequestComposer.createSingleFromDefinition({
1092
- runId: args.runId,
1093
- workflowId: args.workflow.id,
1094
- definition: startDef,
1095
- parent: args.parent,
1096
- executionOptions: args.executionOptions,
1097
- batchId: "batch_1",
1098
- input: startItems,
1099
- base: args.base,
1100
- data: args.data
1101
- });
1102
- return await this.activationEnqueueService.enqueueActivation({
1103
- runId: args.runId,
1104
- workflowId: args.workflow.id,
1105
- startedAt: args.startedAt,
1106
- parent: args.parent,
1107
- executionOptions: args.executionOptions,
1108
- control: args.control,
1109
- workflowSnapshot: args.workflowSnapshot,
1110
- mutableState: args.mutableState,
1111
- policySnapshot: args.policySnapshot,
1112
- pendingQueue: [],
1113
- request: request$1,
1114
- previousNodeSnapshotsByNodeId: initialNodeSnapshotsByNodeId,
1115
- planner: args.planner,
1116
- engineCounters: { completedNodeActivations: 0 },
1117
- connectionInvocations: args.plan.currentState.connectionInvocations ?? []
1118
- });
1119
- }
1120
- const request = this.nodeActivationRequestComposer.createSingleFromDefinition({
1121
- runId: args.runId,
1122
- workflowId: args.workflow.id,
1123
- definition: startDef,
1124
- parent: args.parent,
1125
- executionOptions: args.executionOptions,
1126
- batchId: "batch_1",
1127
- input: startItems,
1128
- base: args.base,
1129
- data: args.data
1130
- });
1131
- return await this.activationEnqueueService.enqueueActivation({
1132
- runId: args.runId,
1133
- workflowId: args.workflow.id,
1134
- startedAt: args.startedAt,
1135
- parent: args.parent,
1136
- executionOptions: args.executionOptions,
1137
- control: args.control,
1138
- workflowSnapshot: args.workflowSnapshot,
1139
- mutableState: args.mutableState,
1140
- policySnapshot: args.policySnapshot,
1141
- pendingQueue: [],
1142
- request,
1143
- previousNodeSnapshotsByNodeId: initialNodeSnapshotsByNodeId,
1144
- planner: args.planner,
1145
- connectionInvocations: args.plan.currentState.connectionInvocations ?? []
1146
- });
1147
- }
1148
- return await this.scheduleQueuedPlan({
1149
- runId: args.runId,
1150
- workflowId: args.workflow.id,
1151
- startedAt: args.startedAt,
1152
- parent: args.parent,
1153
- executionOptions: args.executionOptions,
1154
- control: args.control,
1155
- workflowSnapshot: args.workflowSnapshot,
1156
- mutableState: args.mutableState,
1157
- policySnapshot: args.policySnapshot,
1158
- workflow: args.workflow,
1159
- planner: args.planner,
1160
- queue: [...args.plan.queue],
1161
- base: args.base,
1162
- data: args.data,
1163
- nodeSnapshotsByNodeId: initialNodeSnapshotsByNodeId,
1164
- connectionInvocations: args.plan.currentState.connectionInvocations ?? []
1165
- });
1166
- }
1167
- async scheduleQueuedPlan(args) {
1168
- this.semantics.applyPinnedQueueSkips({
1169
- runId: args.runId,
1170
- workflowId: args.workflowId,
1171
- parent: args.parent,
1172
- mutableState: args.mutableState,
1173
- planner: args.planner,
1174
- queue: args.queue,
1175
- data: args.data,
1176
- nodeSnapshotsByNodeId: args.nodeSnapshotsByNodeId,
1177
- finishedAt: args.startedAt
1178
- });
1179
- const next = args.planner.nextActivation(args.queue);
1180
- if (!next) return await this.completeRun({
1181
- runId: args.runId,
1182
- workflowId: args.workflowId,
1183
- startedAt: args.startedAt,
1184
- parent: args.parent,
1185
- executionOptions: args.executionOptions,
1186
- control: args.control,
1187
- workflowSnapshot: args.workflowSnapshot,
1188
- mutableState: args.mutableState,
1189
- policySnapshot: args.policySnapshot,
1190
- workflow: args.workflow,
1191
- data: args.data,
1192
- nodeSnapshotsByNodeId: args.nodeSnapshotsByNodeId,
1193
- connectionInvocations: args.connectionInvocations
1194
- });
1195
- const definition = WorkflowTopology.fromWorkflow(args.workflow).defsById.get(next.nodeId);
1196
- if (!definition || definition.kind !== "node") throw new Error(`Node ${next.nodeId} is not a runnable node`);
1197
- const request = this.nodeActivationRequestComposer.createFromPlannedActivation({
1198
- next,
1199
- base: args.base,
1200
- data: args.data,
1201
- runId: args.runId,
1202
- workflowId: args.workflowId,
1203
- parent: args.parent,
1204
- executionOptions: args.executionOptions,
1205
- nodeDefinition: definition
1206
- });
1207
- return await this.activationEnqueueService.enqueueActivation({
1208
- runId: args.runId,
1209
- workflowId: args.workflowId,
1210
- startedAt: args.startedAt,
1211
- parent: args.parent,
1212
- executionOptions: args.executionOptions,
1213
- control: args.control,
1214
- workflowSnapshot: args.workflowSnapshot,
1215
- mutableState: args.mutableState,
1216
- policySnapshot: args.policySnapshot,
1217
- pendingQueue: args.queue,
1218
- request,
1219
- previousNodeSnapshotsByNodeId: args.nodeSnapshotsByNodeId,
1220
- planner: args.planner,
1221
- engineCounters: { completedNodeActivations: 0 },
1222
- connectionInvocations: args.connectionInvocations ?? []
1223
- });
1224
- }
1225
- async completeRun(args) {
1226
- await this.runStore.save({
1227
- runId: args.runId,
1228
- workflowId: args.workflowId,
1229
- startedAt: args.startedAt,
1230
- parent: args.parent,
1231
- executionOptions: args.executionOptions,
1232
- control: args.control,
1233
- workflowSnapshot: args.workflowSnapshot,
1234
- mutableState: args.mutableState,
1235
- policySnapshot: args.policySnapshot,
1236
- engineCounters: { completedNodeActivations: 0 },
1237
- connectionInvocations: args.connectionInvocations ? [...args.connectionInvocations] : [],
1238
- status: "completed",
1239
- pending: void 0,
1240
- queue: [],
1241
- outputsByNode: args.data.dump(),
1242
- nodeSnapshotsByNodeId: args.nodeSnapshotsByNodeId
1243
- });
1244
- const result = {
1245
- runId: args.runId,
1246
- workflowId: args.workflowId,
1247
- startedAt: args.startedAt,
1248
- status: "completed",
1249
- outputs: this.semantics.resolveResultOutputs(args.workflow, args.control?.stopCondition, args.data.dump())
1250
- };
1251
- this.waiters.resolveRunCompletion(result);
1252
- return result;
1253
- }
1254
- };
1255
-
1256
- //#endregion
1257
- //#region src/engine/execution/NodeActivationRequestComposer.ts
1258
- /**
1259
- * Builds {@link NodeActivationRequest} values shared by workflow starters and continuation.
1260
- */
1261
- var NodeActivationRequestComposer = class {
1262
- constructor(activationIdFactory, credentialResolverFactory) {
1263
- this.activationIdFactory = activationIdFactory;
1264
- this.credentialResolverFactory = credentialResolverFactory;
1265
- }
1266
- createSingleFromDefinition(args) {
1267
- const activationId = this.activationIdFactory.makeActivationId();
1268
- const ctx = {
1269
- ...args.base,
1270
- data: args.data,
1271
- nodeId: args.definition.id,
1272
- activationId,
1273
- config: args.definition.config,
1274
- binary: args.base.binary.forNode({
1275
- nodeId: args.definition.id,
1276
- activationId
1277
- }),
1278
- getCredential: this.credentialResolverFactory.create(args.workflowId, args.definition.id, args.definition.config)
1279
- };
1280
- return {
1281
- kind: "single",
1282
- runId: args.runId,
1283
- activationId,
1284
- workflowId: args.workflowId,
1285
- nodeId: args.definition.id,
1286
- parent: args.parent,
1287
- executionOptions: args.executionOptions,
1288
- batchId: args.batchId,
1289
- input: args.input,
1290
- ctx
1291
- };
1292
- }
1293
- createFromPlannedActivation(args) {
1294
- const activationId = this.activationIdFactory.makeActivationId();
1295
- const ctx = {
1296
- ...args.base,
1297
- data: args.data,
1298
- nodeId: args.nodeDefinition.id,
1299
- activationId,
1300
- config: args.nodeDefinition.config,
1301
- binary: args.base.binary.forNode({
1302
- nodeId: args.nodeDefinition.id,
1303
- activationId
1304
- }),
1305
- getCredential: this.credentialResolverFactory.create(args.workflowId, args.nodeDefinition.id, args.nodeDefinition.config)
1306
- };
1307
- if (args.next.kind === "multi") return {
1308
- kind: "multi",
1309
- runId: args.runId,
1310
- activationId,
1311
- workflowId: args.workflowId,
1312
- nodeId: args.nodeDefinition.id,
1313
- parent: args.parent,
1314
- executionOptions: args.executionOptions,
1315
- batchId: args.next.batchId,
1316
- inputsByPort: args.next.inputsByPort,
1317
- ctx
1318
- };
1319
- return {
1320
- kind: "single",
1321
- runId: args.runId,
1322
- activationId,
1323
- workflowId: args.workflowId,
1324
- nodeId: args.nodeDefinition.id,
1325
- parent: args.parent,
1326
- executionOptions: args.executionOptions,
1327
- batchId: args.next.batchId,
1328
- input: args.next.input,
1329
- ctx
1330
- };
1331
- }
1332
- };
1333
-
1334
- //#endregion
1335
- //#region src/engine/execution/PersistedRunStateTerminalBuilder.ts
1336
- /**
1337
- * Merges common terminal-run fields onto a loaded {@link PersistedRunState} without repeating object literals.
1338
- */
1339
- var PersistedRunStateTerminalBuilder = class {
1340
- mergeTerminal(args) {
1341
- return {
1342
- ...args.state,
1343
- engineCounters: args.engineCounters,
1344
- status: args.status,
1345
- pending: void 0,
1346
- queue: args.queue,
1347
- outputsByNode: args.outputsByNode,
1348
- nodeSnapshotsByNodeId: args.nodeSnapshotsByNodeId
1349
- };
1350
- }
1351
- };
1352
-
1353
- //#endregion
1354
- //#region src/engine/state/RuntimeContinuationDiagnosticsReporter.ts
1355
- var RuntimeContinuationDiagnostics = class {
1356
- static formatNodeLabel(args) {
1357
- const tokenName = typeof args.definition?.type === "function" ? args.definition.type.name : "Node";
1358
- return args.definition?.name ? `"${args.definition.name}" (${tokenName}:${args.nodeId})` : `${tokenName}:${args.nodeId}`;
1359
- }
1360
- static formatOutputCounts(outputs) {
1361
- const entries = Object.entries(outputs ?? {});
1362
- if (entries.length === 0) return "no outputs";
1363
- return entries.map(([port, items]) => `${port}=${items?.length ?? 0}`).join(", ");
1364
- }
1365
- };
1366
-
1367
- //#endregion
1368
- //#region src/engine/execution/RunContinuationService.ts
1369
- var RunContinuationService = class {
1370
- constructor(activationIdFactory, runStore, runDataFactory, runExecutionContextFactory, workflowSnapshotResolver, planningFactory, nodeStatePublisherFactory, credentialResolverFactory, nodeActivationRequestComposer, persistedRunStateTerminalBuilder, activationEnqueueService, nodeEventPublisher, semantics, waiters, policyErrorServices, terminalPersistence, executionLimitsPolicy) {
1371
- this.activationIdFactory = activationIdFactory;
1372
- this.runStore = runStore;
1373
- this.runDataFactory = runDataFactory;
1374
- this.runExecutionContextFactory = runExecutionContextFactory;
1375
- this.workflowSnapshotResolver = workflowSnapshotResolver;
1376
- this.planningFactory = planningFactory;
1377
- this.nodeStatePublisherFactory = nodeStatePublisherFactory;
1378
- this.credentialResolverFactory = credentialResolverFactory;
1379
- this.nodeActivationRequestComposer = nodeActivationRequestComposer;
1380
- this.persistedRunStateTerminalBuilder = persistedRunStateTerminalBuilder;
1381
- this.activationEnqueueService = activationEnqueueService;
1382
- this.nodeEventPublisher = nodeEventPublisher;
1383
- this.semantics = semantics;
1384
- this.waiters = waiters;
1385
- this.policyErrorServices = policyErrorServices;
1386
- this.terminalPersistence = terminalPersistence;
1387
- this.executionLimitsPolicy = executionLimitsPolicy;
1388
- }
1389
- async markNodeRunning(args) {
1390
- const state = await this.runStore.load(args.runId);
1391
- if (!state?.pending) return;
1392
- if (state.pending.activationId !== args.activationId || state.pending.nodeId !== args.nodeId) return;
1393
- const startedAt = (/* @__PURE__ */ new Date()).toISOString();
1394
- const previous = state.nodeSnapshotsByNodeId?.[args.nodeId];
1395
- const snapshot = NodeSnapshotFactory.running({
1396
- previous,
1397
- runId: state.runId,
1398
- workflowId: state.workflowId,
1399
- nodeId: args.nodeId,
1400
- activationId: args.activationId,
1401
- parent: state.parent,
1402
- startedAt,
1403
- inputsByPort: args.inputsByPort
1404
- });
1405
- await this.runStore.save({
1406
- ...state,
1407
- nodeSnapshotsByNodeId: {
1408
- ...state.nodeSnapshotsByNodeId ?? {},
1409
- [args.nodeId]: snapshot
1410
- }
1411
- });
1412
- await this.nodeEventPublisher.publish("nodeStarted", snapshot);
1413
- }
1414
- async resumeFromNodeResult(args) {
1415
- const state = await this.runStore.load(args.runId);
1416
- if (!state) throw new Error(`Unknown runId: ${args.runId}`);
1417
- if (state.status !== "pending" || !state.pending) throw new Error(`Run ${args.runId} is not pending`);
1418
- if (state.pending.activationId !== args.activationId) throw new Error(`activationId mismatch for run ${args.runId}`);
1419
- if (state.pending.nodeId !== args.nodeId) throw new Error(`nodeId mismatch for run ${args.runId}`);
1420
- const wf = this.resolvePersistedWorkflow(state);
1421
- if (!wf) throw new Error(`Unknown workflowId: ${state.workflowId}`);
1422
- const { topology, planner } = this.planningFactory.create(wf);
1423
- const data = this.runDataFactory.create(state.outputsByNode);
1424
- const limits = this.resolveEngineLimitsFromState(state);
1425
- const base = this.runExecutionContextFactory.create({
1426
- runId: state.runId,
1427
- workflowId: state.workflowId,
1428
- nodeId: args.nodeId,
1429
- parent: state.parent,
1430
- subworkflowDepth: state.executionOptions?.subworkflowDepth ?? 0,
1431
- engineMaxNodeActivations: limits.engineMaxNodeActivations,
1432
- engineMaxSubworkflowDepth: limits.engineMaxSubworkflowDepth,
1433
- data,
1434
- nodeState: this.nodeStatePublisherFactory.create(state.runId, state.workflowId, state.parent)
1435
- });
1436
- data.setOutputs(args.nodeId, args.outputs);
1437
- const completedAt = (/* @__PURE__ */ new Date()).toISOString();
1438
- const completedSnapshot = this.semantics.createFinishedSnapshot({
1439
- workflow: wf,
1440
- previous: state.nodeSnapshotsByNodeId?.[args.nodeId],
1441
- runId: state.runId,
1442
- workflowId: state.workflowId,
1443
- nodeId: args.nodeId,
1444
- activationId: args.activationId,
1445
- parent: state.parent,
1446
- finishedAt: completedAt,
1447
- inputsByPort: state.pending.inputsByPort,
1448
- outputs: args.outputs
1449
- });
1450
- const completedActivations = (state.engineCounters?.completedNodeActivations ?? 0) + 1;
1451
- const engineCounters = { completedNodeActivations: completedActivations };
1452
- const maxNodeActivations = state.executionOptions?.maxNodeActivations ?? Number.MAX_SAFE_INTEGER;
1453
- if (this.semantics.isStopConditionSatisfied(state.control?.stopCondition, args.nodeId)) {
1454
- const completedState = this.persistedRunStateTerminalBuilder.mergeTerminal({
1455
- state,
1456
- engineCounters,
1457
- status: "completed",
1458
- queue: [],
1459
- outputsByNode: data.dump(),
1460
- nodeSnapshotsByNodeId: {
1461
- ...state.nodeSnapshotsByNodeId ?? {},
1462
- [args.nodeId]: completedSnapshot
1463
- }
1464
- });
1465
- await this.runStore.save(completedState);
1466
- await this.nodeEventPublisher.publish("nodeCompleted", completedSnapshot);
1467
- await this.terminalPersistence.maybeDeleteAfterTerminalState({
1468
- workflow: wf,
1469
- state: completedState,
1470
- finalStatus: "completed",
1471
- finishedAt: completedAt
1472
- });
1473
- const result$1 = {
1474
- runId: state.runId,
1475
- workflowId: state.workflowId,
1476
- startedAt: state.startedAt,
1477
- status: "completed",
1478
- outputs: this.semantics.resolveResultOutputs(wf, state.control?.stopCondition, data.dump())
1479
- };
1480
- this.waiters.resolveRunCompletion(result$1);
1481
- return result$1;
1482
- }
1483
- const batchId = state.pending.batchId ?? "batch_1";
1484
- const queue = (state.queue ?? []).map((q) => ({
1485
- ...q,
1486
- batchId: q.batchId ?? batchId
1487
- }));
1488
- const nextNodeSnapshotsByNodeId = {
1489
- ...state.nodeSnapshotsByNodeId ?? {},
1490
- [args.nodeId]: completedSnapshot
1491
- };
1492
- planner.applyOutputs(queue, {
1493
- fromNodeId: args.nodeId,
1494
- outputs: args.outputs,
1495
- batchId
1496
- });
1497
- this.semantics.applyPinnedQueueSkips({
1498
- runId: state.runId,
1499
- workflowId: state.workflowId,
1500
- parent: state.parent,
1501
- mutableState: state.mutableState,
1502
- planner,
1503
- queue,
1504
- data,
1505
- nodeSnapshotsByNodeId: nextNodeSnapshotsByNodeId,
1506
- finishedAt: completedAt
1507
- });
1508
- let next;
1509
- try {
1510
- next = planner.nextActivation(queue);
1511
- } catch (cause) {
1512
- const completedDefinition = topology.defsById.get(args.nodeId);
1513
- const completedNodeLabel = RuntimeContinuationDiagnostics.formatNodeLabel({
1514
- definition: completedDefinition,
1515
- nodeId: args.nodeId
1516
- });
1517
- const reason = cause instanceof Error ? cause.message : String(cause);
1518
- throw new Error(`After completing ${completedNodeLabel}, the engine could not plan the next activation. ${reason} Outputs: ${RuntimeContinuationDiagnostics.formatOutputCounts(args.outputs)}.`, { cause });
1519
- }
1520
- if (!next) {
1521
- const lastNodeId = createWorkflowExecutableNodeClassifier(wf).lastExecutableNodeIdInDefinitionOrder(wf);
1522
- const outputs = data.getOutputItems(lastNodeId, "main");
1523
- const completedState = this.persistedRunStateTerminalBuilder.mergeTerminal({
1524
- state,
1525
- engineCounters,
1526
- status: "completed",
1527
- queue: [],
1528
- outputsByNode: data.dump(),
1529
- nodeSnapshotsByNodeId: nextNodeSnapshotsByNodeId
1530
- });
1531
- await this.runStore.save(completedState);
1532
- await this.nodeEventPublisher.publish("nodeCompleted", completedSnapshot);
1533
- await this.terminalPersistence.maybeDeleteAfterTerminalState({
1534
- workflow: wf,
1535
- state: completedState,
1536
- finalStatus: "completed",
1537
- finishedAt: completedAt
1538
- });
1539
- const result$1 = {
1540
- runId: state.runId,
1541
- workflowId: state.workflowId,
1542
- startedAt: state.startedAt,
1543
- status: "completed",
1544
- outputs
1545
- };
1546
- this.waiters.resolveRunCompletion(result$1);
1547
- return result$1;
1548
- }
1549
- if (completedActivations >= maxNodeActivations) {
1550
- const message = `Run exceeded maxNodeActivations (${maxNodeActivations}) after ${completedActivations} completed node activations (next would be ${next.nodeId}).`;
1551
- const failedState = this.persistedRunStateTerminalBuilder.mergeTerminal({
1552
- state,
1553
- engineCounters,
1554
- status: "failed",
1555
- queue: queue.map((q) => ({ ...q })),
1556
- outputsByNode: data.dump(),
1557
- nodeSnapshotsByNodeId: nextNodeSnapshotsByNodeId
1558
- });
1559
- await this.runStore.save(failedState);
1560
- await this.nodeEventPublisher.publish("nodeCompleted", completedSnapshot);
1561
- await this.terminalPersistence.maybeDeleteAfterTerminalState({
1562
- workflow: wf,
1563
- state: failedState,
1564
- finalStatus: "failed",
1565
- finishedAt: completedAt
1566
- });
1567
- const result$1 = {
1568
- runId: state.runId,
1569
- workflowId: state.workflowId,
1570
- startedAt: state.startedAt,
1571
- status: "failed",
1572
- error: { message }
1573
- };
1574
- this.waiters.resolveRunCompletion(result$1);
1575
- return result$1;
1576
- }
1577
- const def = topology.defsById.get(next.nodeId);
1578
- if (!def || def.kind !== "node") throw new Error(`Node ${next.nodeId} is not a runnable node`);
1579
- const request = this.nodeActivationRequestComposer.createFromPlannedActivation({
1580
- next,
1581
- base,
1582
- data,
1583
- runId: state.runId,
1584
- workflowId: state.workflowId,
1585
- parent: state.parent,
1586
- executionOptions: state.executionOptions,
1587
- nodeDefinition: def
1588
- });
1589
- const { queuedSnapshot, result } = await this.activationEnqueueService.enqueueActivationWithSnapshot({
1590
- runId: state.runId,
1591
- workflowId: state.workflowId,
1592
- startedAt: state.startedAt,
1593
- parent: state.parent,
1594
- executionOptions: state.executionOptions,
1595
- control: state.control,
1596
- workflowSnapshot: state.workflowSnapshot,
1597
- mutableState: state.mutableState,
1598
- policySnapshot: state.policySnapshot,
1599
- pendingQueue: queue,
1600
- request,
1601
- previousNodeSnapshotsByNodeId: nextNodeSnapshotsByNodeId,
1602
- planner,
1603
- engineCounters,
1604
- connectionInvocations: state.connectionInvocations ?? []
1605
- });
1606
- await this.nodeEventPublisher.publish("nodeCompleted", completedSnapshot);
1607
- await this.nodeEventPublisher.publish("nodeQueued", queuedSnapshot);
1608
- return result;
1609
- }
1610
- async resumeFromNodeError(args) {
1611
- const state = await this.runStore.load(args.runId);
1612
- if (!state) throw new Error(`Unknown runId: ${args.runId}`);
1613
- if (state.status !== "pending" || !state.pending) throw new Error(`Run ${args.runId} is not pending`);
1614
- if (state.pending.activationId !== args.activationId) throw new Error(`activationId mismatch for run ${args.runId}`);
1615
- if (state.pending.nodeId !== args.nodeId) throw new Error(`nodeId mismatch for run ${args.runId}`);
1616
- const wf = this.resolvePersistedWorkflow(state);
1617
- if (!wf) throw new Error(`Unknown workflowId: ${state.workflowId}`);
1618
- const failedDefinition = WorkflowTopology.fromWorkflow(wf).defsById.get(args.nodeId);
1619
- const webhookControlSignal = state.executionOptions?.webhook && failedDefinition?.kind === "trigger" ? this.asWebhookControlSignal(args.error) : void 0;
1620
- if (webhookControlSignal) return await this.resumeFromWebhookControl({
1621
- state,
1622
- workflow: wf,
1623
- args,
1624
- signal: webhookControlSignal
1625
- });
1626
- if (failedDefinition && failedDefinition.kind === "node") {
1627
- const nodeHandler = this.policyErrorServices.resolveNodeErrorHandler(failedDefinition.config.nodeErrorHandler);
1628
- if (nodeHandler) try {
1629
- const ctx = this.buildNodeExecutionContextForPending(state, wf, failedDefinition, args.nodeId);
1630
- const inputsByPort = state.pending.inputsByPort;
1631
- const portKeys = Object.keys(inputsByPort);
1632
- const kind = portKeys.length === 1 && portKeys[0] === "in" ? "single" : "multi";
1633
- const items = inputsByPort.in ?? [];
1634
- const recovered = await nodeHandler.handle({
1635
- kind,
1636
- items,
1637
- inputsByPort: kind === "multi" ? inputsByPort : void 0,
1638
- ctx,
1639
- error: args.error
1640
- });
1641
- return await this.resumeFromNodeResult({
1642
- runId: args.runId,
1643
- activationId: args.activationId,
1644
- nodeId: args.nodeId,
1645
- outputs: recovered
1646
- });
1647
- } catch {}
1648
- }
1649
- const finishedAt = (/* @__PURE__ */ new Date()).toISOString();
1650
- const message = args.error?.message ?? String(args.error);
1651
- const failedSnapshot = NodeSnapshotFactory.failed({
1652
- previous: state.nodeSnapshotsByNodeId?.[args.nodeId],
1653
- runId: state.runId,
1654
- workflowId: state.workflowId,
1655
- nodeId: args.nodeId,
1656
- activationId: args.activationId,
1657
- parent: state.parent,
1658
- finishedAt,
1659
- inputsByPort: state.pending.inputsByPort,
1660
- error: args.error
1661
- });
1662
- const failedState = this.persistedRunStateTerminalBuilder.mergeTerminal({
1663
- state,
1664
- engineCounters: state.engineCounters ?? { completedNodeActivations: 0 },
1665
- status: "failed",
1666
- queue: (state.queue ?? []).map((q) => ({ ...q })),
1667
- outputsByNode: state.outputsByNode,
1668
- nodeSnapshotsByNodeId: {
1669
- ...state.nodeSnapshotsByNodeId ?? {},
1670
- [args.nodeId]: failedSnapshot
1671
- }
1672
- });
1673
- await this.runStore.save(failedState);
1674
- await this.nodeEventPublisher.publish("nodeFailed", failedSnapshot);
1675
- const wfErr = this.policyErrorServices.resolveWorkflowErrorHandler(wf.workflowErrorHandler);
1676
- if (wfErr) await Promise.resolve(wfErr.onError({
1677
- runId: state.runId,
1678
- workflowId: state.workflowId,
1679
- workflow: wf,
1680
- failedNodeId: args.nodeId,
1681
- error: args.error,
1682
- startedAt: state.startedAt,
1683
- finishedAt
1684
- }));
1685
- await this.terminalPersistence.maybeDeleteAfterTerminalState({
1686
- workflow: wf,
1687
- state: failedState,
1688
- finalStatus: "failed",
1689
- finishedAt
1690
- });
1691
- const result = {
1692
- runId: state.runId,
1693
- workflowId: state.workflowId,
1694
- startedAt: state.startedAt,
1695
- status: "failed",
1696
- error: { message }
1697
- };
1698
- this.waiters.resolveRunCompletion(result);
1699
- return result;
1700
- }
1701
- async resumeFromStepResult(args) {
1702
- return await this.resumeFromNodeResult(args);
1703
- }
1704
- async resumeFromStepError(args) {
1705
- return await this.resumeFromNodeError(args);
1706
- }
1707
- async waitForCompletion(runId) {
1708
- const existing = await this.runStore.load(runId);
1709
- if (existing?.status === "completed") {
1710
- const wf = this.resolvePersistedWorkflow(existing);
1711
- const outputs = wf ? this.semantics.resolveResultOutputs(wf, existing.control?.stopCondition, existing.outputsByNode) : [];
1712
- return {
1713
- runId: existing.runId,
1714
- workflowId: existing.workflowId,
1715
- startedAt: existing.startedAt,
1716
- status: "completed",
1717
- outputs
1718
- };
1719
- }
1720
- if (existing?.status === "failed") return {
1721
- runId: existing.runId,
1722
- workflowId: existing.workflowId,
1723
- startedAt: existing.startedAt,
1724
- status: "failed",
1725
- error: { message: "Run failed" }
1726
- };
1727
- const result = await this.waiters.waitForCompletion(runId);
1728
- if (result.status !== "completed" && result.status !== "failed") throw new Error(`Unexpected run completion status: ${result.status}`);
1729
- return result;
1730
- }
1731
- async waitForWebhookResponse(runId) {
1732
- return await this.waiters.waitForWebhookResponse(runId);
1733
- }
1734
- async resumeFromWebhookControl(args) {
1735
- const data = this.runDataFactory.create(args.state.outputsByNode);
1736
- const { topology, planner } = this.planningFactory.create(args.workflow);
1737
- const triggerOutputs = { main: args.signal.kind === "respondNowAndContinue" ? args.signal.continueItems ?? [] : args.signal.responseItems };
1738
- data.setOutputs(args.args.nodeId, triggerOutputs);
1739
- const completedSnapshot = this.semantics.createFinishedSnapshot({
1740
- workflow: args.workflow,
1741
- previous: args.state.nodeSnapshotsByNodeId?.[args.args.nodeId],
1742
- runId: args.state.runId,
1743
- workflowId: args.state.workflowId,
1744
- nodeId: args.args.nodeId,
1745
- activationId: args.args.activationId,
1746
- parent: args.state.parent,
1747
- finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
1748
- inputsByPort: args.state.pending?.inputsByPort ?? InputPortMap.empty(),
1749
- outputs: triggerOutputs
1750
- });
1751
- const completedActivations = (args.state.engineCounters?.completedNodeActivations ?? 0) + 1;
1752
- const engineCounters = { completedNodeActivations: completedActivations };
1753
- const maxNodeActivations = args.state.executionOptions?.maxNodeActivations ?? Number.MAX_SAFE_INTEGER;
1754
- if (this.semantics.isStopConditionSatisfied(args.state.control?.stopCondition, args.args.nodeId)) {
1755
- const completedState = this.persistedRunStateTerminalBuilder.mergeTerminal({
1756
- state: args.state,
1757
- engineCounters,
1758
- status: "completed",
1759
- queue: [],
1760
- outputsByNode: data.dump(),
1761
- nodeSnapshotsByNodeId: {
1762
- ...args.state.nodeSnapshotsByNodeId ?? {},
1763
- [args.args.nodeId]: completedSnapshot
1764
- }
1765
- });
1766
- await this.runStore.save(completedState);
1767
- await this.nodeEventPublisher.publish("nodeCompleted", completedSnapshot);
1768
- await this.terminalPersistence.maybeDeleteAfterTerminalState({
1769
- workflow: args.workflow,
1770
- state: completedState,
1771
- finalStatus: "completed",
1772
- finishedAt: completedSnapshot.finishedAt ?? completedSnapshot.updatedAt
1773
- });
1774
- this.waiters.resolveWebhookResponse({
1775
- runId: args.state.runId,
1776
- workflowId: args.state.workflowId,
1777
- startedAt: args.state.startedAt,
1778
- runStatus: "completed",
1779
- response: args.signal.responseItems
1780
- });
1781
- const result$1 = {
1782
- runId: args.state.runId,
1783
- workflowId: args.state.workflowId,
1784
- startedAt: args.state.startedAt,
1785
- status: "completed",
1786
- outputs: this.semantics.resolveResultOutputs(args.workflow, args.state.control?.stopCondition, data.dump())
1787
- };
1788
- this.waiters.resolveRunCompletion(result$1);
1789
- return result$1;
1790
- }
1791
- if (args.signal.kind === "respondNow") {
1792
- const completedState = this.persistedRunStateTerminalBuilder.mergeTerminal({
1793
- state: args.state,
1794
- engineCounters,
1795
- status: "completed",
1796
- queue: [],
1797
- outputsByNode: data.dump(),
1798
- nodeSnapshotsByNodeId: {
1799
- ...args.state.nodeSnapshotsByNodeId ?? {},
1800
- [args.args.nodeId]: completedSnapshot
1801
- }
1802
- });
1803
- await this.runStore.save(completedState);
1804
- await this.nodeEventPublisher.publish("nodeCompleted", completedSnapshot);
1805
- await this.terminalPersistence.maybeDeleteAfterTerminalState({
1806
- workflow: args.workflow,
1807
- state: completedState,
1808
- finalStatus: "completed",
1809
- finishedAt: completedSnapshot.finishedAt ?? completedSnapshot.updatedAt
1810
- });
1811
- const result$1 = {
1812
- runId: args.state.runId,
1813
- workflowId: args.state.workflowId,
1814
- startedAt: args.state.startedAt,
1815
- status: "completed",
1816
- outputs: args.signal.responseItems
1817
- };
1818
- this.waiters.resolveWebhookResponse({
1819
- runId: args.state.runId,
1820
- workflowId: args.state.workflowId,
1821
- startedAt: args.state.startedAt,
1822
- runStatus: "completed",
1823
- response: args.signal.responseItems
1824
- });
1825
- this.waiters.resolveRunCompletion(result$1);
1826
- return result$1;
1827
- }
1828
- const batchId = args.state.pending?.batchId ?? "batch_1";
1829
- const queue = (args.state.queue ?? []).map((entry) => ({
1830
- ...entry,
1831
- batchId: entry.batchId ?? batchId
1832
- }));
1833
- planner.applyOutputs(queue, {
1834
- fromNodeId: args.args.nodeId,
1835
- outputs: triggerOutputs,
1836
- batchId
1837
- });
1838
- const next = planner.nextActivation(queue);
1839
- if (!next) {
1840
- const lastNodeId = createWorkflowExecutableNodeClassifier(args.workflow).lastExecutableNodeIdInDefinitionOrder(args.workflow);
1841
- const outputs = data.getOutputItems(lastNodeId, "main");
1842
- const completedState = this.persistedRunStateTerminalBuilder.mergeTerminal({
1843
- state: args.state,
1844
- engineCounters,
1845
- status: "completed",
1846
- queue: [],
1847
- outputsByNode: data.dump(),
1848
- nodeSnapshotsByNodeId: {
1849
- ...args.state.nodeSnapshotsByNodeId ?? {},
1850
- [args.args.nodeId]: completedSnapshot
1851
- }
1852
- });
1853
- await this.runStore.save(completedState);
1854
- await this.nodeEventPublisher.publish("nodeCompleted", completedSnapshot);
1855
- await this.terminalPersistence.maybeDeleteAfterTerminalState({
1856
- workflow: args.workflow,
1857
- state: completedState,
1858
- finalStatus: "completed",
1859
- finishedAt: completedSnapshot.finishedAt ?? completedSnapshot.updatedAt
1860
- });
1861
- const result$1 = {
1862
- runId: args.state.runId,
1863
- workflowId: args.state.workflowId,
1864
- startedAt: args.state.startedAt,
1865
- status: "completed",
1866
- outputs
1867
- };
1868
- this.waiters.resolveWebhookResponse({
1869
- runId: args.state.runId,
1870
- workflowId: args.state.workflowId,
1871
- startedAt: args.state.startedAt,
1872
- runStatus: "completed",
1873
- response: args.signal.responseItems
1874
- });
1875
- this.waiters.resolveRunCompletion(result$1);
1876
- return result$1;
1877
- }
1878
- if (completedActivations >= maxNodeActivations) {
1879
- const message = `Run exceeded maxNodeActivations (${maxNodeActivations}) after ${completedActivations} completed node activations (next would be ${next.nodeId}).`;
1880
- const failedState = this.persistedRunStateTerminalBuilder.mergeTerminal({
1881
- state: args.state,
1882
- engineCounters,
1883
- status: "failed",
1884
- queue: queue.map((q) => ({ ...q })),
1885
- outputsByNode: data.dump(),
1886
- nodeSnapshotsByNodeId: {
1887
- ...args.state.nodeSnapshotsByNodeId ?? {},
1888
- [args.args.nodeId]: completedSnapshot
1889
- }
1890
- });
1891
- await this.runStore.save(failedState);
1892
- await this.nodeEventPublisher.publish("nodeCompleted", completedSnapshot);
1893
- await this.terminalPersistence.maybeDeleteAfterTerminalState({
1894
- workflow: args.workflow,
1895
- state: failedState,
1896
- finalStatus: "failed",
1897
- finishedAt: completedSnapshot.finishedAt ?? completedSnapshot.updatedAt
1898
- });
1899
- const result$1 = {
1900
- runId: args.state.runId,
1901
- workflowId: args.state.workflowId,
1902
- startedAt: args.state.startedAt,
1903
- status: "failed",
1904
- error: { message }
1905
- };
1906
- this.waiters.resolveWebhookResponse({
1907
- runId: args.state.runId,
1908
- workflowId: args.state.workflowId,
1909
- startedAt: args.state.startedAt,
1910
- runStatus: "pending",
1911
- response: args.signal.responseItems
1912
- });
1913
- this.waiters.resolveRunCompletion(result$1);
1914
- return result$1;
1915
- }
1916
- const nextDefinition = topology.defsById.get(next.nodeId);
1917
- if (!nextDefinition || nextDefinition.kind !== "node") throw new Error(`Node ${next.nodeId} is not a runnable node`);
1918
- const webhookLimits = this.resolveEngineLimitsFromState(args.state);
1919
- const base = this.runExecutionContextFactory.create({
1920
- runId: args.state.runId,
1921
- workflowId: args.state.workflowId,
1922
- nodeId: nextDefinition.id,
1923
- parent: args.state.parent,
1924
- subworkflowDepth: args.state.executionOptions?.subworkflowDepth ?? 0,
1925
- engineMaxNodeActivations: webhookLimits.engineMaxNodeActivations,
1926
- engineMaxSubworkflowDepth: webhookLimits.engineMaxSubworkflowDepth,
1927
- data,
1928
- nodeState: this.nodeStatePublisherFactory.create(args.state.runId, args.state.workflowId, args.state.parent)
1929
- });
1930
- const request = this.nodeActivationRequestComposer.createFromPlannedActivation({
1931
- next,
1932
- base,
1933
- data,
1934
- runId: args.state.runId,
1935
- workflowId: args.state.workflowId,
1936
- parent: args.state.parent,
1937
- executionOptions: args.state.executionOptions,
1938
- nodeDefinition: nextDefinition
1939
- });
1940
- const { queuedSnapshot, result } = await this.activationEnqueueService.enqueueActivationWithSnapshot({
1941
- runId: args.state.runId,
1942
- workflowId: args.state.workflowId,
1943
- startedAt: args.state.startedAt,
1944
- parent: args.state.parent,
1945
- executionOptions: args.state.executionOptions,
1946
- control: args.state.control,
1947
- workflowSnapshot: args.state.workflowSnapshot,
1948
- mutableState: args.state.mutableState,
1949
- policySnapshot: args.state.policySnapshot,
1950
- pendingQueue: queue,
1951
- request,
1952
- previousNodeSnapshotsByNodeId: {
1953
- ...args.state.nodeSnapshotsByNodeId ?? {},
1954
- [args.args.nodeId]: completedSnapshot
1955
- },
1956
- planner,
1957
- engineCounters,
1958
- connectionInvocations: args.state.connectionInvocations ?? []
1959
- });
1960
- await this.nodeEventPublisher.publish("nodeCompleted", completedSnapshot);
1961
- await this.nodeEventPublisher.publish("nodeQueued", queuedSnapshot);
1962
- this.waiters.resolveWebhookResponse({
1963
- runId: args.state.runId,
1964
- workflowId: args.state.workflowId,
1965
- startedAt: args.state.startedAt,
1966
- runStatus: "pending",
1967
- response: args.signal.responseItems
1968
- });
1969
- return result;
1970
- }
1971
- asWebhookControlSignal(error) {
1972
- const candidate = error;
1973
- if (!candidate || candidate.__webhookControl !== true) return void 0;
1974
- if (candidate.kind !== "respondNow" && candidate.kind !== "respondNowAndContinue") return void 0;
1975
- if (!Array.isArray(candidate.responseItems)) return void 0;
1976
- return candidate;
1977
- }
1978
- resolvePersistedWorkflow(state) {
1979
- return this.workflowSnapshotResolver.resolve({
1980
- workflowId: state.workflowId,
1981
- workflowSnapshot: state.workflowSnapshot
1982
- });
1983
- }
1984
- buildNodeExecutionContextForPending(state, wf, def, nodeId) {
1985
- const data = this.runDataFactory.create(state.outputsByNode);
1986
- const limits = this.resolveEngineLimitsFromState(state);
1987
- const base = this.runExecutionContextFactory.create({
1988
- runId: state.runId,
1989
- workflowId: state.workflowId,
1990
- nodeId,
1991
- parent: state.parent,
1992
- subworkflowDepth: state.executionOptions?.subworkflowDepth ?? 0,
1993
- engineMaxNodeActivations: limits.engineMaxNodeActivations,
1994
- engineMaxSubworkflowDepth: limits.engineMaxSubworkflowDepth,
1995
- data,
1996
- nodeState: this.nodeStatePublisherFactory.create(state.runId, state.workflowId, state.parent)
1997
- });
1998
- const activationId = state.pending.activationId;
1999
- return {
2000
- ...base,
2001
- data,
2002
- nodeId,
2003
- activationId,
2004
- config: def.config,
2005
- binary: base.binary.forNode({
2006
- nodeId,
2007
- activationId
2008
- }),
2009
- getCredential: this.credentialResolverFactory.create(wf.id, nodeId, def.config)
2010
- };
2011
- }
2012
- resolveEngineLimitsFromState(state) {
2013
- const fb = this.executionLimitsPolicy.createRootExecutionOptions();
2014
- return {
2015
- engineMaxNodeActivations: state.executionOptions?.maxNodeActivations ?? fb.maxNodeActivations,
2016
- engineMaxSubworkflowDepth: state.executionOptions?.maxSubworkflowDepth ?? fb.maxSubworkflowDepth
2017
- };
2018
- }
2019
- };
2020
-
2021
- //#endregion
2022
- //#region src/engine/materialization/MissingRuntimeExecutionMarkerFactory.ts
2023
- var MissingRuntimeExecutionMarker = class {
2024
- static isMarked(config) {
2025
- return Boolean(config?.missingRuntime);
2026
- }
2027
- };
2028
-
2029
- //#endregion
2030
- //#region src/engine/execution/RunStateSemantics.ts
2031
- var RunStateSemantics = class {
2032
- isStopConditionSatisfied(stopCondition, nodeId) {
2033
- if (!stopCondition || stopCondition.kind === "workflowCompleted") return false;
2034
- return stopCondition.nodeId === nodeId;
2035
- }
2036
- resolveResultOutputs(workflow, stopCondition, outputsByNode) {
2037
- if (stopCondition?.kind === "nodeCompleted") return outputsByNode[stopCondition.nodeId]?.main ?? [];
2038
- return outputsByNode[createWorkflowExecutableNodeClassifier(workflow).lastExecutableNodeIdInDefinitionOrder(workflow)]?.main ?? [];
2039
- }
2040
- applySkippedSnapshots(args) {
2041
- const snapshots = { ...args.currentState.nodeSnapshotsByNodeId };
2042
- const skippedPinnedNodeIds = new Set(args.preservedPinnedNodeIds.filter((nodeId) => args.skippedNodeIds.includes(nodeId)));
2043
- for (const nodeId of args.skippedNodeIds) if (args.currentState.mutableState?.nodesById?.[nodeId]?.pinnedOutputsByPort) skippedPinnedNodeIds.add(nodeId);
2044
- for (const nodeId of skippedPinnedNodeIds) {
2045
- const previous = snapshots[nodeId];
2046
- snapshots[nodeId] = NodeSnapshotFactory.completed({
2047
- previous,
2048
- runId: args.runId,
2049
- workflowId: args.workflowId,
2050
- nodeId,
2051
- activationId: previous?.activationId ?? `synthetic_${nodeId}`,
2052
- parent: args.parent,
2053
- finishedAt: args.finishedAt,
2054
- inputsByPort: previous?.inputsByPort ?? InputPortMap.empty(),
2055
- outputs: args.currentState.outputsByNode[nodeId] ?? {},
2056
- fromPinnedOutput: true
2057
- });
2058
- }
2059
- return snapshots;
2060
- }
2061
- applyPinnedQueueSkips(args) {
2062
- let changed = true;
2063
- while (changed) {
2064
- changed = false;
2065
- for (let index = 0; index < args.queue.length; index += 1) {
2066
- const queueEntry = args.queue[index];
2067
- const pinnedOutputs = args.mutableState?.nodesById?.[queueEntry.nodeId]?.pinnedOutputsByPort;
2068
- if (!pinnedOutputs) continue;
2069
- args.queue.splice(index, 1);
2070
- const previous = args.nodeSnapshotsByNodeId[queueEntry.nodeId];
2071
- args.nodeSnapshotsByNodeId[queueEntry.nodeId] = NodeSnapshotFactory.completed({
2072
- previous,
2073
- runId: args.runId,
2074
- workflowId: args.workflowId,
2075
- nodeId: queueEntry.nodeId,
2076
- activationId: previous?.activationId ?? `synthetic_${queueEntry.nodeId}`,
2077
- parent: args.parent,
2078
- finishedAt: args.finishedAt,
2079
- inputsByPort: this.resolveQueueEntryInputsByPort(queueEntry),
2080
- outputs: pinnedOutputs,
2081
- fromPinnedOutput: true
2082
- });
2083
- args.data.setOutputs(queueEntry.nodeId, pinnedOutputs);
2084
- args.planner.applyOutputs(args.queue, {
2085
- fromNodeId: queueEntry.nodeId,
2086
- outputs: pinnedOutputs,
2087
- batchId: queueEntry.batchId ?? "batch_1"
2088
- });
2089
- changed = true;
2090
- break;
2091
- }
2092
- }
2093
- }
2094
- createFinishedSnapshot(args) {
2095
- const definition = args.workflow.nodes.find((node) => node.id === args.nodeId);
2096
- if (MissingRuntimeExecutionMarker.isMarked(definition?.config)) return NodeSnapshotFactory.skipped(args);
2097
- return NodeSnapshotFactory.completed(args);
2098
- }
2099
- resolveQueueEntryInputsByPort(queueEntry) {
2100
- if (queueEntry.collect) return queueEntry.collect.received;
2101
- return { [queueEntry.toInput ?? "in"]: queueEntry.input };
2102
- }
2103
- };
2104
-
2105
- //#endregion
2106
- //#region src/engine/execution/WorkflowRunExecutionContextFactory.ts
2107
- /**
2108
- * Shared {@link ExecutionContextFactory#create} wiring for workflow runners (base context before node-specific fields).
2109
- */
2110
- var WorkflowRunExecutionContextFactory = class {
2111
- constructor(executionContextFactory, credentialResolverFactory) {
2112
- this.executionContextFactory = executionContextFactory;
2113
- this.credentialResolverFactory = credentialResolverFactory;
2114
- }
2115
- create(args) {
2116
- return this.executionContextFactory.create({
2117
- runId: args.runId,
2118
- workflowId: args.workflowId,
2119
- parent: args.parent,
2120
- subworkflowDepth: args.subworkflowDepth,
2121
- engineMaxNodeActivations: args.engineMaxNodeActivations,
2122
- engineMaxSubworkflowDepth: args.engineMaxSubworkflowDepth,
2123
- data: args.data,
2124
- nodeState: args.nodeState,
2125
- getCredential: this.credentialResolverFactory.create(args.workflowId, args.nodeId)
2126
- });
2127
- }
2128
- };
2129
-
2130
- //#endregion
2131
- //#region src/engine/execution/WorkflowRunStarter.ts
2132
- var WorkflowRunStarter = class {
2133
- constructor(runIdFactory, runStore, runDataFactory, workflowSnapshotFactory, planningFactory, nodeStatePublisherFactory, runExecutionContextFactory, nodeActivationRequestComposer, activationEnqueueService, waiters, workflowPolicyRuntimeDefaults, executionLimitsPolicy) {
2134
- this.runIdFactory = runIdFactory;
2135
- this.runStore = runStore;
2136
- this.runDataFactory = runDataFactory;
2137
- this.workflowSnapshotFactory = workflowSnapshotFactory;
2138
- this.planningFactory = planningFactory;
2139
- this.nodeStatePublisherFactory = nodeStatePublisherFactory;
2140
- this.runExecutionContextFactory = runExecutionContextFactory;
2141
- this.nodeActivationRequestComposer = nodeActivationRequestComposer;
2142
- this.activationEnqueueService = activationEnqueueService;
2143
- this.waiters = waiters;
2144
- this.workflowPolicyRuntimeDefaults = workflowPolicyRuntimeDefaults;
2145
- this.executionLimitsPolicy = executionLimitsPolicy;
2146
- }
2147
- async runWorkflow(wf, startAt, items, parent, executionOptions, persistedStateOverrides) {
2148
- const runId = this.runIdFactory.makeRunId();
2149
- const startedAt = (/* @__PURE__ */ new Date()).toISOString();
2150
- const workflowSnapshot = persistedStateOverrides?.workflowSnapshot ?? this.workflowSnapshotFactory.create(wf);
2151
- const mutableState = persistedStateOverrides?.mutableState;
2152
- const policySnapshot = RunPolicySnapshotFactory.create(wf, this.workflowPolicyRuntimeDefaults);
2153
- const mergedExecutionOptions = this.executionLimitsPolicy.mergeExecutionOptionsForNewRun(parent, executionOptions);
2154
- await this.runStore.createRun({
2155
- runId,
2156
- workflowId: wf.id,
2157
- startedAt,
2158
- parent,
2159
- executionOptions: mergedExecutionOptions,
2160
- workflowSnapshot,
2161
- mutableState,
2162
- policySnapshot,
2163
- engineCounters: { completedNodeActivations: 0 }
2164
- });
2165
- const data = this.runDataFactory.create();
2166
- const base = this.runExecutionContextFactory.create({
2167
- runId,
2168
- workflowId: wf.id,
2169
- nodeId: startAt,
2170
- parent,
2171
- subworkflowDepth: mergedExecutionOptions.subworkflowDepth ?? 0,
2172
- engineMaxNodeActivations: mergedExecutionOptions.maxNodeActivations,
2173
- engineMaxSubworkflowDepth: mergedExecutionOptions.maxSubworkflowDepth,
2174
- data,
2175
- nodeState: this.nodeStatePublisherFactory.create(runId, wf.id, parent)
2176
- });
2177
- const { topology, planner } = this.planningFactory.create(wf);
2178
- const startDef = topology.defsById.get(startAt);
2179
- if (!startDef) throw new Error(`Unknown start nodeId: ${startAt}`);
2180
- const batchId = "batch_1";
2181
- const queue = [];
2182
- const initialNodeSnapshotsByNodeId = {};
2183
- if (startDef.kind === "trigger") {
2184
- const request$1 = this.nodeActivationRequestComposer.createSingleFromDefinition({
2185
- runId,
2186
- workflowId: wf.id,
2187
- definition: startDef,
2188
- parent,
2189
- executionOptions: mergedExecutionOptions,
2190
- batchId,
2191
- input: items,
2192
- base,
2193
- data
2194
- });
2195
- return await this.activationEnqueueService.enqueueActivation({
2196
- runId,
2197
- workflowId: wf.id,
2198
- startedAt,
2199
- parent,
2200
- executionOptions: mergedExecutionOptions,
2201
- workflowSnapshot,
2202
- mutableState,
2203
- policySnapshot,
2204
- control: void 0,
2205
- pendingQueue: [],
2206
- request: request$1,
2207
- previousNodeSnapshotsByNodeId: initialNodeSnapshotsByNodeId,
2208
- planner,
2209
- engineCounters: { completedNodeActivations: 0 },
2210
- connectionInvocations: []
2211
- });
2212
- }
2213
- queue.push({
2214
- nodeId: startAt,
2215
- input: items,
2216
- toInput: "in",
2217
- batchId
2218
- });
2219
- const next = planner.nextActivation(queue);
2220
- if (!next) {
2221
- const lastNodeId = createWorkflowExecutableNodeClassifier(wf).lastExecutableNodeIdInDefinitionOrder(wf);
2222
- const outputs = data.getOutputItems(lastNodeId, "main");
2223
- await this.runStore.save({
2224
- runId,
2225
- workflowId: wf.id,
2226
- startedAt,
2227
- parent,
2228
- executionOptions: mergedExecutionOptions,
2229
- workflowSnapshot,
2230
- mutableState,
2231
- policySnapshot,
2232
- engineCounters: { completedNodeActivations: 0 },
2233
- connectionInvocations: [],
2234
- status: "completed",
2235
- pending: void 0,
2236
- queue: [],
2237
- outputsByNode: data.dump(),
2238
- nodeSnapshotsByNodeId: initialNodeSnapshotsByNodeId
2239
- });
2240
- const result = {
2241
- runId,
2242
- workflowId: wf.id,
2243
- startedAt,
2244
- status: "completed",
2245
- outputs
2246
- };
2247
- this.waiters.resolveRunCompletion(result);
2248
- return result;
2249
- }
2250
- const def = topology.defsById.get(next.nodeId);
2251
- if (!def || def.kind !== "node") throw new Error(`Node ${next.nodeId} is not a runnable node`);
2252
- const request = this.nodeActivationRequestComposer.createFromPlannedActivation({
2253
- next,
2254
- base,
2255
- data,
2256
- runId,
2257
- workflowId: wf.id,
2258
- parent,
2259
- executionOptions: mergedExecutionOptions,
2260
- nodeDefinition: def
2261
- });
2262
- return await this.activationEnqueueService.enqueueActivation({
2263
- runId,
2264
- workflowId: wf.id,
2265
- startedAt,
2266
- parent,
2267
- executionOptions: mergedExecutionOptions,
2268
- control: void 0,
2269
- workflowSnapshot,
2270
- mutableState,
2271
- policySnapshot,
2272
- pendingQueue: queue,
2273
- request,
2274
- previousNodeSnapshotsByNodeId: initialNodeSnapshotsByNodeId,
2275
- planner,
2276
- engineCounters: { completedNodeActivations: 0 },
2277
- connectionInvocations: []
2278
- });
2279
- }
2280
- };
2281
-
2282
- //#endregion
2283
- //#region src/engine/policies/RunTerminalPersistenceCoordinator.ts
2284
- var RunTerminalPersistenceCoordinator = class {
2285
- constructor(runStore, storageEvaluator) {
2286
- this.runStore = runStore;
2287
- this.storageEvaluator = storageEvaluator;
2288
- }
2289
- async maybeDeleteAfterTerminalState(args) {
2290
- if (await this.storageEvaluator.shouldPersist(args.workflow, args.state.policySnapshot, {
2291
- runId: args.state.runId,
2292
- workflowId: args.state.workflowId,
2293
- workflow: args.workflow,
2294
- finalStatus: args.finalStatus,
2295
- startedAt: args.state.startedAt,
2296
- finishedAt: args.finishedAt
2297
- })) return;
2298
- if (!this.runStore.deleteRun) return;
2299
- await this.runStore.deleteRun(args.state.runId);
2300
- }
2301
- };
2302
-
2303
- //#endregion
2304
- //#region src/engine/policies/WorkflowPolicyErrorServices.ts
2305
- var WorkflowPolicyErrorServices = class {
2306
- constructor(nodeResolver) {
2307
- this.nodeResolver = nodeResolver;
2308
- }
2309
- resolveNodeErrorHandler(spec) {
2310
- if (!spec) return void 0;
2311
- if (typeof spec === "object" && spec !== null && "handle" in spec && typeof spec.handle === "function") return spec;
2312
- return this.nodeResolver.resolve(spec);
2313
- }
2314
- resolveWorkflowErrorHandler(spec) {
2315
- if (!spec) return void 0;
2316
- if (typeof spec === "object" && spec !== null && "onError" in spec && typeof spec.onError === "function") return spec;
2317
- return this.nodeResolver.resolve(spec);
2318
- }
2319
- };
2320
-
2321
- //#endregion
2322
- //#region src/engine/policies/WorkflowStoragePolicyEvaluator.ts
2323
- var WorkflowStoragePolicyEvaluator = class {
2324
- constructor(nodeResolver) {
2325
- this.nodeResolver = nodeResolver;
2326
- }
2327
- async shouldPersist(workflow, snapshot, args) {
2328
- const spec = workflow.storagePolicy;
2329
- if (spec === void 0) return this.modeMatches(snapshot?.storagePolicy ?? "ALL", args);
2330
- if (typeof spec === "string") return this.modeMatches(spec, args);
2331
- const resolver = this.nodeResolver.resolve(spec);
2332
- return Boolean(await resolver.shouldPersist(args));
2333
- }
2334
- modeMatches(mode, args) {
2335
- if (mode === "ALL") return true;
2336
- if (mode === "NEVER") return false;
2337
- if (mode === "SUCCESS") return args.finalStatus === "completed";
2338
- if (mode === "ERROR") return args.finalStatus === "failed";
2339
- return true;
2340
- }
2341
- };
2342
-
2343
- //#endregion
2344
- //#region src/engine/credentials/CredentialResolverFactory.ts
2345
- var CredentialResolverFactory = class {
2346
- constructor(credentialSessions) {
2347
- this.credentialSessions = credentialSessions;
2348
- }
2349
- create(workflowId, nodeId, config) {
2350
- const acceptedTypesBySlot = /* @__PURE__ */ new Map();
2351
- for (const requirement of config?.getCredentialRequirements?.() ?? []) acceptedTypesBySlot.set(requirement.slotKey, requirement.acceptedTypes);
2352
- return async (slotKey) => {
2353
- try {
2354
- return await this.credentialSessions.getSession({
2355
- workflowId,
2356
- nodeId,
2357
- slotKey
2358
- });
2359
- } catch (error) {
2360
- const acceptedTypes = acceptedTypesBySlot.get(slotKey) ?? [];
2361
- const message = error instanceof Error ? error.message : String(error);
2362
- const alreadyListsAcceptedTypes = message.includes("Accepted types:") || message.includes("Accepted credential types:") || message.includes("binding points at an unknown type");
2363
- const acceptedTypesSuffix = acceptedTypes.length > 0 && !alreadyListsAcceptedTypes ? ` Accepted types: ${acceptedTypes.join(", ")}.` : "";
2364
- throw new Error(`Failed to resolve credential for workflow ${workflowId} node ${nodeId} slot "${slotKey}". ${message}${acceptedTypesSuffix}`, { cause: error });
2365
- }
2366
- };
2367
- }
2368
- };
2369
-
2370
- //#endregion
2371
- //#region src/events/NodeEventPublisher.ts
2372
- /** Publishes node lifecycle snapshots onto the run {@link RunEventBus}. */
2373
- var NodeEventPublisher = class {
2374
- constructor(eventBus) {
2375
- this.eventBus = eventBus;
2376
- }
2377
- async publish(kind, snapshot) {
2378
- if (!this.eventBus) return;
2379
- await this.eventBus.publish({
2380
- kind,
2381
- runId: snapshot.runId,
2382
- workflowId: snapshot.workflowId,
2383
- parent: snapshot.parent,
2384
- at: snapshot.updatedAt,
2385
- snapshot
2386
- });
2387
- }
2388
- };
2389
-
2390
- //#endregion
2391
- //#region src/engine/planning/RunQueuePlannerDiagnostics.ts
2392
- var RunQueuePlannerDiagnostics = class {
2393
- constructor(topology, nodeInstances) {
2394
- this.topology = topology;
2395
- this.nodeInstances = nodeInstances;
2396
- }
2397
- describeUnsatisfiedCollect(queueEntry) {
2398
- const batchId = queueEntry.batchId ?? "batch_1";
2399
- const expectedInputs = queueEntry.collect?.expectedInputs ?? [];
2400
- const receivedInputs = Object.keys(queueEntry.collect?.received ?? {});
2401
- const missingInputs = expectedInputs.filter((input) => !receivedInputs.includes(input));
2402
- const mergeNodeLabel = this.formatNodeLabel(queueEntry.nodeId);
2403
- const receivedSummary = this.describeReceivedInputs(queueEntry);
2404
- const missingSummary = this.describeMissingInputs(queueEntry.nodeId, missingInputs);
2405
- return [
2406
- `Multi-input collect is stuck at ${mergeNodeLabel} (batchId=${batchId}).`,
2407
- `Expected inputs: ${this.formatInputList(expectedInputs)}.`,
2408
- `Received inputs: ${receivedSummary}.`,
2409
- `Missing inputs: ${missingSummary}.`
2410
- ].join(" ");
2411
- }
2412
- describeReceivedInputs(queueEntry) {
2413
- const received = queueEntry.collect?.received ?? {};
2414
- const receivedEntries = Object.entries(received);
2415
- if (receivedEntries.length === 0) return "none";
2416
- return receivedEntries.map(([input, items]) => `${input} (${items.length} item${items.length === 1 ? "" : "s"})`).join(", ");
2417
- }
2418
- describeMissingInputs(nodeId, missingInputs) {
2419
- if (missingInputs.length === 0) return "none";
2420
- return missingInputs.map((input) => {
2421
- const sources = this.findSources(nodeId, input);
2422
- if (sources.length === 0) return input;
2423
- return `${input} from ${sources.join(" or ")}`;
2424
- }).join(", ");
2425
- }
2426
- findSources(nodeId, input) {
2427
- const matches = [];
2428
- for (const [sourceNodeId, edges] of this.topology.outgoingByNode.entries()) for (const edge of edges) if (edge.to.nodeId === nodeId && edge.to.input === input) matches.push(this.formatNodeLabel(sourceNodeId));
2429
- return matches;
2430
- }
2431
- formatInputList(inputs) {
2432
- return inputs.length > 0 ? `[${inputs.join(", ")}]` : "[]";
2433
- }
2434
- formatNodeLabel(nodeId) {
2435
- const definition = this.topology.defsById.get(nodeId);
2436
- const instance = this.nodeInstances.get(nodeId);
2437
- const typeName = definition?.type && typeof definition.type === "function" ? definition.type.name : instance && typeof instance === "object" && "constructor" in instance ? instance.constructor.name ?? "Node" : "Node";
2438
- return definition?.name ? `"${definition.name}" (${typeName}:${nodeId})` : `${typeName}:${nodeId}`;
2439
- }
2440
- };
2441
-
2442
- //#endregion
2443
- //#region src/engine/planning/RunQueuePlanner.ts
2444
- var RunQueuePlanner = class {
2445
- diagnostics;
2446
- constructor(topology, nodeInstances) {
2447
- this.topology = topology;
2448
- this.nodeInstances = nodeInstances;
2449
- this.diagnostics = new RunQueuePlannerDiagnostics(topology, nodeInstances);
2450
- }
2451
- validateNodeKinds() {
2452
- for (const [toNodeId, inputs] of this.topology.expectedInputsByNode.entries()) {
2453
- if (inputs.length <= 1) {
2454
- const only = inputs[0];
2455
- if (only && only !== "in") {
2456
- const inst$1 = this.nodeInstances.get(toNodeId);
2457
- if (!this.isMultiInputNode(inst$1)) throw new Error(`Node ${toNodeId} only supports input 'in' (got '${only}').`);
2458
- }
2459
- continue;
2460
- }
2461
- const inst = this.nodeInstances.get(toNodeId);
2462
- if (!this.isMultiInputNode(inst)) throw new Error(`Node ${toNodeId} has ${inputs.length} inbound edges. Insert a Merge node to combine branches.`);
2463
- }
2464
- }
2465
- seedFromTrigger(args) {
2466
- const queue = [];
2467
- for (const e of this.topology.outgoingByNode.get(args.startNodeId) ?? []) {
2468
- if (e.output !== "main") continue;
2469
- this.enqueueEdge(queue, {
2470
- batchId: args.batchId,
2471
- to: e.to,
2472
- from: {
2473
- nodeId: args.startNodeId,
2474
- output: "main"
2475
- },
2476
- items: args.items
2477
- });
2478
- }
2479
- return queue;
2480
- }
2481
- applyOutputs(queue, args) {
2482
- for (const e of this.topology.outgoingByNode.get(args.fromNodeId) ?? []) {
2483
- const outItems = args.outputs[e.output] ?? [];
2484
- this.enqueueEdge(queue, {
2485
- batchId: args.batchId,
2486
- to: e.to,
2487
- from: {
2488
- nodeId: args.fromNodeId,
2489
- output: e.output
2490
- },
2491
- items: outItems
2492
- });
2493
- }
2494
- }
2495
- nextActivation(queue) {
2496
- const readyCollect = this.resolveReadyCollect(queue);
2497
- if (readyCollect) return readyCollect;
2498
- const jobIdx = queue.findIndex((q) => !q.collect);
2499
- if (jobIdx === -1) {
2500
- if (queue.length === 0) return null;
2501
- const sealedCollect = this.resolveSealedCollect(queue);
2502
- if (sealedCollect) return sealedCollect;
2503
- const stuck = queue[0];
2504
- throw new Error(this.diagnostics.describeUnsatisfiedCollect(stuck));
2505
- }
2506
- const job = queue.splice(jobIdx, 1)[0];
2507
- const def = this.topology.defsById.get(job.nodeId);
2508
- if (!def || def.kind !== "node") return this.nextActivation(queue);
2509
- return {
2510
- kind: "single",
2511
- nodeId: job.nodeId,
2512
- input: job.input,
2513
- batchId: job.batchId ?? "batch_1"
2514
- };
2515
- }
2516
- sumItemsByPort(inputsByPort) {
2517
- let n = 0;
2518
- for (const v of Object.values(inputsByPort)) n += v?.length ?? 0;
2519
- return n;
2520
- }
2521
- resolveReadyCollect(queue) {
2522
- for (let i = 0; i < queue.length; i++) {
2523
- const ready = this.tryDequeueCollect(queue, i);
2524
- if (ready) return ready;
2525
- }
2526
- return null;
2527
- }
2528
- resolveSealedCollect(queue) {
2529
- for (let i = 0; i < queue.length; i++) {
2530
- const queueEntry = queue[i];
2531
- if (!queueEntry.collect) continue;
2532
- const received = queueEntry.collect.received;
2533
- if (Object.keys(received).length === 0) continue;
2534
- this.fillMissingCollectInputs(queueEntry);
2535
- const ready = this.tryDequeueCollect(queue, i);
2536
- if (ready) return ready;
2537
- }
2538
- return null;
2539
- }
2540
- tryDequeueCollect(queue, index) {
2541
- const queueEntry = queue[index];
2542
- if (!queueEntry.collect) return null;
2543
- const batchId = queueEntry.batchId ?? "batch_1";
2544
- const expected = queueEntry.collect.expectedInputs ?? [];
2545
- const received = queueEntry.collect.received;
2546
- for (const input of expected) if (!(input in received)) return null;
2547
- queue.splice(index, 1);
2548
- return {
2549
- kind: "multi",
2550
- nodeId: queueEntry.nodeId,
2551
- inputsByPort: received,
2552
- batchId
2553
- };
2554
- }
2555
- fillMissingCollectInputs(queueEntry) {
2556
- if (!queueEntry.collect) return;
2557
- const received = queueEntry.collect.received;
2558
- for (const input of queueEntry.collect.expectedInputs ?? []) if (!(input in received)) received[input] = [];
2559
- }
2560
- enqueueEdge(queue, args) {
2561
- const target = this.nodeInstances.get(args.to.nodeId);
2562
- if (!this.isMultiInputNode(target)) {
2563
- if (args.items.length === 0) {
2564
- if (this.shouldContinueAfterEmptyOutputFromSource(args.from.nodeId)) {
2565
- queue.push({
2566
- nodeId: args.to.nodeId,
2567
- input: args.items,
2568
- toInput: args.to.input,
2569
- batchId: args.batchId,
2570
- from: args.from
2571
- });
2572
- return;
2573
- }
2574
- this.propagateEmptyPath(queue, args.to.nodeId, args.batchId);
2575
- return;
2576
- }
2577
- queue.push({
2578
- nodeId: args.to.nodeId,
2579
- input: args.items,
2580
- toInput: args.to.input,
2581
- batchId: args.batchId,
2582
- from: args.from
2583
- });
2584
- return;
2585
- }
2586
- const expected = this.topology.expectedInputsByNode.get(args.to.nodeId) ?? [];
2587
- let collect = queue.find((q) => q.nodeId === args.to.nodeId && (q.batchId ?? "batch_1") === args.batchId && !!q.collect);
2588
- if (!collect) {
2589
- collect = {
2590
- nodeId: args.to.nodeId,
2591
- input: [],
2592
- batchId: args.batchId,
2593
- collect: {
2594
- expectedInputs: expected,
2595
- received: {}
2596
- }
2597
- };
2598
- queue.push(collect);
2599
- }
2600
- const received = collect.collect.received;
2601
- received[args.to.input] = args.items;
2602
- }
2603
- shouldContinueAfterEmptyOutputFromSource(fromNodeId) {
2604
- const def = this.topology.defsById.get(fromNodeId);
2605
- if (!def) return false;
2606
- return def.config.continueWhenEmptyOutput === true;
2607
- }
2608
- propagateEmptyPath(queue, nodeId, batchId) {
2609
- for (const edge of this.topology.outgoingByNode.get(nodeId) ?? []) this.enqueueEdge(queue, {
2610
- batchId,
2611
- to: edge.to,
2612
- from: {
2613
- nodeId,
2614
- output: edge.output
2615
- },
2616
- items: []
2617
- });
2618
- }
2619
- isMultiInputNode(n) {
2620
- return typeof n?.executeMulti === "function";
2621
- }
2622
- };
2623
-
2624
- //#endregion
2625
- //#region src/engine/planning/EngineWorkflowPlanningFactory.ts
2626
- var EngineWorkflowPlanningFactory = class {
2627
- constructor(workflowNodeInstanceFactory, directedCycleDetector) {
2628
- this.workflowNodeInstanceFactory = workflowNodeInstanceFactory;
2629
- this.directedCycleDetector = directedCycleDetector;
2630
- }
2631
- create(workflow) {
2632
- this.directedCycleDetector.validateAcyclic(workflow);
2633
- const topology = WorkflowTopology.fromWorkflow(workflow);
2634
- const planner = new RunQueuePlanner(topology, this.workflowNodeInstanceFactory.createNodes(workflow));
2635
- planner.validateNodeKinds();
2636
- return {
2637
- topology,
2638
- planner
2639
- };
2640
- }
2641
- };
2642
-
2643
- //#endregion
2644
- //#region src/engine/planning/DirectedCycleDetector.ts
2645
- /**
2646
- * Rejects workflow definitions whose edges contain a directed cycle (including self-loops).
2647
- */
2648
- var DirectedCycleDetector = class {
2649
- validateAcyclic(workflow) {
2650
- const classifier = createWorkflowExecutableNodeClassifier(workflow);
2651
- const outgoing = this.buildOutgoingAdjacency(workflow, classifier);
2652
- const state = /* @__PURE__ */ new Map();
2653
- for (const n of workflow.nodes) if (classifier.isExecutableNodeId(n.id)) state.set(n.id, "unvisited");
2654
- for (const n of workflow.nodes) if (classifier.isExecutableNodeId(n.id) && state.get(n.id) === "unvisited") this.depthFirstSearch(n.id, outgoing, state);
2655
- }
2656
- buildOutgoingAdjacency(workflow, classifier) {
2657
- const map = /* @__PURE__ */ new Map();
2658
- for (const e of workflow.edges) {
2659
- if (!classifier.isExecutableNodeId(e.from.nodeId) || !classifier.isExecutableNodeId(e.to.nodeId)) continue;
2660
- const list = map.get(e.from.nodeId) ?? [];
2661
- list.push(e.to.nodeId);
2662
- map.set(e.from.nodeId, list);
2663
- }
2664
- return map;
2665
- }
2666
- depthFirstSearch(nodeId, outgoing, visitState) {
2667
- visitState.set(nodeId, "visiting");
2668
- for (const toId of outgoing.get(nodeId) ?? []) {
2669
- const s = visitState.get(toId);
2670
- if (s === "visiting") throw new Error(`Workflow graph contains a directed cycle (edge ${nodeId} -> ${toId}).`);
2671
- if (s === "unvisited") this.depthFirstSearch(toId, outgoing, visitState);
2672
- }
2673
- visitState.set(nodeId, "done");
2674
- }
2675
- };
2676
-
2677
- //#endregion
2678
- //#region src/engine/state/BoundNodeExecutionStatePublisher.ts
2679
- var BoundNodeExecutionStatePublisher = class {
2680
- chain = Promise.resolve();
2681
- constructor(runStore, runId, workflowId, parent, publishNodeEvent) {
2682
- this.runStore = runStore;
2683
- this.runId = runId;
2684
- this.workflowId = workflowId;
2685
- this.parent = parent;
2686
- this.publishNodeEvent = publishNodeEvent;
2687
- }
2688
- markQueued(args) {
2689
- return this.enqueue(async () => {
2690
- const state = await this.loadState();
2691
- const previous = state.nodeSnapshotsByNodeId?.[args.nodeId];
2692
- const queuedAt = (/* @__PURE__ */ new Date()).toISOString();
2693
- const snapshot = NodeSnapshotFactory.queued({
2694
- runId: this.runId,
2695
- workflowId: this.workflowId,
2696
- nodeId: args.nodeId,
2697
- activationId: args.activationId ?? previous?.activationId ?? `synthetic_${args.nodeId}`,
2698
- parent: this.parent,
2699
- queuedAt,
2700
- inputsByPort: args.inputsByPort ?? previous?.inputsByPort ?? InputPortMap.empty()
2701
- });
2702
- await this.saveSnapshot(state, snapshot);
2703
- await this.publishNodeEvent("nodeQueued", snapshot);
2704
- });
2705
- }
2706
- markRunning(args) {
2707
- return this.enqueue(async () => {
2708
- const state = await this.loadState();
2709
- const previous = state.nodeSnapshotsByNodeId?.[args.nodeId];
2710
- const startedAt = (/* @__PURE__ */ new Date()).toISOString();
2711
- const snapshot = NodeSnapshotFactory.running({
2712
- previous,
2713
- runId: this.runId,
2714
- workflowId: this.workflowId,
2715
- nodeId: args.nodeId,
2716
- activationId: args.activationId ?? previous?.activationId ?? `synthetic_${args.nodeId}`,
2717
- parent: this.parent,
2718
- startedAt,
2719
- inputsByPort: args.inputsByPort ?? previous?.inputsByPort ?? InputPortMap.empty()
2720
- });
2721
- await this.saveSnapshot(state, snapshot);
2722
- await this.publishNodeEvent("nodeStarted", snapshot);
2723
- });
2724
- }
2725
- markCompleted(args) {
2726
- return this.enqueue(async () => {
2727
- const state = await this.loadState();
2728
- const previous = state.nodeSnapshotsByNodeId?.[args.nodeId];
2729
- const finishedAt = (/* @__PURE__ */ new Date()).toISOString();
2730
- const snapshot = NodeSnapshotFactory.completed({
2731
- previous,
2732
- runId: this.runId,
2733
- workflowId: this.workflowId,
2734
- nodeId: args.nodeId,
2735
- activationId: args.activationId ?? previous?.activationId ?? `synthetic_${args.nodeId}`,
2736
- parent: this.parent,
2737
- finishedAt,
2738
- inputsByPort: args.inputsByPort ?? previous?.inputsByPort ?? InputPortMap.empty(),
2739
- outputs: args.outputs ?? previous?.outputs ?? {}
2740
- });
2741
- await this.saveSnapshot(state, snapshot);
2742
- await this.publishNodeEvent("nodeCompleted", snapshot);
2743
- });
2744
- }
2745
- markFailed(args) {
2746
- return this.enqueue(async () => {
2747
- const state = await this.loadState();
2748
- const previous = state.nodeSnapshotsByNodeId?.[args.nodeId];
2749
- const finishedAt = (/* @__PURE__ */ new Date()).toISOString();
2750
- const snapshot = NodeSnapshotFactory.failed({
2751
- previous,
2752
- runId: this.runId,
2753
- workflowId: this.workflowId,
2754
- nodeId: args.nodeId,
2755
- activationId: args.activationId ?? previous?.activationId ?? `synthetic_${args.nodeId}`,
2756
- parent: this.parent,
2757
- finishedAt,
2758
- inputsByPort: args.inputsByPort ?? previous?.inputsByPort ?? InputPortMap.empty(),
2759
- error: args.error
2760
- });
2761
- await this.saveSnapshot(state, snapshot);
2762
- await this.publishNodeEvent("nodeFailed", snapshot);
2763
- });
2764
- }
2765
- appendConnectionInvocation(args) {
2766
- return this.enqueue(async () => {
2767
- const state = await this.loadState();
2768
- const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2769
- const record = {
2770
- invocationId: args.invocationId,
2771
- runId: this.runId,
2772
- workflowId: this.workflowId,
2773
- connectionNodeId: args.connectionNodeId,
2774
- parentAgentNodeId: args.parentAgentNodeId,
2775
- parentAgentActivationId: args.parentAgentActivationId,
2776
- status: args.status,
2777
- managedInput: args.managedInput,
2778
- managedOutput: args.managedOutput,
2779
- error: args.error,
2780
- queuedAt: args.queuedAt,
2781
- startedAt: args.startedAt,
2782
- finishedAt: args.finishedAt,
2783
- updatedAt
2784
- };
2785
- await this.runStore.save({
2786
- ...state,
2787
- connectionInvocations: [...state.connectionInvocations ?? [], record]
2788
- });
2789
- });
2790
- }
2791
- enqueue(work) {
2792
- const next = this.chain.then(work);
2793
- this.chain = next.catch(() => void 0);
2794
- return next;
2795
- }
2796
- async loadState() {
2797
- const state = await this.runStore.load(this.runId);
2798
- if (!state) throw new Error(`Unknown runId: ${this.runId}`);
2799
- return state;
2800
- }
2801
- async saveSnapshot(state, snapshot) {
2802
- await this.runStore.save({
2803
- ...state,
2804
- nodeSnapshotsByNodeId: {
2805
- ...state.nodeSnapshotsByNodeId ?? {},
2806
- [snapshot.nodeId]: snapshot
2807
- }
2808
- });
2809
- }
2810
- };
2811
-
2812
- //#endregion
2813
- //#region src/engine/state/NodeExecutionStatePublisherFactory.ts
2814
- var NodeExecutionStatePublisherFactory = class {
2815
- constructor(runStore, nodeEventPublisher) {
2816
- this.runStore = runStore;
2817
- this.nodeEventPublisher = nodeEventPublisher;
2818
- }
2819
- create(runId, workflowId, parent) {
2820
- return new BoundNodeExecutionStatePublisher(this.runStore, runId, workflowId, parent, async (kind, snapshot) => {
2821
- await this.nodeEventPublisher.publish(kind, snapshot);
2822
- });
2823
- }
2824
- };
2825
-
2826
- //#endregion
2827
- //#region src/engine/triggers/TriggerRuntimeService.ts
2828
- var TriggerRuntimeService = class {
2829
- credentialResolverFactory;
2830
- triggerCleanupHandlesByKey = /* @__PURE__ */ new Map();
2831
- constructor(workflowRepository, workflowActivationPolicy, runIdFactory, runDataFactory, executionContextFactory, credentialResolverFactory, nodeExecutionStatePublisherFactory, nodeResolver, triggerSetupStateStore, emitHandler, executionLimitsPolicy, diagnostics) {
2832
- this.workflowRepository = workflowRepository;
2833
- this.workflowActivationPolicy = workflowActivationPolicy;
2834
- this.runIdFactory = runIdFactory;
2835
- this.runDataFactory = runDataFactory;
2836
- this.executionContextFactory = executionContextFactory;
2837
- this.nodeExecutionStatePublisherFactory = nodeExecutionStatePublisherFactory;
2838
- this.nodeResolver = nodeResolver;
2839
- this.triggerSetupStateStore = triggerSetupStateStore;
2840
- this.emitHandler = emitHandler;
2841
- this.executionLimitsPolicy = executionLimitsPolicy;
2842
- this.diagnostics = diagnostics;
2843
- this.credentialResolverFactory = credentialResolverFactory;
2844
- }
2845
- async startTriggers() {
2846
- for (const wf of this.workflowRepository.list()) {
2847
- if (!this.workflowActivationPolicy.isActive(wf.id)) {
2848
- const summaries = this.formatTriggerSummaries(wf);
2849
- if (summaries.length > 0) this.logInfo(`Workflow "${wf.name}" (${wf.id}) is inactive; skipping trigger setup — ${summaries.join("; ")}.`);
2850
- continue;
2851
- }
2852
- await this.startTriggersForWorkflow(wf);
2853
- }
2854
- }
2855
- async syncWorkflowTriggersForActivation(workflowId) {
2856
- const wf = this.workflowRepository.get(workflowId);
2857
- if (!wf) return;
2858
- const summaries = this.formatTriggerSummaries(wf);
2859
- if (summaries.length > 0) this.logInfo(`Workflow "${wf.name}" (${wf.id}): stopping triggers — ${summaries.join("; ")}.`);
2860
- await this.stopTriggersForWorkflow(wf);
2861
- if (this.workflowActivationPolicy.isActive(workflowId)) {
2862
- if (summaries.length > 0) this.logInfo(`Workflow "${wf.name}" (${wf.id}): activation on; starting triggers — ${summaries.join("; ")}.`);
2863
- await this.startTriggersForWorkflow(wf);
2864
- } else this.logInfo(`Workflow "${wf.name}" (${wf.id}): activation off; triggers not started.`);
2865
- }
2866
- async stop() {
2867
- for (const workflow of this.workflowRepository.list()) await this.stopTriggersForWorkflow(workflow);
2868
- }
2869
- async createTriggerTestItems(args) {
2870
- const definition = args.workflow.nodes.find((node$1) => node$1.id === args.nodeId);
2871
- if (!definition) throw new Error(`Unknown trigger nodeId: ${args.nodeId}`);
2872
- if (definition.kind !== "trigger") throw new Error(`Node ${args.nodeId} is not a trigger`);
2873
- const node = this.nodeResolver.resolve(definition.type);
2874
- if (!this.isTestableTriggerNode(node)) return;
2875
- const data = this.runDataFactory.create();
2876
- const runId = this.runIdFactory.makeRunId();
2877
- const trigger = {
2878
- workflowId: args.workflow.id,
2879
- nodeId: definition.id
2880
- };
2881
- const previousState = await this.triggerSetupStateStore.load(trigger);
2882
- return await node.getTestItems({
2883
- ...this.createExecutionContext({
2884
- runId,
2885
- workflowId: args.workflow.id,
2886
- nodeId: definition.id,
2887
- data
2888
- }),
2889
- trigger,
2890
- nodeId: definition.id,
2891
- config: definition.config,
2892
- previousState: previousState?.state
2893
- });
2894
- }
2895
- async startTriggersForWorkflow(wf) {
2896
- for (const def of wf.nodes) {
2897
- if (def.kind !== "trigger") continue;
2898
- const node = this.nodeResolver.resolve(def.type);
2899
- const data = this.runDataFactory.create();
2900
- const triggerRunId = this.runIdFactory.makeRunId();
2901
- const trigger = {
2902
- workflowId: wf.id,
2903
- nodeId: def.id
2904
- };
2905
- await this.stopTrigger(trigger);
2906
- const previousState = await this.triggerSetupStateStore.load(trigger);
2907
- let nextState;
2908
- try {
2909
- nextState = await node.setup({
2910
- ...this.createExecutionContext({
2911
- runId: triggerRunId,
2912
- workflowId: wf.id,
2913
- nodeId: def.id,
2914
- data
2915
- }),
2916
- trigger,
2917
- config: def.config,
2918
- previousState: previousState?.state,
2919
- registerCleanup: (cleanup) => {
2920
- this.registerTriggerCleanupHandle(trigger, cleanup);
2921
- },
2922
- emit: async (items) => {
2923
- await this.emitHandler.emit(wf, def.id, items);
2924
- }
2925
- });
2926
- } catch (triggerError) {
2927
- await this.stopTrigger(trigger);
2928
- const message = triggerError instanceof Error ? triggerError.message : String(triggerError);
2929
- this.logWarn(`Skipping trigger setup for workflow ${wf.id} node ${def.id}: ${message}`);
2930
- continue;
2931
- }
2932
- if (nextState === void 0) await this.triggerSetupStateStore.delete(trigger);
2933
- else await this.triggerSetupStateStore.save({
2934
- trigger,
2935
- updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2936
- state: nextState
2937
- });
2938
- }
2939
- }
2940
- async stopTriggersForWorkflow(workflow) {
2941
- for (const node of workflow.nodes) {
2942
- if (node.kind !== "trigger") continue;
2943
- await this.stopTrigger({
2944
- workflowId: workflow.id,
2945
- nodeId: node.id
2946
- });
2947
- }
2948
- }
2949
- createExecutionContext(args) {
2950
- const nodeState = this.nodeExecutionStatePublisherFactory.create(args.runId, args.workflowId, void 0);
2951
- const rootLimits = this.executionLimitsPolicy.createRootExecutionOptions();
2952
- return this.executionContextFactory.create({
2953
- runId: args.runId,
2954
- workflowId: args.workflowId,
2955
- parent: void 0,
2956
- subworkflowDepth: rootLimits.subworkflowDepth ?? 0,
2957
- engineMaxNodeActivations: rootLimits.maxNodeActivations,
2958
- engineMaxSubworkflowDepth: rootLimits.maxSubworkflowDepth,
2959
- data: args.data,
2960
- nodeState,
2961
- getCredential: this.credentialResolverFactory.create(args.workflowId, args.nodeId)
2962
- });
2963
- }
2964
- registerTriggerCleanupHandle(trigger, cleanup) {
2965
- const key = this.toTriggerKey(trigger);
2966
- const cleanups = this.triggerCleanupHandlesByKey.get(key) ?? [];
2967
- cleanups.push(cleanup);
2968
- this.triggerCleanupHandlesByKey.set(key, cleanups);
2969
- }
2970
- async stopTrigger(trigger) {
2971
- const key = this.toTriggerKey(trigger);
2972
- const cleanups = this.triggerCleanupHandlesByKey.get(key) ?? [];
2973
- this.triggerCleanupHandlesByKey.delete(key);
2974
- for (const cleanup of [...cleanups].reverse()) await cleanup.stop();
2975
- }
2976
- toTriggerKey(trigger) {
2977
- return `${trigger.workflowId}:${trigger.nodeId}`;
2978
- }
2979
- formatTriggerSummaries(wf) {
2980
- const out = [];
2981
- for (const def of wf.nodes) {
2982
- if (def.kind !== "trigger") continue;
2983
- out.push(this.describeTriggerNode(def));
2984
- }
2985
- return out;
2986
- }
2987
- describeTriggerNode(def) {
2988
- const label = def.name !== void 0 && def.name.trim().length > 0 ? def.name.trim() : String(def.id);
2989
- const cfg = def.config;
2990
- if (typeof cfg.endpointKey === "string" && cfg.endpointKey.trim().length > 0) return `${label} (webhook "${cfg.endpointKey.trim()}")`;
2991
- return label;
2992
- }
2993
- logInfo(message) {
2994
- if (this.diagnostics) this.diagnostics.info(message);
2995
- }
2996
- logWarn(message) {
2997
- if (this.diagnostics) this.diagnostics.warn(message);
2998
- else console.warn(`[engine] ${message}`);
2999
- }
3000
- isTestableTriggerNode(node) {
3001
- return typeof node.getTestItems === "function";
3002
- }
3003
- };
3004
-
3005
- //#endregion
3006
- //#region src/engine/waiters/EngineWaiters.ts
3007
- var EngineWaiters = class {
3008
- completionWaiters = /* @__PURE__ */ new Map();
3009
- webhookResponseWaiters = /* @__PURE__ */ new Map();
3010
- waitForCompletion(runId) {
3011
- return new Promise((resolve) => {
3012
- const list = this.completionWaiters.get(runId) ?? [];
3013
- list.push(resolve);
3014
- this.completionWaiters.set(runId, list);
3015
- });
3016
- }
3017
- waitForWebhookResponse(runId) {
3018
- return new Promise((resolve) => {
3019
- const list = this.webhookResponseWaiters.get(runId) ?? [];
3020
- list.push(resolve);
3021
- this.webhookResponseWaiters.set(runId, list);
3022
- });
3023
- }
3024
- resolveRunCompletion(result) {
3025
- if (result.status !== "completed" && result.status !== "failed") return;
3026
- const list = this.completionWaiters.get(result.runId);
3027
- if (!list || list.length === 0) return;
3028
- this.completionWaiters.delete(result.runId);
3029
- for (const r of list) r(result);
3030
- }
3031
- resolveWebhookResponse(result) {
3032
- const list = this.webhookResponseWaiters.get(result.runId);
3033
- if (!list || list.length === 0) return;
3034
- this.webhookResponseWaiters.delete(result.runId);
3035
- for (const resolve of list) resolve(result);
3036
- }
3037
- };
3038
-
3039
- //#endregion
3040
- //#region src/engine/api/EngineFactory.ts
3041
- /**
3042
- * Composes the {@link Engine} graph from {@link EngineCompositionDeps}. Production wiring usually goes through
3043
- * {@link import("../runtime/EngineRuntimeRegistrar").EngineRuntimeRegistrar}; this factory remains for tests and custom composition.
3044
- * Exported from `@codemation/core/bootstrap` (not the main `@codemation/core` barrel).
3045
- */
3046
- var EngineFactory = class {
3047
- create(deps) {
3048
- const waiters = new EngineWaiters();
3049
- const credentialResolverFactory = new CredentialResolverFactory(deps.credentialSessions);
3050
- const nodeEventPublisher = new NodeEventPublisher(deps.eventBus);
3051
- const nodeStatePublisherFactory = new NodeExecutionStatePublisherFactory(deps.runStore, nodeEventPublisher);
3052
- const planningFactory = new EngineWorkflowPlanningFactory(deps.workflowNodeInstanceFactory, new DirectedCycleDetector());
3053
- const executionLimitsPolicy = deps.executionLimitsPolicy ?? new EngineExecutionLimitsPolicy();
3054
- const workflowSnapshotFactory = new require_PersistedWorkflowSnapshotFactory.PersistedWorkflowSnapshotFactory(deps.tokenRegistry);
3055
- const persistedWorkflowConfigHydrator = deps.persistedWorkflowConfigHydrator ?? new PersistedWorkflowConfigHydrator(deps.tokenRegistry);
3056
- const missingRuntimeNodeDefinitionFactory = deps.missingRuntimeNodeDefinitionFactory ?? new MissingRuntimeNodeDefinitionFactory();
3057
- const workflowSnapshotResolver = new PersistedWorkflowResolver(deps.workflowRepository, deps.tokenRegistry, persistedWorkflowConfigHydrator, missingRuntimeNodeDefinitionFactory);
3058
- const semantics = new RunStateSemantics();
3059
- const activationEnqueueService = new ActivationEnqueueService(deps.activationScheduler, deps.runStore, nodeEventPublisher);
3060
- const runExecutionContextFactory = new WorkflowRunExecutionContextFactory(deps.executionContextFactory, credentialResolverFactory);
3061
- const nodeActivationRequestComposer = new NodeActivationRequestComposer(deps.activationIdFactory, credentialResolverFactory);
3062
- const persistedRunStateTerminalBuilder = new PersistedRunStateTerminalBuilder();
3063
- const storagePolicyEvaluator = new WorkflowStoragePolicyEvaluator(deps.nodeResolver);
3064
- const terminalPersistence = new RunTerminalPersistenceCoordinator(deps.runStore, storagePolicyEvaluator);
3065
- const policyErrorServices = new WorkflowPolicyErrorServices(deps.nodeResolver);
3066
- const workflowRunStarter = new WorkflowRunStarter(deps.runIdFactory, deps.runStore, deps.runDataFactory, workflowSnapshotFactory, planningFactory, nodeStatePublisherFactory, runExecutionContextFactory, nodeActivationRequestComposer, activationEnqueueService, waiters, deps.workflowPolicyRuntimeDefaults, executionLimitsPolicy);
3067
- const currentStateRunStarter = new CurrentStateRunStarter(deps.runIdFactory, deps.runStore, deps.runDataFactory, workflowSnapshotFactory, planningFactory, nodeStatePublisherFactory, runExecutionContextFactory, nodeActivationRequestComposer, activationEnqueueService, semantics, waiters, deps.workflowPolicyRuntimeDefaults, executionLimitsPolicy);
3068
- const runContinuationService = new RunContinuationService(deps.activationIdFactory, deps.runStore, deps.runDataFactory, runExecutionContextFactory, workflowSnapshotResolver, planningFactory, nodeStatePublisherFactory, credentialResolverFactory, nodeActivationRequestComposer, persistedRunStateTerminalBuilder, activationEnqueueService, nodeEventPublisher, semantics, waiters, policyErrorServices, terminalPersistence, executionLimitsPolicy);
3069
- const triggerRuntime = new TriggerRuntimeService(deps.workflowRepository, deps.workflowActivationPolicy, deps.runIdFactory, deps.runDataFactory, deps.executionContextFactory, credentialResolverFactory, nodeStatePublisherFactory, deps.nodeResolver, deps.triggerSetupStateStore, { emit: async (workflow, triggerNodeId, items) => {
3070
- await workflowRunStarter.runWorkflow(workflow, triggerNodeId, items, void 0);
3071
- } }, executionLimitsPolicy, deps.triggerRuntimeDiagnostics);
3072
- const engine = new Engine({
3073
- workflowCatalog: deps.workflowCatalog,
3074
- tokenRegistry: deps.tokenRegistry,
3075
- webhookTriggerMatcher: deps.webhookTriggerMatcher,
3076
- workflowSnapshotResolver,
3077
- triggerRuntime,
3078
- workflowRunStarter,
3079
- currentStateRunStarter,
3080
- runContinuationService
3081
- });
3082
- deps.activationScheduler.setContinuation?.(engine);
3083
- return engine;
3084
- }
3085
- };
3086
-
3087
- //#endregion
3088
- Object.defineProperty(exports, 'ConnectionNodeIdFactory', {
3089
- enumerable: true,
3090
- get: function () {
3091
- return ConnectionNodeIdFactory;
3092
- }
3093
- });
3094
- Object.defineProperty(exports, 'CoreTokens', {
3095
- enumerable: true,
3096
- get: function () {
3097
- return CoreTokens;
3098
- }
3099
- });
3100
- Object.defineProperty(exports, 'CredentialResolverFactory', {
3101
- enumerable: true,
3102
- get: function () {
3103
- return CredentialResolverFactory;
3104
- }
3105
- });
3106
- Object.defineProperty(exports, 'DirectedCycleDetector', {
3107
- enumerable: true,
3108
- get: function () {
3109
- return DirectedCycleDetector;
3110
- }
3111
- });
3112
- Object.defineProperty(exports, 'ENGINE_EXECUTION_LIMITS_DEFAULTS', {
3113
- enumerable: true,
3114
- get: function () {
3115
- return ENGINE_EXECUTION_LIMITS_DEFAULTS;
3116
- }
3117
- });
3118
- Object.defineProperty(exports, 'Engine', {
3119
- enumerable: true,
3120
- get: function () {
3121
- return Engine;
3122
- }
3123
- });
3124
- Object.defineProperty(exports, 'EngineExecutionLimitsPolicy', {
3125
- enumerable: true,
3126
- get: function () {
3127
- return EngineExecutionLimitsPolicy;
3128
- }
3129
- });
3130
- Object.defineProperty(exports, 'EngineFactory', {
3131
- enumerable: true,
3132
- get: function () {
3133
- return EngineFactory;
3134
- }
3135
- });
3136
- Object.defineProperty(exports, 'MissingRuntimeNodeToken', {
3137
- enumerable: true,
3138
- get: function () {
3139
- return MissingRuntimeNodeToken;
3140
- }
3141
- });
3142
- Object.defineProperty(exports, 'MissingRuntimeTriggerToken', {
3143
- enumerable: true,
3144
- get: function () {
3145
- return MissingRuntimeTriggerToken;
3146
- }
3147
- });
3148
- Object.defineProperty(exports, 'NodeEventPublisher', {
3149
- enumerable: true,
3150
- get: function () {
3151
- return NodeEventPublisher;
3152
- }
3153
- });
3154
- Object.defineProperty(exports, 'RunPolicySnapshotFactory', {
3155
- enumerable: true,
3156
- get: function () {
3157
- return RunPolicySnapshotFactory;
3158
- }
3159
- });
3160
- Object.defineProperty(exports, 'RunTerminalPersistenceCoordinator', {
3161
- enumerable: true,
3162
- get: function () {
3163
- return RunTerminalPersistenceCoordinator;
3164
- }
3165
- });
3166
- Object.defineProperty(exports, 'WorkflowExecutableNodeClassifier', {
3167
- enumerable: true,
3168
- get: function () {
3169
- return WorkflowExecutableNodeClassifier;
3170
- }
3171
- });
3172
- Object.defineProperty(exports, 'WorkflowPolicyErrorServices', {
3173
- enumerable: true,
3174
- get: function () {
3175
- return WorkflowPolicyErrorServices;
3176
- }
3177
- });
3178
- Object.defineProperty(exports, 'WorkflowStoragePolicyEvaluator', {
3179
- enumerable: true,
3180
- get: function () {
3181
- return WorkflowStoragePolicyEvaluator;
3182
- }
3183
- });
3184
- Object.defineProperty(exports, 'createWorkflowExecutableNodeClassifier', {
3185
- enumerable: true,
3186
- get: function () {
3187
- return createWorkflowExecutableNodeClassifier;
3188
- }
3189
- });
3190
- //# sourceMappingURL=EngineFactory-l_9xmBtv.cjs.map