@leitwerk-dev/process-sdk 0.1.9 → 0.2.1

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 (256) hide show
  1. package/dist/browser-ui-extension.d.ts +20 -0
  2. package/dist/browser-ui-extension.d.ts.map +1 -1
  3. package/dist/capabilities.d.ts +6 -0
  4. package/dist/capabilities.d.ts.map +1 -1
  5. package/dist/{chunk-LIIP7FMU.js → chunk-5R6MVLHC.js} +1 -1
  6. package/dist/chunk-5R6MVLHC.js.map +1 -0
  7. package/dist/chunk-DVXW2ZUV.js +1 -0
  8. package/dist/chunk-DVXW2ZUV.js.map +1 -0
  9. package/dist/{chunk-TRQJ5PRM.js → chunk-I7U6HCLN.js} +1 -11
  10. package/dist/chunk-I7U6HCLN.js.map +1 -0
  11. package/dist/{chunk-5RJZ2E7D.js → chunk-TM2LTSW4.js} +2 -6
  12. package/dist/chunk-TM2LTSW4.js.map +1 -0
  13. package/dist/codecs.d.ts +1 -0
  14. package/dist/codecs.d.ts.map +1 -1
  15. package/dist/commit-message.d.ts +5 -0
  16. package/dist/commit-message.d.ts.map +1 -1
  17. package/dist/core-capabilities.d.ts +396 -44
  18. package/dist/core-capabilities.d.ts.map +1 -1
  19. package/dist/define-process.d.ts +209 -64
  20. package/dist/define-process.d.ts.map +1 -1
  21. package/dist/event-bus.d.ts +1 -0
  22. package/dist/event-bus.d.ts.map +1 -1
  23. package/dist/{extension-api-BBcwktmc.d.ts → extension-api-B4gG5w1K.d.ts} +1111 -153
  24. package/dist/extension-api.d.ts +481 -38
  25. package/dist/extension-api.d.ts.map +1 -1
  26. package/dist/external-action-source.d.ts +9 -0
  27. package/dist/external-action-source.d.ts.map +1 -0
  28. package/dist/external-source-poll.d.ts +22 -0
  29. package/dist/external-source-poll.d.ts.map +1 -0
  30. package/dist/flow.d.ts +380 -107
  31. package/dist/flow.d.ts.map +1 -1
  32. package/dist/form-contract.d.ts +1 -1
  33. package/dist/form-contract.d.ts.map +1 -1
  34. package/dist/fs-utils.d.ts +6 -0
  35. package/dist/fs-utils.d.ts.map +1 -1
  36. package/dist/git-binary.d.ts +2 -1
  37. package/dist/git-binary.d.ts.map +1 -1
  38. package/dist/git-binary.js +25 -33
  39. package/dist/git-binary.js.map +1 -1
  40. package/dist/graph-fragments.d.ts +16 -0
  41. package/dist/graph-fragments.d.ts.map +1 -1
  42. package/dist/host-capabilities.d.ts +9 -3
  43. package/dist/host-capabilities.d.ts.map +1 -1
  44. package/dist/index.d.ts +40 -29
  45. package/dist/index.d.ts.map +1 -1
  46. package/dist/index.js +4876 -29
  47. package/dist/index.js.map +1 -1
  48. package/dist/integration-http.d.ts +32 -0
  49. package/dist/integration-http.d.ts.map +1 -0
  50. package/dist/json-data.d.ts +3 -0
  51. package/dist/json-data.d.ts.map +1 -0
  52. package/dist/leaf-outcome-renderer.d.ts +35 -0
  53. package/dist/leaf-outcome-renderer.d.ts.map +1 -1
  54. package/dist/leaf-outcome-renderer.js +86 -64
  55. package/dist/leaf-outcome-renderer.js.map +1 -1
  56. package/dist/leaf-outcomes.d.ts +3 -0
  57. package/dist/leaf-outcomes.d.ts.map +1 -1
  58. package/dist/model-provider.d.ts +144 -12
  59. package/dist/model-provider.d.ts.map +1 -1
  60. package/dist/pi-config-public.d.ts +2 -0
  61. package/dist/pi-config-public.d.ts.map +1 -0
  62. package/dist/pi-config-public.js +15 -0
  63. package/dist/pi-config-public.js.map +1 -0
  64. package/dist/pi-config.d.ts +41 -5
  65. package/dist/pi-config.d.ts.map +1 -1
  66. package/dist/pi-config.js +20 -180
  67. package/dist/pi-config.js.map +1 -1
  68. package/dist/process-definition-internals.d.ts +4 -0
  69. package/dist/process-definition-internals.d.ts.map +1 -1
  70. package/dist/process-flow-view.d.ts +2 -0
  71. package/dist/process-flow-view.d.ts.map +1 -1
  72. package/dist/process-graph.d.ts +34 -0
  73. package/dist/process-graph.d.ts.map +1 -1
  74. package/dist/process-launcher-builder.d.ts +5 -0
  75. package/dist/process-launcher-builder.d.ts.map +1 -1
  76. package/dist/process-watcher-builder.d.ts +5 -0
  77. package/dist/process-watcher-builder.d.ts.map +1 -1
  78. package/dist/process-watcher-source.d.ts +3 -1
  79. package/dist/process-watcher-source.d.ts.map +1 -1
  80. package/dist/project-binding.d.ts +13 -0
  81. package/dist/project-binding.d.ts.map +1 -0
  82. package/dist/registry-utils.d.ts +6 -0
  83. package/dist/registry-utils.d.ts.map +1 -1
  84. package/dist/repository-feedback.d.ts +47 -0
  85. package/dist/repository-feedback.d.ts.map +1 -0
  86. package/dist/repository-git-env.d.ts +8 -2
  87. package/dist/repository-git-env.d.ts.map +1 -1
  88. package/dist/repository-http.d.ts +31 -0
  89. package/dist/repository-http.d.ts.map +1 -0
  90. package/dist/repository-https.d.ts +3 -0
  91. package/dist/repository-https.d.ts.map +1 -0
  92. package/dist/repository-issue-watcher.d.ts +51 -0
  93. package/dist/repository-issue-watcher.d.ts.map +1 -0
  94. package/dist/repository-reconciliation.d.ts +5 -0
  95. package/dist/repository-reconciliation.d.ts.map +1 -0
  96. package/dist/repository-source-config.d.ts +58 -0
  97. package/dist/repository-source-config.d.ts.map +1 -0
  98. package/dist/repository-types.d.ts +63 -0
  99. package/dist/repository-types.d.ts.map +1 -0
  100. package/dist/review-flow-public.d.ts +2 -0
  101. package/dist/review-flow-public.d.ts.map +1 -0
  102. package/dist/review-flow-public.js +11 -0
  103. package/dist/review-flow-public.js.map +1 -0
  104. package/dist/review-flow.d.ts +6 -0
  105. package/dist/review-flow.d.ts.map +1 -1
  106. package/dist/review-flow.js +12 -43
  107. package/dist/review-flow.js.map +1 -1
  108. package/dist/runtime-internals-public.d.ts +2 -0
  109. package/dist/runtime-internals-public.d.ts.map +1 -0
  110. package/dist/runtime-internals-public.js +16 -0
  111. package/dist/runtime-internals-public.js.map +1 -0
  112. package/dist/runtime-internals.js +19 -2
  113. package/dist/runtime-internals.js.map +1 -1
  114. package/dist/server-events.d.ts +67 -0
  115. package/dist/server-events.d.ts.map +1 -1
  116. package/dist/server-process-builder.d.ts +7 -0
  117. package/dist/server-process-builder.d.ts.map +1 -1
  118. package/dist/state-helpers.d.ts +8 -0
  119. package/dist/state-helpers.d.ts.map +1 -1
  120. package/dist/subprocess-env.d.ts +4 -0
  121. package/dist/subprocess-env.d.ts.map +1 -1
  122. package/dist/tool-arguments.d.ts +9 -0
  123. package/dist/tool-arguments.d.ts.map +1 -0
  124. package/dist/tool-renderers.d.ts +6 -0
  125. package/dist/tool-renderers.d.ts.map +1 -1
  126. package/dist/turn-semantics.d.ts +18 -6
  127. package/dist/turn-semantics.d.ts.map +1 -1
  128. package/dist/types.d.ts +209 -38
  129. package/dist/types.d.ts.map +1 -1
  130. package/dist/ui-process-builder.d.ts +5 -0
  131. package/dist/ui-process-builder.d.ts.map +1 -1
  132. package/dist/worker-process-builder.d.ts +5 -0
  133. package/dist/worker-process-builder.d.ts.map +1 -1
  134. package/package.json +17 -15
  135. package/src/browser-ui-extension.ts +20 -0
  136. package/src/capabilities.ts +9 -1
  137. package/src/codecs.ts +1 -0
  138. package/src/commit-message.ts +5 -0
  139. package/src/core-capabilities.ts +464 -59
  140. package/src/define-process.ts +384 -332
  141. package/src/event-bus.ts +1 -0
  142. package/src/extension-api.ts +521 -41
  143. package/src/external-action-source.ts +17 -0
  144. package/src/external-source-poll.ts +61 -0
  145. package/src/flow.ts +674 -677
  146. package/src/form-contract.ts +0 -4
  147. package/src/fs-utils.ts +21 -2
  148. package/src/git-binary.ts +2 -1
  149. package/src/graph-fragments.ts +16 -0
  150. package/src/host-capabilities.ts +9 -6
  151. package/src/index.ts +51 -206
  152. package/src/integration-http.ts +70 -0
  153. package/src/json-data.ts +25 -0
  154. package/src/leaf-outcome-renderer.ts +35 -0
  155. package/src/leaf-outcomes.ts +4 -9
  156. package/src/model-provider.ts +179 -43
  157. package/src/pi-config-public.ts +7 -0
  158. package/src/pi-config.ts +48 -8
  159. package/src/process-definition-internals.ts +4 -0
  160. package/src/process-flow-view.ts +34 -88
  161. package/src/process-graph.ts +59 -51
  162. package/src/process-launcher-builder.ts +5 -0
  163. package/src/process-watcher-builder.ts +5 -0
  164. package/src/process-watcher-source.ts +9 -10
  165. package/src/project-binding.ts +40 -0
  166. package/src/registry-utils.ts +7 -5
  167. package/src/repository-feedback.ts +85 -0
  168. package/src/repository-git-env.ts +40 -2
  169. package/src/repository-http.ts +88 -0
  170. package/src/repository-https.ts +22 -0
  171. package/src/repository-issue-watcher.ts +122 -0
  172. package/src/repository-reconciliation.ts +30 -0
  173. package/src/repository-source-config.ts +79 -0
  174. package/src/repository-types.ts +63 -0
  175. package/src/review-flow-public.ts +5 -0
  176. package/src/review-flow.ts +6 -0
  177. package/src/runtime-internals-public.ts +7 -0
  178. package/src/server-events.ts +67 -0
  179. package/src/server-process-builder.ts +10 -1
  180. package/src/state-helpers.ts +14 -4
  181. package/src/subprocess-env.ts +9 -0
  182. package/src/tool-arguments.ts +39 -0
  183. package/src/tool-renderers.ts +6 -0
  184. package/src/turn-semantics.ts +45 -76
  185. package/src/types.ts +216 -44
  186. package/src/ui-process-builder.ts +8 -1
  187. package/src/worker-process-builder.ts +8 -1
  188. package/dist/browser-ui-extension.js +0 -2
  189. package/dist/browser-ui-extension.js.map +0 -1
  190. package/dist/capabilities.js +0 -7
  191. package/dist/capabilities.js.map +0 -1
  192. package/dist/chunk-5RJZ2E7D.js.map +0 -1
  193. package/dist/chunk-LIIP7FMU.js.map +0 -1
  194. package/dist/chunk-TRQJ5PRM.js.map +0 -1
  195. package/dist/codecs.js +0 -9
  196. package/dist/codecs.js.map +0 -1
  197. package/dist/commit-message.js +0 -3
  198. package/dist/commit-message.js.map +0 -1
  199. package/dist/core-capabilities.js +0 -6
  200. package/dist/core-capabilities.js.map +0 -1
  201. package/dist/define-process.js +0 -1078
  202. package/dist/define-process.js.map +0 -1
  203. package/dist/event-bus.js +0 -31
  204. package/dist/event-bus.js.map +0 -1
  205. package/dist/extension-api.js +0 -5
  206. package/dist/extension-api.js.map +0 -1
  207. package/dist/flow.js +0 -1645
  208. package/dist/flow.js.map +0 -1
  209. package/dist/form-contract.js +0 -2
  210. package/dist/form-contract.js.map +0 -1
  211. package/dist/fs-utils.js +0 -23
  212. package/dist/fs-utils.js.map +0 -1
  213. package/dist/graph-fragments.js +0 -57
  214. package/dist/graph-fragments.js.map +0 -1
  215. package/dist/host-capabilities.js +0 -42
  216. package/dist/host-capabilities.js.map +0 -1
  217. package/dist/launcher-contract.js +0 -2
  218. package/dist/launcher-contract.js.map +0 -1
  219. package/dist/leaf-outcomes.js +0 -52
  220. package/dist/leaf-outcomes.js.map +0 -1
  221. package/dist/model-provider.js +0 -171
  222. package/dist/model-provider.js.map +0 -1
  223. package/dist/process-definition-internals.js +0 -25
  224. package/dist/process-definition-internals.js.map +0 -1
  225. package/dist/process-flow-view.js +0 -418
  226. package/dist/process-flow-view.js.map +0 -1
  227. package/dist/process-graph.js +0 -212
  228. package/dist/process-graph.js.map +0 -1
  229. package/dist/process-launcher-builder.js +0 -43
  230. package/dist/process-launcher-builder.js.map +0 -1
  231. package/dist/process-watcher-builder.js +0 -40
  232. package/dist/process-watcher-builder.js.map +0 -1
  233. package/dist/process-watcher-source.js +0 -52
  234. package/dist/process-watcher-source.js.map +0 -1
  235. package/dist/registry-utils.js +0 -18
  236. package/dist/registry-utils.js.map +0 -1
  237. package/dist/repository-git-env.js +0 -26
  238. package/dist/repository-git-env.js.map +0 -1
  239. package/dist/server-events.js +0 -2
  240. package/dist/server-events.js.map +0 -1
  241. package/dist/server-process-builder.js +0 -52
  242. package/dist/server-process-builder.js.map +0 -1
  243. package/dist/state-helpers.js +0 -18
  244. package/dist/state-helpers.js.map +0 -1
  245. package/dist/subprocess-env.js +0 -34
  246. package/dist/subprocess-env.js.map +0 -1
  247. package/dist/tool-renderers.js +0 -63
  248. package/dist/tool-renderers.js.map +0 -1
  249. package/dist/turn-semantics.js +0 -365
  250. package/dist/turn-semantics.js.map +0 -1
  251. package/dist/types.js +0 -23
  252. package/dist/types.js.map +0 -1
  253. package/dist/ui-process-builder.js +0 -30
  254. package/dist/ui-process-builder.js.map +0 -1
  255. package/dist/worker-process-builder.js +0 -22
  256. package/dist/worker-process-builder.js.map +0 -1
@@ -1,1078 +0,0 @@
1
- import { assertValidProcessProductName, } from "@leitwerk-dev/domain";
2
- import { getProcessTurnTransitions, markDefinedProcess, setProcessTurnTransitions, } from "./process-definition-internals.js";
3
- function createTransitionTargetError(context, detail) {
4
- return new Error(`${context} ${detail}`);
5
- }
6
- function createProcessTurnBinding(definition, transitions) {
7
- const binding = { definition };
8
- if (transitions && transitions.length > 0) {
9
- setProcessTurnTransitions(binding, transitions);
10
- }
11
- return binding;
12
- }
13
- function normalizeStaticRouteTarget(context, target, knownTurnIds) {
14
- const declaredTargetCount = (target.to !== undefined ? 1 : 0) +
15
- (target.complete === true ? 1 : 0) +
16
- (target.lifecycleStatus !== undefined ? 1 : 0);
17
- if (declaredTargetCount !== 1) {
18
- throw createTransitionTargetError(context, "must declare exactly one target via 'to', 'complete', or 'lifecycleStatus'");
19
- }
20
- if (target.to !== undefined) {
21
- if (knownTurnIds && !knownTurnIds.has(target.to)) {
22
- throw createTransitionTargetError(context, `references unknown turn '${target.to}'`);
23
- }
24
- return { nextTurnId: target.to };
25
- }
26
- if (target.complete === true) {
27
- return { lifecycleStatus: "completed" };
28
- }
29
- return { lifecycleStatus: target.lifecycleStatus };
30
- }
31
- function buildOutcomeTransition(turnId, outcome, target, knownTurnIds) {
32
- if ("branches" in target) {
33
- throw new Error(`Turn '${turnId}' outcome '${outcome}' must compile state routing before a static transition`);
34
- }
35
- if ("wait" in target && target.wait && hasDeclaredStaticRouteTarget(target)) {
36
- throw new Error(`Turn '${turnId}' outcome '${outcome}' cannot wait and declare another route`);
37
- }
38
- if (!hasDeclaredStaticRouteTarget(target)) {
39
- return { nextTurnId: turnId };
40
- }
41
- return normalizeStaticRouteTarget(`Turn '${turnId}' outcome '${outcome}'`, target, knownTurnIds);
42
- }
43
- function normalizeBranchRoutes(input) {
44
- const entries = Object.entries(input.branches);
45
- if (entries.length === 0)
46
- throw new Error(`${input.subject} must declare at least one branch`);
47
- const routes = {};
48
- const transitions = [];
49
- const usedTriggers = new Set();
50
- for (const [branchId, branchSpec] of entries) {
51
- if (branchId.trim() === "")
52
- throw new Error(`${input.subject} contains an empty branch id`);
53
- const target = normalizeStaticRouteTarget(`${input.subject} branch '${branchId}'`, branchSpec, input.knownTurnIds);
54
- const trigger = branchSpec.trigger ?? branchId;
55
- if (usedTriggers.has(trigger)) {
56
- throw new Error(`${input.subject} contains duplicate branch trigger '${trigger}'`);
57
- }
58
- usedTriggers.add(trigger);
59
- const route = { ...target, trigger };
60
- routes[branchId] = route;
61
- transitions.push(route);
62
- }
63
- return { routes, transitions };
64
- }
65
- function resolveOutcomeRouting(input) {
66
- if (!("branches" in input.spec)) {
67
- return null;
68
- }
69
- const { routes } = normalizeBranchRoutes({
70
- subject: `Turn '${input.turnId}' outcome '${input.outcome}'`,
71
- branches: input.spec.branches,
72
- knownTurnIds: input.knownTurnIds,
73
- });
74
- return { routes, choose: input.spec.choose };
75
- }
76
- function resolveActionRouting(input) {
77
- if ("branches" in input.spec) {
78
- const { routes, transitions } = normalizeBranchRoutes({
79
- subject: `Action '${input.actionId}' on turn '${input.turnId}'`,
80
- branches: input.spec.branches,
81
- knownTurnIds: input.knownTurnIds,
82
- });
83
- return {
84
- routing: { kind: "branches", routes, choose: input.spec.choose },
85
- transitions,
86
- };
87
- }
88
- const target = normalizeStaticRouteTarget(`Action '${input.actionId}' on turn '${input.turnId}'`, input.spec, input.knownTurnIds);
89
- const route = {
90
- ...(target.nextTurnId ? { nextTurnId: target.nextTurnId } : {}),
91
- ...(target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {}),
92
- trigger: input.spec.trigger ?? input.actionId,
93
- };
94
- return {
95
- routing: {
96
- kind: "static",
97
- route,
98
- },
99
- transitions: [route],
100
- };
101
- }
102
- function externalSourceTransitionId(input) {
103
- return `${input.turnId}:${input.source.kind}:${input.index}`;
104
- }
105
- function externalActionArmingId(input) {
106
- return `${input.turnId}:${input.externalActionId}`;
107
- }
108
- function externalActionTransitionTrigger(input) {
109
- return `external:${input.externalActionId}`;
110
- }
111
- function compileExternalSourceTransitions(input) {
112
- if (input.spec.transitions.length === 0) {
113
- throw new Error(`External turn '${input.turnId}' must declare at least one source transition`);
114
- }
115
- return input.spec.transitions.map((transition, index) => {
116
- if (transition.source.kind.trim() === "") {
117
- throw new Error(`External turn '${input.turnId}' source transition ${index} has an empty kind`);
118
- }
119
- const target = normalizeStaticRouteTarget(`External turn '${input.turnId}' source '${transition.source.kind}'`, transition, input.knownTurnIds);
120
- return {
121
- ...(target.nextTurnId ? { nextTurnId: target.nextTurnId } : {}),
122
- ...(target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {}),
123
- trigger: externalSourceTransitionId({
124
- turnId: input.turnId,
125
- source: transition.source,
126
- index,
127
- }),
128
- };
129
- });
130
- }
131
- export function getExternalSourceTransitionId(input) {
132
- return externalSourceTransitionId(input);
133
- }
134
- export function getExternalActionArmingId(input) {
135
- return externalActionArmingId(input);
136
- }
137
- export function getExternalActionTransitionTrigger(input) {
138
- return externalActionTransitionTrigger(input);
139
- }
140
- function previewMatchesTransition(preview, transition) {
141
- if (preview.kind === "trigger") {
142
- return transition.trigger === preview.trigger;
143
- }
144
- if (preview.kind === "terminal") {
145
- return transition.lifecycleStatus === preview.lifecycleStatus;
146
- }
147
- return transition.nextTurnId === preview.turnId;
148
- }
149
- function validateActionPreviewMatchesTransitions(input) {
150
- const matches = input.transitions.filter((transition) => previewMatchesTransition(input.preview, transition));
151
- if (matches.length === 1) {
152
- return;
153
- }
154
- const previewLabel = input.preview.kind === "trigger"
155
- ? `trigger '${input.preview.trigger}'`
156
- : input.preview.kind === "terminal"
157
- ? `terminal '${input.preview.lifecycleStatus}'`
158
- : `fixed turn '${String(input.preview.turnId)}'`;
159
- throw new Error(`Action '${input.actionId}' on turn '${input.turnId}' ${input.context} does not match a compiled transition for ${previewLabel}`);
160
- }
161
- function buildActionPreviewAndScheduling(turnId, actionId, spec, transitions) {
162
- const preview = (() => {
163
- if (spec.preview) {
164
- return spec.preview;
165
- }
166
- if (transitions.length !== 1) {
167
- return undefined;
168
- }
169
- const [transition] = transitions;
170
- if (!transition) {
171
- return undefined;
172
- }
173
- if (transition.lifecycleStatus !== undefined) {
174
- return {
175
- kind: "terminal",
176
- lifecycleStatus: transition.lifecycleStatus,
177
- };
178
- }
179
- return {
180
- kind: "trigger",
181
- trigger: transition.trigger,
182
- };
183
- })();
184
- if (spec.preview && preview) {
185
- validateActionPreviewMatchesTransitions({
186
- turnId,
187
- actionId,
188
- preview,
189
- transitions,
190
- context: "preview",
191
- });
192
- }
193
- if (spec.schedulable && preview) {
194
- validateActionPreviewMatchesTransitions({
195
- turnId,
196
- actionId,
197
- preview,
198
- transitions,
199
- context: "scheduling",
200
- });
201
- }
202
- if (spec.schedulable && !preview) {
203
- throw new Error(`Action '${actionId}' is schedulable but does not resolve to a unique preview transition`);
204
- }
205
- return {
206
- ...(preview ? { preview } : {}),
207
- ...(spec.schedulable && preview ? { scheduling: { preview } } : {}),
208
- };
209
- }
210
- function mergeProcessEffectPlans(left, right) {
211
- if (!left) {
212
- return right;
213
- }
214
- if (!right) {
215
- return left;
216
- }
217
- return {
218
- ...left,
219
- ...right,
220
- ...(left.processPatch || right.processPatch
221
- ? { processPatch: { ...(left.processPatch ?? {}), ...(right.processPatch ?? {}) } }
222
- : {}),
223
- ...(left.broadcasts || right.broadcasts
224
- ? { broadcasts: [...(left.broadcasts ?? []), ...(right.broadcasts ?? [])] }
225
- : {}),
226
- ...(left.emit || right.emit ? { emit: [...(left.emit ?? []), ...(right.emit ?? [])] } : {}),
227
- ...(left.queueInput || right.queueInput
228
- ? { queueInput: [...(left.queueInput ?? []), ...(right.queueInput ?? [])] }
229
- : {}),
230
- };
231
- }
232
- function normalizeEffectString(value) {
233
- return typeof value === "string" ? value.trim() : "";
234
- }
235
- function normalizeEffectStringArray(value) {
236
- return Array.isArray(value)
237
- ? value
238
- .map((entry) => (typeof entry === "string" ? entry.trim() : ""))
239
- .filter((entry) => entry !== "")
240
- : [];
241
- }
242
- async function buildSavePlanResultEffect(input) {
243
- const statePlan = input.intent.state ? await input.intent.state(input.execution) : undefined;
244
- const planRevision = input.execution.ctx.process.planRevision + 1;
245
- const summary = normalizeEffectString(input.execution.event.params[input.intent.summaryParam]);
246
- const acceptanceCriteria = normalizeEffectStringArray(input.execution.event.params[input.intent.acceptanceCriteriaParam]);
247
- const planMarkdown = typeof input.execution.event.turnResultMarkdown === "string"
248
- ? input.execution.event.turnResultMarkdown
249
- : normalizeEffectString(input.execution.event.params[input.intent.planMarkdownParam]);
250
- return mergeProcessEffectPlans(statePlan, {
251
- processPatch: { planRevision },
252
- broadcasts: [
253
- {
254
- type: input.intent.broadcastType,
255
- payload: {
256
- planRevision,
257
- reviewState: "awaiting_approval",
258
- approved: false,
259
- summary,
260
- },
261
- },
262
- ],
263
- emit: [
264
- {
265
- type: input.intent.emitEventType,
266
- data: {
267
- planRevision,
268
- summary,
269
- planMarkdown,
270
- acceptanceCriteria,
271
- },
272
- },
273
- ],
274
- });
275
- }
276
- function resolveOutcomeEffect(input) {
277
- const lifecycleIntent = "lifecycleIntent" in input.spec ? input.spec.lifecycleIntent : undefined;
278
- const waits = "wait" in input.spec && input.spec.wait === true;
279
- if (!lifecycleIntent && !waits)
280
- return input.spec.effect;
281
- return async (execution) => {
282
- const explicitPlan = input.spec.effect ? await input.spec.effect(execution) : undefined;
283
- let lifecyclePlan;
284
- if (lifecycleIntent) {
285
- switch (lifecycleIntent.kind) {
286
- case "save_plan_result":
287
- lifecyclePlan = await buildSavePlanResultEffect({
288
- intent: lifecycleIntent,
289
- execution,
290
- });
291
- break;
292
- }
293
- }
294
- const result = mergeProcessEffectPlans(explicitPlan, lifecyclePlan);
295
- return waits
296
- ? mergeProcessEffectPlans(result, { processPatch: { lifecycleStatus: "waiting" } })
297
- : result;
298
- };
299
- }
300
- function areFormsEquivalent(left, right) {
301
- if (left === right) {
302
- return true;
303
- }
304
- return JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
305
- }
306
- function cloneStateForFormPatch(state) {
307
- if (typeof state !== "object" || state === null) {
308
- throw new Error("Declarative form state fields require object process state");
309
- }
310
- return structuredClone(state);
311
- }
312
- function normalizeFormStateValue(field, value) {
313
- if (field.kind === "number") {
314
- const parsed = typeof value === "number" ? value : Number(String(value).trim());
315
- if (!Number.isFinite(parsed)) {
316
- throw new Error(`Field '${field.id}' must be a number`);
317
- }
318
- return parsed;
319
- }
320
- return value;
321
- }
322
- function applyFormStateFields(input) {
323
- const stateFields = (input.form?.fields ?? []).filter((field) => field.state);
324
- if (stateFields.length === 0) {
325
- return undefined;
326
- }
327
- const nextState = cloneStateForFormPatch(input.state);
328
- for (const field of stateFields) {
329
- const rawValue = input.inputValue[field.id];
330
- if (rawValue === undefined) {
331
- continue;
332
- }
333
- const path = field.state?.path.trim();
334
- if (!path) {
335
- throw new Error(`Form field '${field.id}' declares an empty state path`);
336
- }
337
- const segments = path.split(".").map((segment) => segment.trim());
338
- if (segments.some((segment) => segment === "")) {
339
- throw new Error(`Form field '${field.id}' declares invalid state path '${path}'`);
340
- }
341
- let target = nextState;
342
- for (const segment of segments.slice(0, -1)) {
343
- const existing = target[segment];
344
- if (typeof existing !== "object" || existing === null || Array.isArray(existing)) {
345
- target[segment] = {};
346
- }
347
- target = target[segment];
348
- }
349
- target[segments[segments.length - 1]] = normalizeFormStateValue(field, rawValue);
350
- }
351
- return nextState;
352
- }
353
- function makeProcessServerRuntimeContext(ctx) {
354
- return {
355
- process: ctx.process,
356
- projects: ctx.projects,
357
- params: ctx.params,
358
- state: ctx.state,
359
- readSemanticTurnResultMarkdown: (ref) => ctx.readSemanticTurnResultMarkdown(ref),
360
- readProductTurnResultMarkdown: (productName) => ctx.readProductTurnResultMarkdown(productName),
361
- };
362
- }
363
- function mergeTransitionWithState(input) {
364
- const next = {
365
- ...(input.transition ?? {}),
366
- ...(input.result?.state !== undefined ? { state: input.result.state } : {}),
367
- };
368
- const hasFields = next.turnId !== undefined ||
369
- next.lifecycleStatus !== undefined ||
370
- next.trigger !== undefined ||
371
- next.effect !== undefined ||
372
- next.state !== undefined;
373
- return hasFields ? next : null;
374
- }
375
- function hasLifecycleEffects(result) {
376
- return Boolean(result?.processPatch !== undefined ||
377
- (result?.broadcasts !== undefined && result.broadcasts.length > 0));
378
- }
379
- async function applyProcessEffectPlan(input) {
380
- const transition = mergeTransitionWithState({
381
- result: input.result,
382
- transition: input.transition,
383
- });
384
- if (transition) {
385
- await input.ctx.transition(transition);
386
- }
387
- if (hasLifecycleEffects(input.result)) {
388
- if (!input.ctx.applyLifecycleEffects) {
389
- throw new Error("Process lifecycle effects are not supported by this server context");
390
- }
391
- input.ctx.applyLifecycleEffects({
392
- ...(input.result.processPatch ? { processPatch: input.result.processPatch } : {}),
393
- ...(input.result.broadcasts ? { broadcasts: input.result.broadcasts } : {}),
394
- });
395
- }
396
- for (const emitted of input.result?.emit ?? []) {
397
- input.ctx.emitEvent(emitted.type, emitted.data);
398
- }
399
- for (const queuedInput of input.result?.queueInput ?? []) {
400
- input.ctx.queueInput(queuedInput);
401
- }
402
- }
403
- function compileTurnOutcomeDefinitions(input) {
404
- const outcomeEntries = Object.entries(input.outcomes ?? {});
405
- if (outcomeEntries.length > 0 && input.turnEnd) {
406
- throw new Error(`Turn '${input.turnId}' cannot declare both tool outcomes and a turnEnd result`);
407
- }
408
- if (outcomeEntries.length === 0 && !input.turnEnd) {
409
- throw new Error(`Turn '${input.turnId}' must declare at least one tool outcome or a turnEnd result`);
410
- }
411
- const transitions = [];
412
- const outcomes = new Map();
413
- for (const [outcome, spec] of outcomeEntries) {
414
- if (outcome.trim() === "") {
415
- throw new Error(`Turn '${input.turnId}' declares an empty outcome id`);
416
- }
417
- const routing = resolveOutcomeRouting({
418
- turnId: input.turnId,
419
- outcome,
420
- spec,
421
- knownTurnIds: input.knownTurnIds,
422
- });
423
- const target = routing
424
- ? null
425
- : buildOutcomeTransition(input.turnId, outcome, spec, input.knownTurnIds);
426
- if (routing) {
427
- for (const route of Object.values(routing.routes)) {
428
- transitions.push({
429
- ...(route.nextTurnId ? { nextTurnId: route.nextTurnId } : {}),
430
- ...(route.lifecycleStatus ? { lifecycleStatus: route.lifecycleStatus } : {}),
431
- trigger: route.trigger,
432
- outcome,
433
- });
434
- }
435
- }
436
- else if (target) {
437
- transitions.push({
438
- ...(target.nextTurnId ? { nextTurnId: target.nextTurnId } : {}),
439
- ...(target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {}),
440
- outcome,
441
- });
442
- }
443
- outcomes.set(outcome, {
444
- effect: resolveOutcomeEffect({ spec }),
445
- ...(routing ? { routing } : {}),
446
- });
447
- }
448
- if (input.turnEnd) {
449
- if (input.turnEnd.outcome.trim() === "") {
450
- throw new Error(`Turn '${input.turnId}' declares an empty turnEnd outcome id`);
451
- }
452
- const target = buildOutcomeTransition(input.turnId, input.turnEnd.outcome, input.turnEnd, input.knownTurnIds);
453
- transitions.push({
454
- ...(target.nextTurnId ? { nextTurnId: target.nextTurnId } : {}),
455
- ...(target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {}),
456
- outcome: input.turnEnd.outcome,
457
- });
458
- outcomes.set(input.turnEnd.outcome, {
459
- effect: resolveOutcomeEffect({ spec: input.turnEnd }),
460
- });
461
- }
462
- return { transitions, outcomes };
463
- }
464
- function addActionUse(input) {
465
- const existing = input.actionUses.get(input.actionId) ?? [];
466
- if (existing.some((candidate) => candidate.turnId === input.use.turnId)) {
467
- throw new Error(`Turn '${input.use.turnId}' declares action '${input.actionId}' more than once`);
468
- }
469
- existing.push(input.use);
470
- input.actionUses.set(input.actionId, existing);
471
- }
472
- function hasDeclaredStaticRouteTarget(target) {
473
- return (target.to !== undefined || target.complete === true || target.lifecycleStatus !== undefined);
474
- }
475
- function resolveExternalActionRoute(input) {
476
- if (input.externalActionId.trim() === "") {
477
- throw new Error(`Human turn '${input.turnId}' declares an empty external action id`);
478
- }
479
- if (input.spec.id !== input.externalActionId) {
480
- throw new Error(`Human turn '${input.turnId}' external action '${input.externalActionId}' has mismatched spec id '${input.spec.id}'`);
481
- }
482
- if (input.spec.source.kind.trim() === "") {
483
- throw new Error(`Human turn '${input.turnId}' external action '${input.externalActionId}' must declare a non-empty source kind`);
484
- }
485
- const target = normalizeStaticRouteTarget(`Human turn '${input.turnId}' external action '${input.externalActionId}'`, input.spec, input.knownTurnIds);
486
- return {
487
- ...(target.nextTurnId ? { nextTurnId: target.nextTurnId } : {}),
488
- ...(target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {}),
489
- trigger: externalActionTransitionTrigger({ externalActionId: input.externalActionId }),
490
- };
491
- }
492
- function validateExternalActionPublishedInputTarget(input) {
493
- const publication = input.spec.publishInput;
494
- if (!publication || !input.turnDefinitionsById) {
495
- return;
496
- }
497
- if (input.spec.to === undefined) {
498
- throw new Error(`Human turn '${input.turnId}' external action '${input.externalActionId}' publishes input '${publication.productName}' but does not route to a consuming turn`);
499
- }
500
- const targetTurn = input.turnDefinitionsById.get(input.spec.to);
501
- if (!targetTurn || targetTurn.kind !== "llm") {
502
- throw new Error(`Human turn '${input.turnId}' external action '${input.externalActionId}' publishes input '${publication.productName}' but target turn '${input.spec.to}' is not an LLM turn`);
503
- }
504
- const consumed = new Set([
505
- ...(targetTurn.consumedProducts ?? []),
506
- ...(targetTurn.optionalConsumedProducts ?? []),
507
- ]);
508
- if (!consumed.has(publication.productName)) {
509
- throw new Error(`Human turn '${input.turnId}' external action '${input.externalActionId}' publishes input '${publication.productName}' but target turn '${input.spec.to}' does not consume it`);
510
- }
511
- }
512
- function validateActionPrimaryPrompt(turnId, actionId, action) {
513
- const fields = action.form?.fields ?? [];
514
- const textualFields = fields.filter((field) => field.kind === "text" || field.kind === "textarea");
515
- const primaryPrompts = fields.filter((field) => field.primaryPrompt);
516
- if (primaryPrompts.some((field) => field.kind !== "text" && field.kind !== "textarea")) {
517
- throw new Error(`Human turn '${turnId}' action '${actionId}' primary prompt must be a text or textarea field`);
518
- }
519
- if (primaryPrompts.length > 1) {
520
- throw new Error(`Human turn '${turnId}' action '${actionId}' must declare at most one primary prompt`);
521
- }
522
- if (textualFields.length > 0 && primaryPrompts.length === 0) {
523
- throw new Error(`Human turn '${turnId}' action '${actionId}' with textual fields must declare a primary prompt`);
524
- }
525
- }
526
- function deriveExternalActions(input) {
527
- const externalActions = [];
528
- const transitions = [];
529
- const usedTriggers = new Map(input.reservedTriggers);
530
- for (const [externalActionId, actionSpec] of Object.entries(input.externalActions ?? {})) {
531
- if (actionSpec.publishInput) {
532
- assertValidProcessProductName(actionSpec.publishInput.productName);
533
- if (actionSpec.publishInput.inputField.trim() === "") {
534
- throw new Error(`Turn '${input.turnId}' external action '${externalActionId}' publishInput must declare a non-empty inputField`);
535
- }
536
- }
537
- validateExternalActionPublishedInputTarget({
538
- turnId: input.turnId,
539
- externalActionId,
540
- spec: actionSpec,
541
- turnDefinitionsById: input.turnDefinitionsById,
542
- });
543
- const transition = resolveExternalActionRoute({
544
- turnId: input.turnId,
545
- externalActionId,
546
- spec: actionSpec,
547
- knownTurnIds: input.knownTurnIds,
548
- });
549
- const existingActionId = usedTriggers.get(transition.trigger);
550
- if (existingActionId) {
551
- throw new Error(`Turn '${input.turnId}' contains duplicate trigger '${transition.trigger}' across action '${existingActionId}' and external action '${externalActionId}'`);
552
- }
553
- usedTriggers.set(transition.trigger, externalActionId);
554
- transitions.push({
555
- ...(transition.nextTurnId ? { nextTurnId: transition.nextTurnId } : {}),
556
- ...(transition.lifecycleStatus ? { lifecycleStatus: transition.lifecycleStatus } : {}),
557
- trigger: transition.trigger,
558
- });
559
- externalActions.push({
560
- externalActionId,
561
- actionSpec,
562
- transition,
563
- view: {
564
- id: externalActionArmingId({ turnId: input.turnId, externalActionId }),
565
- externalActionId,
566
- sourceKind: actionSpec.source.kind,
567
- label: actionSpec.label ?? actionSpec.source.label ?? null,
568
- description: actionSpec.description ?? actionSpec.source.description ?? null,
569
- },
570
- });
571
- }
572
- return { externalActions, transitions };
573
- }
574
- function deriveHumanTurnActions(input) {
575
- const actionEntries = Object.entries(input.spec.actions);
576
- if (actionEntries.length === 0 && input.knownTurnIds) {
577
- throw new Error(`Human turn '${input.turnId}' must declare at least one action`);
578
- }
579
- const derivedActions = [];
580
- const transitions = [];
581
- const actionIdByTrigger = new Map();
582
- for (const [actionId, actionSpec] of actionEntries) {
583
- if (actionId.trim() === "") {
584
- throw new Error(`Human turn '${input.turnId}' declares an empty action id`);
585
- }
586
- validateActionPrimaryPrompt(input.turnId, actionId, actionSpec);
587
- const resolved = !input.knownTurnIds &&
588
- !("branches" in actionSpec) &&
589
- !hasDeclaredStaticRouteTarget(actionSpec)
590
- ? {
591
- routing: {
592
- kind: "static",
593
- route: { trigger: actionSpec.trigger ?? actionId },
594
- },
595
- transitions: [],
596
- }
597
- : resolveActionRouting({
598
- turnId: input.turnId,
599
- actionId,
600
- spec: actionSpec,
601
- knownTurnIds: input.knownTurnIds,
602
- });
603
- for (const transition of resolved.transitions) {
604
- const existingActionId = actionIdByTrigger.get(transition.trigger);
605
- if (existingActionId && existingActionId !== actionId) {
606
- throw new Error(`Human turn '${input.turnId}' contains duplicate action trigger '${transition.trigger}' across actions '${existingActionId}' and '${actionId}'`);
607
- }
608
- actionIdByTrigger.set(transition.trigger, actionId);
609
- transitions.push({
610
- ...(transition.nextTurnId ? { nextTurnId: transition.nextTurnId } : {}),
611
- ...(transition.lifecycleStatus ? { lifecycleStatus: transition.lifecycleStatus } : {}),
612
- trigger: transition.trigger,
613
- });
614
- }
615
- const previewAndScheduling = !input.knownTurnIds && resolved.transitions.length === 0
616
- ? {
617
- ...(actionSpec.preview ? { preview: actionSpec.preview } : {}),
618
- ...(actionSpec.schedulable && actionSpec.preview
619
- ? { scheduling: { preview: actionSpec.preview } }
620
- : {}),
621
- }
622
- : buildActionPreviewAndScheduling(input.turnId, actionId, actionSpec, resolved.transitions);
623
- derivedActions.push({
624
- actionId,
625
- actionSpec,
626
- routing: resolved.routing,
627
- transitions: resolved.transitions,
628
- actionView: {
629
- actionId,
630
- label: actionSpec.label,
631
- description: actionSpec.description,
632
- acceptanceState: actionSpec.acceptanceState,
633
- ...previewAndScheduling,
634
- },
635
- externalTriggers: actionSpec.externalTriggers?.map((trigger) => ({
636
- id: trigger.id,
637
- actionId,
638
- label: trigger.label,
639
- description: trigger.description,
640
- })) ?? [],
641
- });
642
- }
643
- const derivedExternal = deriveExternalActions({
644
- turnId: input.turnId,
645
- externalActions: input.spec.externalActions,
646
- knownTurnIds: input.knownTurnIds,
647
- turnDefinitionsById: input.turnDefinitionsById,
648
- reservedTriggers: actionIdByTrigger,
649
- });
650
- return {
651
- actions: derivedActions,
652
- externalActions: derivedExternal.externalActions,
653
- transitions: [...transitions, ...derivedExternal.transitions],
654
- };
655
- }
656
- export function resolveHumanTurnView(input) {
657
- const derived = deriveHumanTurnActions({
658
- turnId: input.turnId,
659
- spec: input.turn,
660
- });
661
- return {
662
- actions: derived.actions.map((action) => action.actionView),
663
- externalTriggers: derived.actions.flatMap((action) => action.externalTriggers),
664
- externalActions: derived.externalActions.map((action) => action.view),
665
- };
666
- }
667
- function compileHumanTurn(input) {
668
- const derived = deriveHumanTurnActions({
669
- turnId: input.turnId,
670
- spec: input.spec,
671
- knownTurnIds: input.knownTurnIds,
672
- turnDefinitionsById: input.turnDefinitionsById,
673
- });
674
- for (const action of derived.actions) {
675
- addActionUse({
676
- actionUses: input.actionUses,
677
- actionId: action.actionId,
678
- use: {
679
- turnId: input.turnId,
680
- label: action.actionSpec.label,
681
- ...(action.actionSpec.form ? { form: action.actionSpec.form } : {}),
682
- ...(action.actionSpec.effect ? { effect: action.actionSpec.effect } : {}),
683
- routing: action.routing,
684
- },
685
- });
686
- }
687
- return {
688
- binding: createProcessTurnBinding(input.spec, derived.transitions),
689
- };
690
- }
691
- function compileExternalTurn(input) {
692
- const transitions = compileExternalSourceTransitions({
693
- turnId: input.turnId,
694
- spec: input.spec,
695
- knownTurnIds: input.knownTurnIds,
696
- });
697
- return {
698
- binding: createProcessTurnBinding(input.spec, transitions),
699
- };
700
- }
701
- function getTurnEntries(turns) {
702
- return Object.entries(turns);
703
- }
704
- function resolveActionRouteForExecution(input) {
705
- if (input.use.routing.kind === "static") {
706
- return { route: input.use.routing.route };
707
- }
708
- const actionExecution = {
709
- ctx: makeProcessServerRuntimeContext(input.ctx),
710
- input: input.inputValue,
711
- turnId: input.use.turnId,
712
- actionId: input.actionId,
713
- };
714
- const routes = input.use.routing.routes;
715
- return Promise.resolve(input.use.routing.choose(actionExecution)).then((selectedBranchId) => {
716
- if (!Object.hasOwn(routes, selectedBranchId)) {
717
- throw new Error(`Action '${input.actionId}' on turn '${input.use.turnId}' selected unknown branch '${selectedBranchId}'`);
718
- }
719
- const route = routes[selectedBranchId];
720
- if (!route) {
721
- throw new Error(`Action '${input.actionId}' on turn '${input.use.turnId}' selected unknown branch '${selectedBranchId}'`);
722
- }
723
- return { route, selectedBranchId };
724
- });
725
- }
726
- function buildActionTransitionRequest(route) {
727
- if (route.nextTurnId !== undefined) {
728
- return {
729
- turnId: route.nextTurnId,
730
- trigger: route.trigger,
731
- };
732
- }
733
- return {
734
- turnId: null,
735
- lifecycleStatus: route.lifecycleStatus,
736
- trigger: route.trigger,
737
- };
738
- }
739
- function validateHappyPathConnectivity(input) {
740
- const happyPath = input.happyPath;
741
- if (!happyPath || happyPath.length < 2) {
742
- return;
743
- }
744
- const happyPathTurns = new Set(happyPath);
745
- for (let index = 0; index < happyPath.length - 1; index += 1) {
746
- const source = happyPath[index];
747
- const target = happyPath[index + 1];
748
- let connected = false;
749
- const visited = new Set([source]);
750
- const queue = [source];
751
- while (queue.length > 0 && !connected) {
752
- const current = queue.shift();
753
- for (const transition of getProcessTurnTransitions(input.turns.get(current))) {
754
- const next = transition.nextTurnId;
755
- if (next === undefined || !input.turnDefinitionsById.has(next)) {
756
- continue;
757
- }
758
- if (next === target) {
759
- connected = true;
760
- break;
761
- }
762
- if (visited.has(next) || happyPathTurns.has(next)) {
763
- continue;
764
- }
765
- const definition = input.turnDefinitionsById.get(next);
766
- if (definition?.kind !== "human") {
767
- continue;
768
- }
769
- visited.add(next);
770
- queue.push(next);
771
- }
772
- }
773
- if (!connected) {
774
- throw new Error(`Process '${input.processId}' happy path segment '${source}' -> '${target}' is not connected by declared transitions`);
775
- }
776
- }
777
- }
778
- function buildDefinedProcess(input) {
779
- const turnEntries = getTurnEntries(input.turns);
780
- if (turnEntries.length === 0) {
781
- throw new Error(`Process '${input.id}' must declare at least one turn`);
782
- }
783
- const knownTurnIds = new Set(turnEntries.map(([turnId]) => turnId));
784
- const turnDefinitionsById = new Map(turnEntries.map(([turnId, turnSpec]) => [turnId, turnSpec]));
785
- if (!knownTurnIds.has(input.entry)) {
786
- throw new Error(`Process '${input.id}' entry turn '${input.entry}' is not declared`);
787
- }
788
- const seenEntries = new Set();
789
- for (const turnId of [input.entry, ...(input.alternateEntries ?? [])]) {
790
- if (seenEntries.has(turnId)) {
791
- throw new Error(`Process '${input.id}' declares duplicate entry turn '${turnId}'`);
792
- }
793
- if (!knownTurnIds.has(turnId)) {
794
- throw new Error(`Process '${input.id}' entry turn '${turnId}' is not declared`);
795
- }
796
- seenEntries.add(turnId);
797
- }
798
- if (input.happyPath) {
799
- if (input.happyPath.length === 0) {
800
- throw new Error(`Process '${input.id}' declares an empty happy path`);
801
- }
802
- const seen = new Set();
803
- for (const turnId of input.happyPath) {
804
- if (!knownTurnIds.has(turnId)) {
805
- throw new Error(`Process '${input.id}' happy path references undeclared turn '${turnId}'`);
806
- }
807
- if (seen.has(turnId)) {
808
- throw new Error(`Process '${input.id}' happy path repeats turn '${turnId}'`);
809
- }
810
- seen.add(turnId);
811
- }
812
- if (input.happyPath[0] !== input.entry) {
813
- throw new Error(`Process '${input.id}' happy path must start at the entry turn '${input.entry}'`);
814
- }
815
- }
816
- const turns = new Map();
817
- const actionUses = new Map();
818
- const compiledOutcomesByTurn = new Map();
819
- const executableTurns = new Map();
820
- for (const [turnId, turnSpec] of turnEntries) {
821
- if (turnSpec.kind === "llm") {
822
- const compiledOutcomes = compileTurnOutcomeDefinitions({
823
- turnId,
824
- outcomes: turnSpec.outcomes,
825
- turnEnd: turnSpec.turnEnd,
826
- knownTurnIds,
827
- });
828
- turns.set(turnId, createProcessTurnBinding(turnSpec, compiledOutcomes.transitions));
829
- compiledOutcomesByTurn.set(turnId, compiledOutcomes.outcomes);
830
- executableTurns.set(turnId, {
831
- kind: "llm",
832
- id: turnId,
833
- spec: turnSpec,
834
- });
835
- continue;
836
- }
837
- if (turnSpec.kind === "automatic" || turnSpec.kind === "server_automatic") {
838
- const compiledOutcomes = compileTurnOutcomeDefinitions({
839
- turnId,
840
- outcomes: turnSpec.outcomes,
841
- turnEnd: turnSpec.turnEnd,
842
- knownTurnIds,
843
- });
844
- const externalTransitions = turnSpec.kind === "automatic"
845
- ? deriveExternalActions({
846
- turnId,
847
- externalActions: turnSpec.externalActions,
848
- knownTurnIds,
849
- turnDefinitionsById,
850
- }).transitions
851
- : [];
852
- turns.set(turnId, createProcessTurnBinding(turnSpec, [
853
- ...compiledOutcomes.transitions,
854
- ...externalTransitions,
855
- ]));
856
- compiledOutcomesByTurn.set(turnId, compiledOutcomes.outcomes);
857
- if (turnSpec.kind === "automatic") {
858
- executableTurns.set(turnId, {
859
- kind: "automatic",
860
- id: turnId,
861
- spec: turnSpec,
862
- });
863
- }
864
- continue;
865
- }
866
- if (turnSpec.kind === "human") {
867
- const compiled = compileHumanTurn({
868
- turnId,
869
- spec: turnSpec,
870
- knownTurnIds,
871
- turnDefinitionsById,
872
- actionUses,
873
- });
874
- turns.set(turnId, compiled.binding);
875
- continue;
876
- }
877
- const compiled = compileExternalTurn({
878
- turnId,
879
- spec: turnSpec,
880
- knownTurnIds,
881
- });
882
- turns.set(turnId, compiled.binding);
883
- }
884
- validateHappyPathConnectivity({
885
- processId: input.id,
886
- happyPath: input.happyPath,
887
- turns,
888
- turnDefinitionsById,
889
- });
890
- const worker = (api) => {
891
- api.start(input.entry);
892
- const manuallyRegisteredTurns = new Set();
893
- input.worker?.({
894
- start(turnId) {
895
- api.start(turnId);
896
- },
897
- turn(turnId, handler) {
898
- manuallyRegisteredTurns.add(turnId);
899
- api.turn(turnId, handler);
900
- },
901
- });
902
- for (const executable of executableTurns.values()) {
903
- if (manuallyRegisteredTurns.has(executable.id)) {
904
- continue;
905
- }
906
- if (executable.kind === "llm") {
907
- api.turn(executable.id, async (run) => {
908
- await run.turn(executable.spec);
909
- });
910
- continue;
911
- }
912
- api.turn(executable.id, async (run) => {
913
- await run.complete(await executable.spec.run(run.ctx));
914
- });
915
- }
916
- };
917
- const server = (api) => {
918
- for (const [actionId, uses] of actionUses) {
919
- const [firstUse] = uses;
920
- const form = firstUse?.form;
921
- for (const use of uses) {
922
- if (!areFormsEquivalent(form, use.form)) {
923
- throw new Error(`Action '${actionId}' must use the same form on every turn that references it`);
924
- }
925
- }
926
- api.action({
927
- id: actionId,
928
- label: firstUse?.label ?? actionId,
929
- ...(form ? { form } : {}),
930
- async plan(inputValue, ctx) {
931
- const turnId = ctx.process.selectedTurnId;
932
- const use = uses.find((candidate) => candidate.turnId === turnId);
933
- if (!use || !turnId) {
934
- throw new Error(`Action '${actionId}' is not available for selected turn '${String(turnId)}'`);
935
- }
936
- const resolvedRoute = await resolveActionRouteForExecution({
937
- use,
938
- actionId,
939
- ctx,
940
- inputValue,
941
- });
942
- const effectResult = use.effect
943
- ? await use.effect({
944
- ctx: makeProcessServerRuntimeContext(ctx),
945
- input: inputValue,
946
- turnId,
947
- actionId,
948
- ...(resolvedRoute.selectedBranchId
949
- ? { selectedBranchId: resolvedRoute.selectedBranchId }
950
- : {}),
951
- })
952
- : undefined;
953
- const formState = applyFormStateFields({
954
- form: use.form,
955
- inputValue,
956
- state: effectResult?.state ?? ctx.state,
957
- });
958
- const result = formState
959
- ? mergeProcessEffectPlans(effectResult, { state: formState })
960
- : effectResult;
961
- await applyProcessEffectPlan({
962
- ctx,
963
- result,
964
- transition: buildActionTransitionRequest(resolvedRoute.route),
965
- });
966
- },
967
- });
968
- }
969
- for (const [turnId, outcomes] of compiledOutcomesByTurn) {
970
- api.onTurnOutcome(turnId, async (event, ctx) => {
971
- const { effect, routing } = outcomes.get(event.outcome) ?? {};
972
- if (!effect && !routing) {
973
- return;
974
- }
975
- const execution = {
976
- ctx: makeProcessServerRuntimeContext(ctx),
977
- event,
978
- turnId,
979
- outcome: event.outcome,
980
- };
981
- const result = effect ? await effect(execution) : undefined;
982
- let transition;
983
- if (routing) {
984
- const branchId = await routing.choose(execution);
985
- const route = routing.routes[branchId];
986
- if (!route) {
987
- throw new Error(`Turn '${turnId}' outcome '${event.outcome}' selected unknown branch '${branchId}'`);
988
- }
989
- transition = buildActionTransitionRequest(route);
990
- }
991
- await applyProcessEffectPlan({ ctx, result, transition });
992
- });
993
- }
994
- input.server?.(api);
995
- };
996
- return {
997
- turns,
998
- worker,
999
- server,
1000
- };
1001
- }
1002
- export function defineProcess(input) {
1003
- const compiled = buildDefinedProcess(input);
1004
- const process = {
1005
- id: input.id,
1006
- displayName: input.displayName,
1007
- entryTurnId: input.entry,
1008
- alternateEntryTurnIds: [...(input.alternateEntries ?? [])],
1009
- ...(input.happyPath ? { happyPath: [...input.happyPath] } : {}),
1010
- turns: compiled.turns,
1011
- paramsCodec: input.paramsCodec,
1012
- stateCodec: input.stateCodec,
1013
- initialState: input.initialState,
1014
- ...(input.repositoryCredentials ? { repositoryCredentials: input.repositoryCredentials } : {}),
1015
- ...(input.piConfig ? { piConfig: input.piConfig } : {}),
1016
- server: compiled.server,
1017
- worker: compiled.worker,
1018
- ui: input.ui,
1019
- launchers: input.launchers,
1020
- watchers: input.watchers,
1021
- };
1022
- markDefinedProcess(process);
1023
- return process;
1024
- }
1025
- export function routeTurnOutcomes(baseTurn, routes, options = {}) {
1026
- const baseOutcomes = (baseTurn.outcomes ?? {});
1027
- for (const outcomeId of Object.keys(routes)) {
1028
- if (!baseOutcomes[outcomeId]) {
1029
- throw new Error(`Cannot route unknown outcome '${outcomeId}' on reusable turn`);
1030
- }
1031
- }
1032
- if (options.strict) {
1033
- for (const outcomeId of Object.keys(baseOutcomes)) {
1034
- if (!routes[outcomeId]) {
1035
- throw new Error(`Strict routing omitted outcome '${outcomeId}' on reusable turn`);
1036
- }
1037
- }
1038
- }
1039
- return {
1040
- ...baseTurn,
1041
- outcomes: Object.fromEntries(Object.entries(baseOutcomes).map(([outcomeId, baseOutcome]) => [
1042
- outcomeId,
1043
- { ...baseOutcome, ...(routes[outcomeId] ?? {}) },
1044
- ])),
1045
- };
1046
- }
1047
- // biome-ignore-end lint/suspicious/noExplicitAny: end routable turn instantiation helper suppression
1048
- export function llmTurn(input) {
1049
- return {
1050
- ...input,
1051
- kind: "llm",
1052
- };
1053
- }
1054
- export function automaticTurn(input) {
1055
- return {
1056
- ...input,
1057
- kind: "automatic",
1058
- };
1059
- }
1060
- export function serverAutomaticTurn(input) {
1061
- return {
1062
- ...input,
1063
- kind: "server_automatic",
1064
- };
1065
- }
1066
- export function humanTurn(input) {
1067
- return {
1068
- ...input,
1069
- kind: "human",
1070
- };
1071
- }
1072
- export function externalTurn(input) {
1073
- return {
1074
- ...input,
1075
- kind: "external",
1076
- };
1077
- }
1078
- //# sourceMappingURL=define-process.js.map