@leitwerk-dev/process-sdk 0.1.2 → 0.1.3

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 (153) hide show
  1. package/dist/browser-ui-extension.d.ts +27 -0
  2. package/dist/browser-ui-extension.d.ts.map +1 -0
  3. package/dist/browser-ui-extension.js +2 -0
  4. package/dist/browser-ui-extension.js.map +1 -0
  5. package/dist/capabilities.d.ts +9 -0
  6. package/dist/capabilities.d.ts.map +1 -0
  7. package/dist/capabilities.js +7 -0
  8. package/dist/capabilities.js.map +1 -0
  9. package/dist/codecs.d.ts +3 -0
  10. package/dist/codecs.d.ts.map +1 -0
  11. package/dist/codecs.js +9 -0
  12. package/dist/codecs.js.map +1 -0
  13. package/dist/commit-message.d.ts +7 -0
  14. package/dist/commit-message.d.ts.map +1 -0
  15. package/dist/commit-message.js +3 -0
  16. package/dist/commit-message.js.map +1 -0
  17. package/dist/core-capabilities.d.ts +393 -0
  18. package/dist/core-capabilities.d.ts.map +1 -0
  19. package/dist/core-capabilities.js +6 -0
  20. package/dist/core-capabilities.js.map +1 -0
  21. package/dist/define-process.d.ts +269 -0
  22. package/dist/define-process.d.ts.map +1 -0
  23. package/dist/define-process.js +1040 -0
  24. package/dist/define-process.js.map +1 -0
  25. package/dist/event-bus.d.ts +3 -0
  26. package/dist/event-bus.d.ts.map +1 -0
  27. package/dist/event-bus.js +31 -0
  28. package/dist/event-bus.js.map +1 -0
  29. package/dist/extension-api.d.ts +425 -0
  30. package/dist/extension-api.d.ts.map +1 -0
  31. package/dist/extension-api.js +5 -0
  32. package/dist/extension-api.js.map +1 -0
  33. package/dist/flow.d.ts +456 -0
  34. package/dist/flow.d.ts.map +1 -0
  35. package/dist/flow.js +1557 -0
  36. package/dist/flow.js.map +1 -0
  37. package/dist/form-contract.d.ts +2 -0
  38. package/dist/form-contract.d.ts.map +1 -0
  39. package/dist/form-contract.js +2 -0
  40. package/dist/form-contract.js.map +1 -0
  41. package/dist/fs-utils.d.ts +3 -0
  42. package/dist/fs-utils.d.ts.map +1 -0
  43. package/dist/fs-utils.js +23 -0
  44. package/dist/fs-utils.js.map +1 -0
  45. package/dist/git-binary.d.ts +3 -4
  46. package/dist/git-binary.d.ts.map +1 -0
  47. package/dist/git-binary.js +33 -25
  48. package/dist/git-binary.js.map +1 -1
  49. package/dist/graph-fragments.d.ts +23 -0
  50. package/dist/graph-fragments.d.ts.map +1 -0
  51. package/dist/graph-fragments.js +57 -0
  52. package/dist/graph-fragments.js.map +1 -0
  53. package/dist/host-capabilities.d.ts +12 -0
  54. package/dist/host-capabilities.d.ts.map +1 -0
  55. package/dist/host-capabilities.js +42 -0
  56. package/dist/host-capabilities.js.map +1 -0
  57. package/dist/index.d.ts +35 -1066
  58. package/dist/index.d.ts.map +1 -0
  59. package/dist/index.js +28 -4488
  60. package/dist/index.js.map +1 -1
  61. package/dist/launcher-contract.d.ts +2 -0
  62. package/dist/launcher-contract.d.ts.map +1 -0
  63. package/dist/launcher-contract.js +2 -0
  64. package/dist/launcher-contract.js.map +1 -0
  65. package/dist/leaf-outcome-renderer.d.ts +7 -7
  66. package/dist/leaf-outcome-renderer.d.ts.map +1 -0
  67. package/dist/leaf-outcome-renderer.js +64 -74
  68. package/dist/leaf-outcome-renderer.js.map +1 -1
  69. package/dist/leaf-outcomes.d.ts +5 -0
  70. package/dist/leaf-outcomes.d.ts.map +1 -0
  71. package/dist/leaf-outcomes.js +52 -0
  72. package/dist/leaf-outcomes.js.map +1 -0
  73. package/dist/model-provider.d.ts +210 -0
  74. package/dist/model-provider.d.ts.map +1 -0
  75. package/dist/model-provider.js +171 -0
  76. package/dist/model-provider.js.map +1 -0
  77. package/dist/pi-config.d.ts +15 -19
  78. package/dist/pi-config.d.ts.map +1 -0
  79. package/dist/pi-config.js +180 -21
  80. package/dist/pi-config.js.map +1 -1
  81. package/dist/process-definition-internals.d.ts +7 -0
  82. package/dist/process-definition-internals.d.ts.map +1 -0
  83. package/dist/process-definition-internals.js +25 -0
  84. package/dist/process-definition-internals.js.map +1 -0
  85. package/dist/process-flow-view.d.ts +20 -0
  86. package/dist/process-flow-view.d.ts.map +1 -0
  87. package/dist/process-flow-view.js +418 -0
  88. package/dist/process-flow-view.js.map +1 -0
  89. package/dist/process-graph.d.ts +45 -0
  90. package/dist/process-graph.d.ts.map +1 -0
  91. package/dist/process-graph.js +213 -0
  92. package/dist/process-graph.js.map +1 -0
  93. package/dist/process-launcher-builder.d.ts +9 -0
  94. package/dist/process-launcher-builder.d.ts.map +1 -0
  95. package/dist/process-launcher-builder.js +43 -0
  96. package/dist/process-launcher-builder.js.map +1 -0
  97. package/dist/process-watcher-builder.d.ts +10 -0
  98. package/dist/process-watcher-builder.d.ts.map +1 -0
  99. package/dist/process-watcher-builder.js +40 -0
  100. package/dist/process-watcher-builder.js.map +1 -0
  101. package/dist/registry-utils.d.ts +8 -0
  102. package/dist/registry-utils.d.ts.map +1 -0
  103. package/dist/registry-utils.js +18 -0
  104. package/dist/registry-utils.js.map +1 -0
  105. package/dist/repository-git-env.d.ts +8 -0
  106. package/dist/repository-git-env.d.ts.map +1 -0
  107. package/dist/repository-git-env.js +26 -0
  108. package/dist/repository-git-env.js.map +1 -0
  109. package/dist/review-flow.d.ts +7 -13
  110. package/dist/review-flow.d.ts.map +1 -0
  111. package/dist/review-flow.js +43 -12
  112. package/dist/review-flow.js.map +1 -1
  113. package/dist/runtime-internals.d.ts +3 -21
  114. package/dist/runtime-internals.d.ts.map +1 -0
  115. package/dist/runtime-internals.js +2 -18
  116. package/dist/runtime-internals.js.map +1 -1
  117. package/dist/server-events.d.ts +84 -0
  118. package/dist/server-events.d.ts.map +1 -0
  119. package/dist/server-events.js +2 -0
  120. package/dist/server-events.js.map +1 -0
  121. package/dist/server-process-builder.d.ts +11 -0
  122. package/dist/server-process-builder.d.ts.map +1 -0
  123. package/dist/server-process-builder.js +52 -0
  124. package/dist/server-process-builder.js.map +1 -0
  125. package/dist/state-helpers.d.ts +9 -0
  126. package/dist/state-helpers.d.ts.map +1 -0
  127. package/dist/state-helpers.js +20 -0
  128. package/dist/state-helpers.js.map +1 -0
  129. package/dist/subprocess-env.d.ts +12 -0
  130. package/dist/subprocess-env.d.ts.map +1 -0
  131. package/dist/subprocess-env.js +34 -0
  132. package/dist/subprocess-env.js.map +1 -0
  133. package/dist/tool-renderers.d.ts +10 -0
  134. package/dist/tool-renderers.d.ts.map +1 -0
  135. package/dist/tool-renderers.js +63 -0
  136. package/dist/tool-renderers.js.map +1 -0
  137. package/dist/turn-semantics.d.ts +22 -0
  138. package/dist/turn-semantics.d.ts.map +1 -0
  139. package/dist/turn-semantics.js +339 -0
  140. package/dist/turn-semantics.js.map +1 -0
  141. package/dist/types.d.ts +295 -0
  142. package/dist/types.d.ts.map +1 -0
  143. package/dist/types.js +12 -0
  144. package/dist/types.js.map +1 -0
  145. package/dist/ui-process-builder.d.ts +9 -0
  146. package/dist/ui-process-builder.d.ts.map +1 -0
  147. package/dist/ui-process-builder.js +30 -0
  148. package/dist/ui-process-builder.js.map +1 -0
  149. package/dist/worker-process-builder.d.ts +10 -0
  150. package/dist/worker-process-builder.d.ts.map +1 -0
  151. package/dist/worker-process-builder.js +22 -0
  152. package/dist/worker-process-builder.js.map +1 -0
  153. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -1,4489 +1,29 @@
1
- import {
2
- PI_BUILT_IN_TOOL_NAMES,
3
- TURN_COMPLETION_MODES,
4
- TURN_CONTEXT_MODES,
5
- collectProcessAvailableToolNames,
6
- resolveTurnActiveToolNames,
7
- resolveTurnAvailableToolNames,
8
- validatePiBuiltInToolArray
9
- } from "./chunk-ITPH65G6.js";
10
- import {
11
- buildPlanSavedEventPayload,
12
- buildReviewCompletedEventPayload,
13
- buildReviewRequestedEventPayload,
14
- filterStringArray
15
- } from "./chunk-LIIP7FMU.js";
16
- import {
17
- cloneArrayValueMap,
18
- cloneMap,
19
- getProcessTurnTransitions,
20
- markDefinedProcess,
21
- registerUnique,
22
- setProcessTurnTransitions
23
- } from "./chunk-5RJZ2E7D.js";
24
-
25
- // src/capabilities.ts
26
- function createCapabilityToken(id, options = {}) {
27
- return {
28
- id,
29
- cardinality: options.cardinality ?? "single"
30
- };
31
- }
32
-
33
- // src/codecs.ts
34
- var emptyParamsCodec = {
35
- parse() {
36
- return {};
37
- },
38
- serialize(value) {
39
- return value;
40
- }
41
- };
42
-
43
- // src/commit-message.ts
44
- var COMMIT_MESSAGE_PROJECT_METADATA_KEY = "leitwerk.commitMessage";
45
- var BUILT_IN_COMMIT_MESSAGE_RULES = "Write a concise imperative subject that summarizes the accepted plan. Add a body only when it provides useful context.";
46
-
47
- // src/core-capabilities.ts
48
- var coreHostCapabilities = {
49
- serverSetup: createCapabilityToken("core:serverSetup"),
50
- processModelSelection: createCapabilityToken(
51
- "core:processModelSelection"
52
- )
53
- };
54
-
55
- // src/define-process.ts
56
- import {
57
- assertValidProcessProductName
58
- } from "@leitwerk-dev/domain";
59
- function createTransitionTargetError(context, detail) {
60
- return new Error(`${context} ${detail}`);
61
- }
62
- function createProcessTurnBinding(definition, transitions) {
63
- const binding = { definition };
64
- if (transitions && transitions.length > 0) {
65
- setProcessTurnTransitions(binding, transitions);
66
- }
67
- return binding;
68
- }
69
- function normalizeStaticRouteTarget(context, target, knownTurnIds) {
70
- const declaredTargetCount = (target.to !== void 0 ? 1 : 0) + (target.complete === true ? 1 : 0) + (target.lifecycleStatus !== void 0 ? 1 : 0);
71
- if (declaredTargetCount !== 1) {
72
- throw createTransitionTargetError(
73
- context,
74
- "must declare exactly one target via 'to', 'complete', or 'lifecycleStatus'"
75
- );
76
- }
77
- if (target.to !== void 0) {
78
- if (knownTurnIds && !knownTurnIds.has(target.to)) {
79
- throw createTransitionTargetError(context, `references unknown turn '${target.to}'`);
80
- }
81
- return { nextTurnId: target.to };
82
- }
83
- if (target.complete === true) {
84
- return { lifecycleStatus: "completed" };
85
- }
86
- return { lifecycleStatus: target.lifecycleStatus };
87
- }
88
- function buildOutcomeTransition(turnId, outcome, target, knownTurnIds) {
89
- if (!hasDeclaredStaticRouteTarget(target)) {
90
- return { nextTurnId: turnId };
91
- }
92
- return normalizeStaticRouteTarget(`Turn '${turnId}' outcome '${outcome}'`, target, knownTurnIds);
93
- }
94
- function resolveActionRouting(input) {
95
- if ("branches" in input.spec) {
96
- const entries = Object.entries(input.spec.branches);
97
- if (entries.length === 0) {
98
- throw new Error(
99
- `Action '${input.actionId}' on turn '${input.turnId}' must declare at least one branch`
100
- );
101
- }
102
- const routes = {};
103
- const resolvedTransitions = [];
104
- const usedTriggers = /* @__PURE__ */ new Set();
105
- for (const [branchId, branchSpec] of entries) {
106
- if (branchId.trim() === "") {
107
- throw new Error(
108
- `Action '${input.actionId}' on turn '${input.turnId}' contains an empty branch id`
109
- );
110
- }
111
- const target2 = normalizeStaticRouteTarget(
112
- `Action '${input.actionId}' branch '${branchId}' on turn '${input.turnId}'`,
113
- branchSpec,
114
- input.knownTurnIds
115
- );
116
- const trigger = branchSpec.trigger ?? branchId;
117
- if (usedTriggers.has(trigger)) {
118
- throw new Error(
119
- `Action '${input.actionId}' on turn '${input.turnId}' contains duplicate branch trigger '${trigger}'`
120
- );
121
- }
122
- usedTriggers.add(trigger);
123
- const normalized = {
124
- ...target2.nextTurnId ? { nextTurnId: target2.nextTurnId } : {},
125
- ...target2.lifecycleStatus ? { lifecycleStatus: target2.lifecycleStatus } : {},
126
- trigger
127
- };
128
- routes[branchId] = normalized;
129
- resolvedTransitions.push(normalized);
130
- }
131
- return {
132
- routing: {
133
- kind: "branches",
134
- routes,
135
- choose: input.spec.choose
136
- },
137
- transitions: resolvedTransitions
138
- };
139
- }
140
- const target = normalizeStaticRouteTarget(
141
- `Action '${input.actionId}' on turn '${input.turnId}'`,
142
- input.spec,
143
- input.knownTurnIds
144
- );
145
- const route = {
146
- ...target.nextTurnId ? { nextTurnId: target.nextTurnId } : {},
147
- ...target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {},
148
- trigger: input.spec.trigger ?? input.actionId
149
- };
150
- return {
151
- routing: {
152
- kind: "static",
153
- route
154
- },
155
- transitions: [route]
156
- };
157
- }
158
- function externalSourceTransitionId(input) {
159
- return `${input.turnId}:${input.source.kind}:${input.index}`;
160
- }
161
- function externalActionArmingId(input) {
162
- return `${input.turnId}:${input.externalActionId}`;
163
- }
164
- function externalActionTransitionTrigger(input) {
165
- return `external:${input.externalActionId}`;
166
- }
167
- function compileExternalSourceTransitions(input) {
168
- if (input.spec.transitions.length === 0) {
169
- throw new Error(`External turn '${input.turnId}' must declare at least one source transition`);
170
- }
171
- return input.spec.transitions.map((transition, index) => {
172
- if (transition.source.kind.trim() === "") {
173
- throw new Error(
174
- `External turn '${input.turnId}' source transition ${index} has an empty kind`
175
- );
176
- }
177
- const target = normalizeStaticRouteTarget(
178
- `External turn '${input.turnId}' source '${transition.source.kind}'`,
179
- transition,
180
- input.knownTurnIds
181
- );
182
- return {
183
- ...target.nextTurnId ? { nextTurnId: target.nextTurnId } : {},
184
- ...target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {},
185
- trigger: externalSourceTransitionId({
186
- turnId: input.turnId,
187
- source: transition.source,
188
- index
189
- })
190
- };
191
- });
192
- }
193
- function getExternalSourceTransitionId(input) {
194
- return externalSourceTransitionId(input);
195
- }
196
- function getExternalActionArmingId(input) {
197
- return externalActionArmingId(input);
198
- }
199
- function getExternalActionTransitionTrigger(input) {
200
- return externalActionTransitionTrigger(input);
201
- }
202
- function previewMatchesTransition(preview, transition) {
203
- if (preview.kind === "trigger") {
204
- return transition.trigger === preview.trigger;
205
- }
206
- if (preview.kind === "terminal") {
207
- return transition.lifecycleStatus === preview.lifecycleStatus;
208
- }
209
- return transition.nextTurnId === preview.turnId;
210
- }
211
- function validateActionPreviewMatchesTransitions(input) {
212
- const matches = input.transitions.filter(
213
- (transition) => previewMatchesTransition(input.preview, transition)
214
- );
215
- if (matches.length === 1) {
216
- return;
217
- }
218
- const previewLabel = input.preview.kind === "trigger" ? `trigger '${input.preview.trigger}'` : input.preview.kind === "terminal" ? `terminal '${input.preview.lifecycleStatus}'` : `fixed turn '${String(input.preview.turnId)}'`;
219
- throw new Error(
220
- `Action '${input.actionId}' on turn '${input.turnId}' ${input.context} does not match a compiled transition for ${previewLabel}`
221
- );
222
- }
223
- function buildActionPreviewAndScheduling(turnId, actionId, spec, transitions) {
224
- const preview = (() => {
225
- if (spec.preview) {
226
- return spec.preview;
227
- }
228
- if (transitions.length !== 1) {
229
- return void 0;
230
- }
231
- const [transition] = transitions;
232
- if (!transition) {
233
- return void 0;
234
- }
235
- if (transition.lifecycleStatus !== void 0) {
236
- return {
237
- kind: "terminal",
238
- lifecycleStatus: transition.lifecycleStatus
239
- };
240
- }
241
- return {
242
- kind: "trigger",
243
- trigger: transition.trigger
244
- };
245
- })();
246
- if (spec.preview && preview) {
247
- validateActionPreviewMatchesTransitions({
248
- turnId,
249
- actionId,
250
- preview,
251
- transitions,
252
- context: "preview"
253
- });
254
- }
255
- if (spec.schedulable && preview) {
256
- validateActionPreviewMatchesTransitions({
257
- turnId,
258
- actionId,
259
- preview,
260
- transitions,
261
- context: "scheduling"
262
- });
263
- }
264
- if (spec.schedulable && !preview) {
265
- throw new Error(
266
- `Action '${actionId}' is schedulable but does not resolve to a unique preview transition`
267
- );
268
- }
269
- return {
270
- ...preview ? { preview } : {},
271
- ...spec.schedulable && preview ? { scheduling: { preview } } : {}
272
- };
273
- }
274
- function mergeProcessEffectPlans(left, right) {
275
- if (!left) {
276
- return right;
277
- }
278
- if (!right) {
279
- return left;
280
- }
281
- return {
282
- ...left,
283
- ...right,
284
- ...left.processPatch || right.processPatch ? { processPatch: { ...left.processPatch ?? {}, ...right.processPatch ?? {} } } : {},
285
- ...left.broadcasts || right.broadcasts ? { broadcasts: [...left.broadcasts ?? [], ...right.broadcasts ?? []] } : {},
286
- ...left.emit || right.emit ? { emit: [...left.emit ?? [], ...right.emit ?? []] } : {},
287
- ...left.queueInput || right.queueInput ? { queueInput: [...left.queueInput ?? [], ...right.queueInput ?? []] } : {}
288
- };
289
- }
290
- function normalizeEffectString(value) {
291
- return typeof value === "string" ? value.trim() : "";
292
- }
293
- function normalizeEffectStringArray(value) {
294
- return Array.isArray(value) ? value.map((entry) => typeof entry === "string" ? entry.trim() : "").filter((entry) => entry !== "") : [];
295
- }
296
- function getTurnReviewSubject(turnDef) {
297
- if (!turnDef || !("reviewSubject" in turnDef)) {
298
- return null;
299
- }
300
- return turnDef.reviewSubject ?? null;
301
- }
302
- function patchReviewSubjectIntoState(state, reviewSubject) {
303
- if (typeof state !== "object" || state === null || Array.isArray(state)) {
304
- return state;
305
- }
306
- return {
307
- ...state,
308
- reviewSubject
309
- };
310
- }
311
- async function buildSavePlanResultEffect(input) {
312
- const statePlan = input.intent.state ? await input.intent.state(input.execution) : void 0;
313
- const targetReviewSubject = getTurnReviewSubject(input.targetTurn);
314
- const baseState = statePlan?.state ?? input.execution.ctx.state;
315
- const planRevision = input.execution.ctx.process.planRevision + 1;
316
- const summary = normalizeEffectString(input.execution.event.params[input.intent.summaryParam]);
317
- const acceptanceCriteria = normalizeEffectStringArray(
318
- input.execution.event.params[input.intent.acceptanceCriteriaParam]
319
- );
320
- const planMarkdown = typeof input.execution.event.turnResultMarkdown === "string" ? input.execution.event.turnResultMarkdown : normalizeEffectString(input.execution.event.params[input.intent.planMarkdownParam]);
321
- return mergeProcessEffectPlans(statePlan, {
322
- state: patchReviewSubjectIntoState(baseState, targetReviewSubject),
323
- processPatch: { planRevision },
324
- broadcasts: [
325
- {
326
- type: input.intent.broadcastType,
327
- payload: {
328
- planRevision,
329
- reviewState: "awaiting_approval",
330
- approved: false,
331
- summary
332
- }
333
- }
334
- ],
335
- emit: [
336
- {
337
- type: input.intent.emitEventType,
338
- data: {
339
- planRevision,
340
- summary,
341
- planMarkdown,
342
- acceptanceCriteria
343
- }
344
- }
345
- ]
346
- });
347
- }
348
- function resolveOutcomeEffect(input) {
349
- const lifecycleIntent = "lifecycleIntent" in input.spec ? input.spec.lifecycleIntent : void 0;
350
- if (!lifecycleIntent) {
351
- return input.spec.effect;
352
- }
353
- return async (execution) => {
354
- const explicitPlan = input.spec.effect ? await input.spec.effect(execution) : void 0;
355
- let lifecyclePlan;
356
- switch (lifecycleIntent.kind) {
357
- case "save_plan_result":
358
- lifecyclePlan = await buildSavePlanResultEffect({
359
- intent: lifecycleIntent,
360
- execution,
361
- targetTurn: input.targetTurn
362
- });
363
- break;
364
- }
365
- return mergeProcessEffectPlans(explicitPlan, lifecyclePlan);
366
- };
367
- }
368
- function areFormsEquivalent(left, right) {
369
- if (left === right) {
370
- return true;
371
- }
372
- return JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
373
- }
374
- function cloneStateForFormPatch(state) {
375
- if (typeof state !== "object" || state === null) {
376
- throw new Error("Declarative form state fields require object process state");
377
- }
378
- return structuredClone(state);
379
- }
380
- function normalizeFormStateValue(field, value) {
381
- if (field.kind === "number") {
382
- const parsed = typeof value === "number" ? value : Number(String(value).trim());
383
- if (!Number.isFinite(parsed)) {
384
- throw new Error(`Field '${field.id}' must be a number`);
385
- }
386
- return parsed;
387
- }
388
- return value;
389
- }
390
- function applyFormStateFields(input) {
391
- const stateFields = (input.form?.fields ?? []).filter((field) => field.state);
392
- if (stateFields.length === 0) {
393
- return void 0;
394
- }
395
- const nextState = cloneStateForFormPatch(input.state);
396
- for (const field of stateFields) {
397
- const rawValue = input.inputValue[field.id];
398
- if (rawValue === void 0) {
399
- continue;
400
- }
401
- const path3 = field.state?.path.trim();
402
- if (!path3) {
403
- throw new Error(`Form field '${field.id}' declares an empty state path`);
404
- }
405
- const segments = path3.split(".").map((segment) => segment.trim());
406
- if (segments.some((segment) => segment === "")) {
407
- throw new Error(`Form field '${field.id}' declares invalid state path '${path3}'`);
408
- }
409
- let target = nextState;
410
- for (const segment of segments.slice(0, -1)) {
411
- const existing = target[segment];
412
- if (typeof existing !== "object" || existing === null || Array.isArray(existing)) {
413
- target[segment] = {};
414
- }
415
- target = target[segment];
416
- }
417
- target[segments[segments.length - 1]] = normalizeFormStateValue(field, rawValue);
418
- }
419
- return nextState;
420
- }
421
- function makeProcessServerRuntimeContext(ctx) {
422
- return {
423
- process: ctx.process,
424
- projects: ctx.projects,
425
- params: ctx.params,
426
- state: ctx.state,
427
- readSemanticTurnResultMarkdown: (ref) => ctx.readSemanticTurnResultMarkdown(ref),
428
- readProductTurnResultMarkdown: (productName) => ctx.readProductTurnResultMarkdown(productName)
429
- };
430
- }
431
- function mergeTransitionWithState(input) {
432
- const next = {
433
- ...input.transition ?? {},
434
- ...input.result?.state !== void 0 ? { state: input.result.state } : {}
435
- };
436
- const hasFields = next.turnId !== void 0 || next.lifecycleStatus !== void 0 || next.trigger !== void 0 || next.effect !== void 0 || next.state !== void 0;
437
- return hasFields ? next : null;
438
- }
439
- function hasLifecycleEffects(result) {
440
- return Boolean(
441
- result?.processPatch !== void 0 || result?.broadcasts !== void 0 && result.broadcasts.length > 0
442
- );
443
- }
444
- async function applyProcessEffectPlan(input) {
445
- const transition = mergeTransitionWithState({
446
- result: input.result,
447
- transition: input.transition
448
- });
449
- if (transition) {
450
- await input.ctx.transition(transition);
451
- }
452
- if (hasLifecycleEffects(input.result)) {
453
- if (!input.ctx.applyLifecycleEffects) {
454
- throw new Error("Process lifecycle effects are not supported by this server context");
455
- }
456
- input.ctx.applyLifecycleEffects({
457
- ...input.result.processPatch ? { processPatch: input.result.processPatch } : {},
458
- ...input.result.broadcasts ? { broadcasts: input.result.broadcasts } : {}
459
- });
460
- }
461
- for (const emitted of input.result?.emit ?? []) {
462
- input.ctx.emitEvent(emitted.type, emitted.data);
463
- }
464
- for (const queuedInput of input.result?.queueInput ?? []) {
465
- input.ctx.queueInput(queuedInput);
466
- }
467
- }
468
- function compileTurnOutcomeDefinitions(input) {
469
- const outcomeEntries = Object.entries(input.outcomes ?? {});
470
- if (outcomeEntries.length > 0 && input.turnEnd) {
471
- throw new Error(
472
- `Turn '${input.turnId}' cannot declare both tool outcomes and a turnEnd result`
473
- );
474
- }
475
- if (outcomeEntries.length === 0 && !input.turnEnd) {
476
- throw new Error(
477
- `Turn '${input.turnId}' must declare at least one tool outcome or a turnEnd result`
478
- );
479
- }
480
- const transitions = [];
481
- const effects = /* @__PURE__ */ new Map();
482
- for (const [outcome, spec] of outcomeEntries) {
483
- if (outcome.trim() === "") {
484
- throw new Error(`Turn '${input.turnId}' declares an empty outcome id`);
485
- }
486
- const target = buildOutcomeTransition(input.turnId, outcome, spec, input.knownTurnIds);
487
- transitions.push({
488
- ...target.nextTurnId ? { nextTurnId: target.nextTurnId } : {},
489
- ...target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {},
490
- outcome
491
- });
492
- effects.set(
493
- outcome,
494
- resolveOutcomeEffect({
495
- spec,
496
- targetTurn: target.nextTurnId ? input.turnDefinitionsById.get(target.nextTurnId) : void 0
497
- })
498
- );
499
- }
500
- if (input.turnEnd) {
501
- if (input.turnEnd.outcome.trim() === "") {
502
- throw new Error(`Turn '${input.turnId}' declares an empty turnEnd outcome id`);
503
- }
504
- const target = buildOutcomeTransition(
505
- input.turnId,
506
- input.turnEnd.outcome,
507
- input.turnEnd,
508
- input.knownTurnIds
509
- );
510
- transitions.push({
511
- ...target.nextTurnId ? { nextTurnId: target.nextTurnId } : {},
512
- ...target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {},
513
- outcome: input.turnEnd.outcome
514
- });
515
- effects.set(
516
- input.turnEnd.outcome,
517
- resolveOutcomeEffect({
518
- spec: input.turnEnd,
519
- targetTurn: target.nextTurnId ? input.turnDefinitionsById.get(target.nextTurnId) : void 0
520
- })
521
- );
522
- }
523
- return {
524
- transitions,
525
- effects
526
- };
527
- }
528
- function addActionUse(input) {
529
- const existing = input.actionUses.get(input.actionId) ?? [];
530
- if (existing.some((candidate) => candidate.turnId === input.use.turnId)) {
531
- throw new Error(
532
- `Turn '${input.use.turnId}' declares action '${input.actionId}' more than once`
533
- );
534
- }
535
- existing.push(input.use);
536
- input.actionUses.set(input.actionId, existing);
537
- }
538
- function hasDeclaredStaticRouteTarget(target) {
539
- return target.to !== void 0 || target.complete === true || target.lifecycleStatus !== void 0;
540
- }
541
- function resolveExternalActionRoute(input) {
542
- if (input.externalActionId.trim() === "") {
543
- throw new Error(`Human turn '${input.turnId}' declares an empty external action id`);
544
- }
545
- if (input.spec.id !== input.externalActionId) {
546
- throw new Error(
547
- `Human turn '${input.turnId}' external action '${input.externalActionId}' has mismatched spec id '${input.spec.id}'`
548
- );
549
- }
550
- if (input.spec.source.kind.trim() === "") {
551
- throw new Error(
552
- `Human turn '${input.turnId}' external action '${input.externalActionId}' must declare a non-empty source kind`
553
- );
554
- }
555
- const target = normalizeStaticRouteTarget(
556
- `Human turn '${input.turnId}' external action '${input.externalActionId}'`,
557
- input.spec,
558
- input.knownTurnIds
559
- );
560
- return {
561
- ...target.nextTurnId ? { nextTurnId: target.nextTurnId } : {},
562
- ...target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {},
563
- trigger: externalActionTransitionTrigger({ externalActionId: input.externalActionId })
564
- };
565
- }
566
- function validateExternalActionPublishedInputTarget(input) {
567
- const publication = input.spec.publishInput;
568
- if (!publication || !input.turnDefinitionsById) {
569
- return;
570
- }
571
- if (input.spec.to === void 0) {
572
- throw new Error(
573
- `Human turn '${input.turnId}' external action '${input.externalActionId}' publishes input '${publication.productName}' but does not route to a consuming turn`
574
- );
575
- }
576
- const targetTurn = input.turnDefinitionsById.get(input.spec.to);
577
- if (!targetTurn || targetTurn.kind !== "llm") {
578
- throw new Error(
579
- `Human turn '${input.turnId}' external action '${input.externalActionId}' publishes input '${publication.productName}' but target turn '${input.spec.to}' is not an LLM turn`
580
- );
581
- }
582
- const consumed = /* @__PURE__ */ new Set([
583
- ...targetTurn.consumedProducts ?? [],
584
- ...targetTurn.optionalConsumedProducts ?? []
585
- ]);
586
- if (!consumed.has(publication.productName)) {
587
- throw new Error(
588
- `Human turn '${input.turnId}' external action '${input.externalActionId}' publishes input '${publication.productName}' but target turn '${input.spec.to}' does not consume it`
589
- );
590
- }
591
- }
592
- function validateActionPrimaryPrompt(turnId, actionId, action) {
593
- const fields = action.form?.fields ?? [];
594
- const textualFields = fields.filter(
595
- (field) => field.kind === "text" || field.kind === "textarea"
596
- );
597
- const primaryPrompts = fields.filter((field) => field.primaryPrompt);
598
- if (primaryPrompts.some((field) => field.kind !== "text" && field.kind !== "textarea")) {
599
- throw new Error(
600
- `Human turn '${turnId}' action '${actionId}' primary prompt must be a text or textarea field`
601
- );
602
- }
603
- if (primaryPrompts.length > 1) {
604
- throw new Error(
605
- `Human turn '${turnId}' action '${actionId}' must declare at most one primary prompt`
606
- );
607
- }
608
- if (textualFields.length > 0 && primaryPrompts.length === 0) {
609
- throw new Error(
610
- `Human turn '${turnId}' action '${actionId}' with textual fields must declare a primary prompt`
611
- );
612
- }
613
- }
614
- function deriveHumanTurnActions(input) {
615
- const actionEntries = Object.entries(input.spec.actions);
616
- if (actionEntries.length === 0 && input.knownTurnIds) {
617
- throw new Error(`Human turn '${input.turnId}' must declare at least one action`);
618
- }
619
- const derivedActions = [];
620
- const transitions = [];
621
- const actionIdByTrigger = /* @__PURE__ */ new Map();
622
- for (const [actionId, actionSpec] of actionEntries) {
623
- if (actionId.trim() === "") {
624
- throw new Error(`Human turn '${input.turnId}' declares an empty action id`);
625
- }
626
- validateActionPrimaryPrompt(input.turnId, actionId, actionSpec);
627
- const resolved = !input.knownTurnIds && !("branches" in actionSpec) && !hasDeclaredStaticRouteTarget(actionSpec) ? {
628
- routing: {
629
- kind: "static",
630
- route: { trigger: actionSpec.trigger ?? actionId }
631
- },
632
- transitions: []
633
- } : resolveActionRouting({
634
- turnId: input.turnId,
635
- actionId,
636
- spec: actionSpec,
637
- knownTurnIds: input.knownTurnIds
638
- });
639
- for (const transition of resolved.transitions) {
640
- const existingActionId = actionIdByTrigger.get(transition.trigger);
641
- if (existingActionId && existingActionId !== actionId) {
642
- throw new Error(
643
- `Human turn '${input.turnId}' contains duplicate action trigger '${transition.trigger}' across actions '${existingActionId}' and '${actionId}'`
644
- );
645
- }
646
- actionIdByTrigger.set(transition.trigger, actionId);
647
- transitions.push({
648
- ...transition.nextTurnId ? { nextTurnId: transition.nextTurnId } : {},
649
- ...transition.lifecycleStatus ? { lifecycleStatus: transition.lifecycleStatus } : {},
650
- trigger: transition.trigger
651
- });
652
- }
653
- const previewAndScheduling = !input.knownTurnIds && resolved.transitions.length === 0 ? {
654
- ...actionSpec.preview ? { preview: actionSpec.preview } : {},
655
- ...actionSpec.schedulable && actionSpec.preview ? { scheduling: { preview: actionSpec.preview } } : {}
656
- } : buildActionPreviewAndScheduling(input.turnId, actionId, actionSpec, resolved.transitions);
657
- derivedActions.push({
658
- actionId,
659
- actionSpec,
660
- routing: resolved.routing,
661
- transitions: resolved.transitions,
662
- actionView: {
663
- actionId,
664
- label: actionSpec.label,
665
- description: actionSpec.description,
666
- acceptanceState: actionSpec.acceptanceState,
667
- ...previewAndScheduling
668
- },
669
- externalTriggers: actionSpec.externalTriggers?.map((trigger) => ({
670
- id: trigger.id,
671
- actionId,
672
- label: trigger.label,
673
- description: trigger.description
674
- })) ?? []
675
- });
676
- }
677
- const externalActionEntries = Object.entries(input.spec.externalActions ?? {});
678
- const derivedExternalActions = [];
679
- const externalActionIds = /* @__PURE__ */ new Set();
680
- for (const [externalActionId, actionSpec] of externalActionEntries) {
681
- if (externalActionIds.has(externalActionId)) {
682
- throw new Error(
683
- `Human turn '${input.turnId}' declares duplicate external action '${externalActionId}'`
684
- );
685
- }
686
- externalActionIds.add(externalActionId);
687
- if (actionSpec.publishInput) {
688
- assertValidProcessProductName(actionSpec.publishInput.productName);
689
- if (actionSpec.publishInput.inputField.trim() === "") {
690
- throw new Error(
691
- `Human turn '${input.turnId}' external action '${externalActionId}' publishInput must declare a non-empty inputField`
692
- );
693
- }
694
- }
695
- validateExternalActionPublishedInputTarget({
696
- turnId: input.turnId,
697
- externalActionId,
698
- spec: actionSpec,
699
- turnDefinitionsById: input.turnDefinitionsById
700
- });
701
- const transition = resolveExternalActionRoute({
702
- turnId: input.turnId,
703
- externalActionId,
704
- spec: actionSpec,
705
- knownTurnIds: input.knownTurnIds
706
- });
707
- const existingActionId = actionIdByTrigger.get(transition.trigger);
708
- if (existingActionId) {
709
- throw new Error(
710
- `Human turn '${input.turnId}' contains duplicate trigger '${transition.trigger}' across action '${existingActionId}' and external action '${externalActionId}'`
711
- );
712
- }
713
- actionIdByTrigger.set(transition.trigger, externalActionId);
714
- transitions.push({
715
- ...transition.nextTurnId ? { nextTurnId: transition.nextTurnId } : {},
716
- ...transition.lifecycleStatus ? { lifecycleStatus: transition.lifecycleStatus } : {},
717
- trigger: transition.trigger
718
- });
719
- derivedExternalActions.push({
720
- externalActionId,
721
- actionSpec,
722
- transition,
723
- view: {
724
- id: externalActionArmingId({ turnId: input.turnId, externalActionId }),
725
- externalActionId,
726
- sourceKind: actionSpec.source.kind,
727
- label: actionSpec.label ?? actionSpec.source.label ?? null,
728
- description: actionSpec.description ?? actionSpec.source.description ?? null
729
- }
730
- });
731
- }
732
- return {
733
- actions: derivedActions,
734
- externalActions: derivedExternalActions,
735
- transitions
736
- };
737
- }
738
- function resolveHumanTurnView(input) {
739
- const derived = deriveHumanTurnActions({
740
- turnId: input.turnId,
741
- spec: input.turn
742
- });
743
- return {
744
- actions: derived.actions.map((action) => action.actionView),
745
- externalTriggers: derived.actions.flatMap((action) => action.externalTriggers),
746
- externalActions: derived.externalActions.map((action) => action.view)
747
- };
748
- }
749
- function compileHumanTurn(input) {
750
- const derived = deriveHumanTurnActions({
751
- turnId: input.turnId,
752
- spec: input.spec,
753
- knownTurnIds: input.knownTurnIds,
754
- turnDefinitionsById: input.turnDefinitionsById
755
- });
756
- for (const action of derived.actions) {
757
- addActionUse({
758
- actionUses: input.actionUses,
759
- actionId: action.actionId,
760
- use: {
761
- turnId: input.turnId,
762
- label: action.actionSpec.label,
763
- ...action.actionSpec.form ? { form: action.actionSpec.form } : {},
764
- ...action.actionSpec.effect ? { effect: action.actionSpec.effect } : {},
765
- routing: action.routing
766
- }
767
- });
768
- }
769
- return {
770
- binding: createProcessTurnBinding(input.spec, derived.transitions)
771
- };
772
- }
773
- function compileExternalTurn(input) {
774
- const transitions = compileExternalSourceTransitions({
775
- turnId: input.turnId,
776
- spec: input.spec,
777
- knownTurnIds: input.knownTurnIds
778
- });
779
- return {
780
- binding: createProcessTurnBinding(input.spec, transitions)
781
- };
782
- }
783
- function getTurnEntries(turns) {
784
- return Object.entries(turns);
785
- }
786
- function resolveActionRouteForExecution(input) {
787
- if (input.use.routing.kind === "static") {
788
- return { route: input.use.routing.route };
789
- }
790
- const actionExecution = {
791
- ctx: makeProcessServerRuntimeContext(input.ctx),
792
- input: input.inputValue,
793
- turnId: input.use.turnId,
794
- actionId: input.actionId
795
- };
796
- const routes = input.use.routing.routes;
797
- return Promise.resolve(input.use.routing.choose(actionExecution)).then((selectedBranchId) => {
798
- if (!Object.hasOwn(routes, selectedBranchId)) {
799
- throw new Error(
800
- `Action '${input.actionId}' on turn '${input.use.turnId}' selected unknown branch '${selectedBranchId}'`
801
- );
802
- }
803
- const route = routes[selectedBranchId];
804
- if (!route) {
805
- throw new Error(
806
- `Action '${input.actionId}' on turn '${input.use.turnId}' selected unknown branch '${selectedBranchId}'`
807
- );
808
- }
809
- return { route, selectedBranchId };
810
- });
811
- }
812
- function buildActionTransitionRequest(route) {
813
- if (route.nextTurnId !== void 0) {
814
- return {
815
- turnId: route.nextTurnId,
816
- trigger: route.trigger
817
- };
818
- }
819
- return {
820
- turnId: null,
821
- lifecycleStatus: route.lifecycleStatus,
822
- trigger: route.trigger
823
- };
824
- }
825
- function validateHappyPathConnectivity(input) {
826
- const happyPath = input.happyPath;
827
- if (!happyPath || happyPath.length < 2) {
828
- return;
829
- }
830
- const happyPathTurns = new Set(happyPath);
831
- for (let index = 0; index < happyPath.length - 1; index += 1) {
832
- const source = happyPath[index];
833
- const target = happyPath[index + 1];
834
- let connected = false;
835
- const visited = /* @__PURE__ */ new Set([source]);
836
- const queue = [source];
837
- while (queue.length > 0 && !connected) {
838
- const current = queue.shift();
839
- for (const transition of getProcessTurnTransitions(input.turns.get(current))) {
840
- const next = transition.nextTurnId;
841
- if (next === void 0 || !input.turnDefinitionsById.has(next)) {
842
- continue;
843
- }
844
- if (next === target) {
845
- connected = true;
846
- break;
847
- }
848
- if (visited.has(next) || happyPathTurns.has(next)) {
849
- continue;
850
- }
851
- const definition = input.turnDefinitionsById.get(next);
852
- if (definition?.kind !== "human") {
853
- continue;
854
- }
855
- visited.add(next);
856
- queue.push(next);
857
- }
858
- }
859
- if (!connected) {
860
- throw new Error(
861
- `Process '${input.processId}' happy path segment '${source}' -> '${target}' is not connected by declared transitions`
862
- );
863
- }
864
- }
865
- }
866
- function buildDefinedProcess(input) {
867
- const turnEntries = getTurnEntries(input.turns);
868
- if (turnEntries.length === 0) {
869
- throw new Error(`Process '${input.id}' must declare at least one turn`);
870
- }
871
- const knownTurnIds = new Set(turnEntries.map(([turnId]) => turnId));
872
- const turnDefinitionsById = new Map(
873
- turnEntries.map(([turnId, turnSpec]) => [turnId, turnSpec])
874
- );
875
- if (!knownTurnIds.has(input.entry)) {
876
- throw new Error(`Process '${input.id}' entry turn '${input.entry}' is not declared`);
877
- }
878
- const seenEntries = /* @__PURE__ */ new Set();
879
- for (const turnId of [input.entry, ...input.alternateEntries ?? []]) {
880
- if (seenEntries.has(turnId)) {
881
- throw new Error(`Process '${input.id}' declares duplicate entry turn '${turnId}'`);
882
- }
883
- if (!knownTurnIds.has(turnId)) {
884
- throw new Error(`Process '${input.id}' entry turn '${turnId}' is not declared`);
885
- }
886
- seenEntries.add(turnId);
887
- }
888
- if (input.happyPath) {
889
- if (input.happyPath.length === 0) {
890
- throw new Error(`Process '${input.id}' declares an empty happy path`);
891
- }
892
- const seen = /* @__PURE__ */ new Set();
893
- for (const turnId of input.happyPath) {
894
- if (!knownTurnIds.has(turnId)) {
895
- throw new Error(`Process '${input.id}' happy path references undeclared turn '${turnId}'`);
896
- }
897
- if (seen.has(turnId)) {
898
- throw new Error(`Process '${input.id}' happy path repeats turn '${turnId}'`);
899
- }
900
- seen.add(turnId);
901
- }
902
- if (input.happyPath[0] !== input.entry) {
903
- throw new Error(
904
- `Process '${input.id}' happy path must start at the entry turn '${input.entry}'`
905
- );
906
- }
907
- }
908
- const turns = /* @__PURE__ */ new Map();
909
- const actionUses = /* @__PURE__ */ new Map();
910
- const outcomeEffects = /* @__PURE__ */ new Map();
911
- const executableTurns = /* @__PURE__ */ new Map();
912
- for (const [turnId, turnSpec] of turnEntries) {
913
- if (turnSpec.kind === "llm") {
914
- const compiledOutcomes = compileTurnOutcomeDefinitions({
915
- turnId,
916
- outcomes: turnSpec.outcomes,
917
- turnEnd: turnSpec.turnEnd,
918
- knownTurnIds,
919
- turnDefinitionsById
920
- });
921
- turns.set(turnId, createProcessTurnBinding(turnSpec, compiledOutcomes.transitions));
922
- outcomeEffects.set(turnId, compiledOutcomes.effects);
923
- executableTurns.set(turnId, {
924
- kind: "llm",
925
- id: turnId,
926
- spec: turnSpec
927
- });
928
- continue;
929
- }
930
- if (turnSpec.kind === "automatic" || turnSpec.kind === "server_automatic") {
931
- const compiledOutcomes = compileTurnOutcomeDefinitions({
932
- turnId,
933
- outcomes: turnSpec.outcomes,
934
- turnEnd: turnSpec.turnEnd,
935
- knownTurnIds,
936
- turnDefinitionsById
937
- });
938
- turns.set(turnId, createProcessTurnBinding(turnSpec, compiledOutcomes.transitions));
939
- outcomeEffects.set(turnId, compiledOutcomes.effects);
940
- if (turnSpec.kind === "automatic") {
941
- executableTurns.set(turnId, {
942
- kind: "automatic",
943
- id: turnId,
944
- spec: turnSpec
945
- });
946
- }
947
- continue;
948
- }
949
- if (turnSpec.kind === "human") {
950
- const compiled2 = compileHumanTurn({
951
- turnId,
952
- spec: turnSpec,
953
- knownTurnIds,
954
- turnDefinitionsById,
955
- actionUses
956
- });
957
- turns.set(turnId, compiled2.binding);
958
- continue;
959
- }
960
- const compiled = compileExternalTurn({
961
- turnId,
962
- spec: turnSpec,
963
- knownTurnIds
964
- });
965
- turns.set(turnId, compiled.binding);
966
- }
967
- validateHappyPathConnectivity({
968
- processId: input.id,
969
- happyPath: input.happyPath,
970
- turns,
971
- turnDefinitionsById
972
- });
973
- const worker = (api) => {
974
- api.start(input.entry);
975
- const manuallyRegisteredTurns = /* @__PURE__ */ new Set();
976
- input.worker?.({
977
- start(turnId) {
978
- api.start(turnId);
979
- },
980
- turn(turnId, handler) {
981
- manuallyRegisteredTurns.add(turnId);
982
- api.turn(turnId, handler);
983
- }
984
- });
985
- for (const executable of executableTurns.values()) {
986
- if (manuallyRegisteredTurns.has(executable.id)) {
987
- continue;
988
- }
989
- if (executable.kind === "llm") {
990
- api.turn(executable.id, async (run) => {
991
- await run.turn(executable.spec);
992
- });
993
- continue;
994
- }
995
- api.turn(executable.id, async (run) => {
996
- await run.complete(await executable.spec.run(run.ctx));
997
- });
998
- }
999
- };
1000
- const server = (api) => {
1001
- for (const [actionId, uses] of actionUses) {
1002
- const [firstUse] = uses;
1003
- const form = firstUse?.form;
1004
- for (const use of uses) {
1005
- if (!areFormsEquivalent(form, use.form)) {
1006
- throw new Error(
1007
- `Action '${actionId}' must use the same form on every turn that references it`
1008
- );
1009
- }
1010
- }
1011
- api.action({
1012
- id: actionId,
1013
- label: firstUse?.label ?? actionId,
1014
- ...form ? { form } : {},
1015
- async plan(inputValue, ctx) {
1016
- const turnId = ctx.process.selectedTurnId;
1017
- const use = uses.find((candidate) => candidate.turnId === turnId);
1018
- if (!use || !turnId) {
1019
- throw new Error(
1020
- `Action '${actionId}' is not available for selected turn '${String(turnId)}'`
1021
- );
1022
- }
1023
- const resolvedRoute = await resolveActionRouteForExecution({
1024
- use,
1025
- actionId,
1026
- ctx,
1027
- inputValue
1028
- });
1029
- const effectResult = use.effect ? await use.effect({
1030
- ctx: makeProcessServerRuntimeContext(ctx),
1031
- input: inputValue,
1032
- turnId,
1033
- actionId,
1034
- ...resolvedRoute.selectedBranchId ? { selectedBranchId: resolvedRoute.selectedBranchId } : {}
1035
- }) : void 0;
1036
- const formState = applyFormStateFields({
1037
- form: use.form,
1038
- inputValue,
1039
- state: effectResult?.state ?? ctx.state
1040
- });
1041
- const result = formState ? mergeProcessEffectPlans(effectResult, { state: formState }) : effectResult;
1042
- await applyProcessEffectPlan({
1043
- ctx,
1044
- result,
1045
- transition: buildActionTransitionRequest(resolvedRoute.route)
1046
- });
1047
- }
1048
- });
1049
- }
1050
- for (const [turnId, effects] of outcomeEffects) {
1051
- api.onTurnOutcome(turnId, async (event, ctx) => {
1052
- const effect = effects.get(event.outcome);
1053
- if (!effect) {
1054
- return;
1055
- }
1056
- const result = await effect({
1057
- ctx: makeProcessServerRuntimeContext(ctx),
1058
- event,
1059
- turnId,
1060
- outcome: event.outcome
1061
- });
1062
- await applyProcessEffectPlan({ ctx, result });
1063
- });
1064
- }
1065
- input.server?.(api);
1066
- };
1067
- return {
1068
- turns,
1069
- worker,
1070
- server
1071
- };
1072
- }
1073
- function defineProcess(input) {
1074
- const compiled = buildDefinedProcess(input);
1075
- const process2 = {
1076
- id: input.id,
1077
- displayName: input.displayName,
1078
- entryTurnId: input.entry,
1079
- alternateEntryTurnIds: [...input.alternateEntries ?? []],
1080
- ...input.happyPath ? { happyPath: [...input.happyPath] } : {},
1081
- turns: compiled.turns,
1082
- paramsCodec: input.paramsCodec,
1083
- stateCodec: input.stateCodec,
1084
- initialState: input.initialState,
1085
- ...input.repositoryCredentials ? { repositoryCredentials: input.repositoryCredentials } : {},
1086
- ...input.piConfig ? { piConfig: input.piConfig } : {},
1087
- server: compiled.server,
1088
- worker: compiled.worker,
1089
- ui: input.ui,
1090
- launchers: input.launchers,
1091
- watchers: input.watchers
1092
- };
1093
- markDefinedProcess(process2);
1094
- return process2;
1095
- }
1096
- function routeTurnOutcomes(baseTurn, routes, options = {}) {
1097
- const baseOutcomes = baseTurn.outcomes ?? {};
1098
- for (const outcomeId of Object.keys(routes)) {
1099
- if (!baseOutcomes[outcomeId]) {
1100
- throw new Error(`Cannot route unknown outcome '${outcomeId}' on reusable turn`);
1101
- }
1102
- }
1103
- if (options.strict) {
1104
- for (const outcomeId of Object.keys(baseOutcomes)) {
1105
- if (!routes[outcomeId]) {
1106
- throw new Error(`Strict routing omitted outcome '${outcomeId}' on reusable turn`);
1107
- }
1108
- }
1109
- }
1110
- return {
1111
- ...baseTurn,
1112
- outcomes: Object.fromEntries(
1113
- Object.entries(baseOutcomes).map(([outcomeId, baseOutcome]) => [
1114
- outcomeId,
1115
- { ...baseOutcome, ...routes[outcomeId] ?? {} }
1116
- ])
1117
- )
1118
- };
1119
- }
1120
- function llmTurn(input) {
1121
- return {
1122
- ...input,
1123
- kind: "llm"
1124
- };
1125
- }
1126
- function automaticTurn(input) {
1127
- return {
1128
- ...input,
1129
- kind: "automatic"
1130
- };
1131
- }
1132
- function serverAutomaticTurn(input) {
1133
- return {
1134
- ...input,
1135
- kind: "server_automatic"
1136
- };
1137
- }
1138
- function humanTurn(input) {
1139
- return {
1140
- ...input,
1141
- kind: "human"
1142
- };
1143
- }
1144
- function externalTurn(input) {
1145
- return {
1146
- ...input,
1147
- kind: "external"
1148
- };
1149
- }
1150
-
1151
- // src/event-bus.ts
1152
- function createEventBus() {
1153
- const listeners = /* @__PURE__ */ new Map();
1154
- return {
1155
- emit(event, data) {
1156
- const handlers = listeners.get(event);
1157
- if (!handlers) return;
1158
- for (const handler of handlers) {
1159
- try {
1160
- void handler(data);
1161
- } catch {
1162
- }
1163
- }
1164
- },
1165
- on(event, handler) {
1166
- const typedHandler = handler;
1167
- let set = listeners.get(event);
1168
- if (!set) {
1169
- set = /* @__PURE__ */ new Set();
1170
- listeners.set(event, set);
1171
- }
1172
- set.add(typedHandler);
1173
- },
1174
- off(event, handler) {
1175
- listeners.get(event)?.delete(handler);
1176
- }
1177
- };
1178
- }
1179
-
1180
- // src/extension-api.ts
1181
- function findUiLauncherById(launcherService, launcherId) {
1182
- return launcherService.listUiLaunchers().find((launcher) => launcher.id === launcherId) ?? null;
1183
- }
1184
-
1185
- // src/flow.ts
1186
- import path from "path";
1187
- import {
1188
- assertValidProcessProductName as assertValidProcessProductName2,
1189
- createReviewSubject,
1190
- humanizeProcessLabel
1191
- } from "@leitwerk-dev/domain";
1192
- var DEFAULT_PLAN_RESULT_OUTCOME_ID = "plan_saved";
1193
- var DEFAULT_FLOW_PRODUCT_NAME = "default";
1194
- var ASSISTANT_OUTPUT_TURN_RESULT = { mode: "assistant_output", required: true };
1195
- var OUTCOME_TOOL_MARKDOWN_PARAMETER_NAME = "markdown";
1196
- var OUTCOME_TOOL_ARGUMENT_TURN_RESULT = {
1197
- mode: "outcome_tool_argument",
1198
- parameterName: OUTCOME_TOOL_MARKDOWN_PARAMETER_NAME,
1199
- required: true
1200
- };
1201
- function textField(input) {
1202
- return {
1203
- type: "string",
1204
- description: input.description,
1205
- required: true,
1206
- requiredErrorCode: input.requiredErrorCode
1207
- };
1208
- }
1209
- function stringArrayField(input) {
1210
- return {
1211
- type: "array",
1212
- description: input.description,
1213
- items: { type: "string" },
1214
- required: true,
1215
- requiredErrorCode: input.requiredErrorCode,
1216
- minItems: input.minItems,
1217
- minItemsErrorCode: input.minItemsErrorCode
1218
- };
1219
- }
1220
- function normalizeProductName(productName) {
1221
- assertValidProcessProductName2(productName);
1222
- return productName;
1223
- }
1224
- function toRequiredErrorCode(name) {
1225
- const snake = name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "").toLowerCase();
1226
- return `${snake || "value"}_required`;
1227
- }
1228
- function readInitialPrompt(params) {
1229
- if (typeof params === "object" && params !== null && "prompt" in params) {
1230
- const value = params.prompt;
1231
- if (typeof value === "string") {
1232
- return value;
1233
- }
1234
- }
1235
- return "";
1236
- }
1237
- function isPathInside(parent, child) {
1238
- const relative = path.relative(parent, child);
1239
- return relative !== "" && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
1240
- }
1241
- function safeJoinInside(parent, childPath, context) {
1242
- const parentPath = path.resolve(parent);
1243
- const targetPath = path.resolve(parentPath, childPath);
1244
- if (!isPathInside(parentPath, targetPath)) {
1245
- throw new Error(`${context} resolves outside '${parentPath}'`);
1246
- }
1247
- return targetPath;
1248
- }
1249
- function toWorkspaceClonePath(relativePath) {
1250
- return `./${relativePath.split(path.sep).join("/")}`;
1251
- }
1252
- function resolveSafeProjectWorkspacePath(key) {
1253
- if (path.isAbsolute(key)) {
1254
- throw new Error(`Flow context project key '${key}' must be a relative workspace path`);
1255
- }
1256
- const virtualWorkspaceRoot = path.resolve(path.sep, "__leitwerk_process_workspace__");
1257
- const virtualTarget = safeJoinInside(
1258
- virtualWorkspaceRoot,
1259
- key,
1260
- `Flow context project key '${key}'`
1261
- );
1262
- const relativePath = path.relative(virtualWorkspaceRoot, virtualTarget);
1263
- return {
1264
- relativePath,
1265
- workspaceClonePath: toWorkspaceClonePath(relativePath)
1266
- };
1267
- }
1268
- function resolveRepoByKey(input) {
1269
- const requestedKey = input.key.trim();
1270
- if (!requestedKey) {
1271
- throw new Error("Flow repo lookup requires a non-empty project key");
1272
- }
1273
- const matches = input.projects.filter((project2) => project2.key.trim() === requestedKey);
1274
- if (matches.length === 0) {
1275
- if (!input.required) {
1276
- return void 0;
1277
- }
1278
- const availableKeys = input.projects.map((project2) => project2.key.trim()).filter((key2) => key2 !== "").join(", ");
1279
- throw new Error(
1280
- `Flow context requires project '${requestedKey}', but this process has no project with that key${availableKeys ? ` (available: ${availableKeys})` : ""}`
1281
- );
1282
- }
1283
- if (matches.length > 1) {
1284
- throw new Error(`Flow context found duplicate project key '${requestedKey}'`);
1285
- }
1286
- const project = matches[0];
1287
- const key = project.key.trim();
1288
- if (!key) {
1289
- throw new Error("Flow context requires projects to have non-empty keys");
1290
- }
1291
- const baseBranch = project.baseBranch.trim();
1292
- if (!baseBranch) {
1293
- throw new Error(`Flow context project '${key}' has no base branch`);
1294
- }
1295
- const workBranch = (project.workBranch ?? project.baseBranch).trim();
1296
- if (!workBranch) {
1297
- throw new Error(`Flow context project '${key}' has no work branch`);
1298
- }
1299
- const workspacePath = resolveSafeProjectWorkspacePath(key);
1300
- return {
1301
- key,
1302
- workspaceClonePath: workspacePath.workspaceClonePath,
1303
- fsPath: typeof input.workspaceRoot === "string" && input.workspaceRoot.trim() !== "" ? safeJoinInside(
1304
- input.workspaceRoot,
1305
- workspacePath.relativePath,
1306
- `Flow context project '${key}' workspace path`
1307
- ) : workspacePath.workspaceClonePath,
1308
- baseBranch,
1309
- workBranch,
1310
- locator: project.repoLocator
1311
- };
1312
- }
1313
- function createFlowRepoLookup(input) {
1314
- return {
1315
- get: (key) => resolveRepoByKey({
1316
- projects: input.projects,
1317
- workspaceRoot: input.workspaceRoot,
1318
- key,
1319
- required: true
1320
- }),
1321
- optional: (key) => resolveRepoByKey({
1322
- projects: input.projects,
1323
- workspaceRoot: input.workspaceRoot,
1324
- key,
1325
- required: false
1326
- }),
1327
- all: () => input.projects.map(
1328
- (project) => resolveRepoByKey({
1329
- projects: input.projects,
1330
- workspaceRoot: input.workspaceRoot,
1331
- key: project.key,
1332
- required: true
1333
- })
1334
- )
1335
- };
1336
- }
1337
- function createFlowPromptContext(ctx, consumedProducts, optionalConsumedProducts = []) {
1338
- const productInput = {};
1339
- for (const productName of consumedProducts) {
1340
- const markdown = ctx.turnResultMarkdownByProduct?.[productName];
1341
- if (typeof markdown !== "string" || markdown.trim() === "") {
1342
- throw new Error(
1343
- `Flow prompt context requires product '${productName}' markdown, but the worker payload did not provide it`
1344
- );
1345
- }
1346
- productInput[productName] = markdown;
1347
- }
1348
- for (const productName of optionalConsumedProducts) {
1349
- if (productName in productInput) {
1350
- continue;
1351
- }
1352
- const markdown = ctx.turnResultMarkdownByProduct?.[productName];
1353
- if (typeof markdown === "string" && markdown.trim() !== "") {
1354
- productInput[productName] = markdown;
1355
- }
1356
- }
1357
- return {
1358
- process: ctx.process,
1359
- projects: ctx.projects,
1360
- params: ctx.params,
1361
- state: ctx.state,
1362
- ...ctx.workspaceRoot ? { workspaceRoot: ctx.workspaceRoot } : {},
1363
- prompts: {
1364
- initial: readInitialPrompt(ctx.params)
1365
- },
1366
- input: productInput,
1367
- repo: createFlowRepoLookup({
1368
- projects: ctx.projects,
1369
- workspaceRoot: ctx.workspaceRoot
1370
- })
1371
- };
1372
- }
1373
- function createFlowAutomaticRunContext(ctx) {
1374
- return {
1375
- process: ctx.process,
1376
- projects: ctx.projects,
1377
- params: ctx.params,
1378
- state: ctx.state,
1379
- ...ctx.workspaceRoot ? { workspaceRoot: ctx.workspaceRoot } : {},
1380
- repo: createFlowRepoLookup({
1381
- projects: ctx.projects,
1382
- workspaceRoot: ctx.workspaceRoot
1383
- })
1384
- };
1385
- }
1386
- function createFlowLlmOutcomeEffectContext(input) {
1387
- return {
1388
- process: input.ctx.process,
1389
- projects: input.ctx.projects,
1390
- params: input.ctx.params,
1391
- state: input.ctx.state,
1392
- output: typeof input.event.turnResultMarkdown === "string" ? { content: input.event.turnResultMarkdown } : null
1393
- };
1394
- }
1395
- function createFlowAutomaticOutcomeEffectContext(input) {
1396
- return {
1397
- process: input.ctx.process,
1398
- projects: input.ctx.projects,
1399
- params: input.ctx.params,
1400
- state: input.ctx.state,
1401
- output: typeof input.event.turnResultMarkdown === "string" ? { content: input.event.turnResultMarkdown } : null
1402
- };
1403
- }
1404
- function wrapLlmOutcomeEffect(effect) {
1405
- return (execution) => effect({
1406
- ctx: createFlowLlmOutcomeEffectContext({ ctx: execution.ctx, event: execution.event }),
1407
- event: execution.event,
1408
- turnId: execution.turnId,
1409
- outcome: execution.outcome
1410
- });
1411
- }
1412
- function wrapAutomaticOutcomeEffect(effect) {
1413
- return (execution) => effect({
1414
- ctx: createFlowAutomaticOutcomeEffectContext({ ctx: execution.ctx, event: execution.event }),
1415
- event: execution.event,
1416
- turnId: execution.turnId,
1417
- outcome: execution.outcome
1418
- });
1419
- }
1420
- var RouteAndEffectBuilder = class {
1421
- target = null;
1422
- flowEffect;
1423
- setTarget(next) {
1424
- if (this.target && next) {
1425
- throw new Error("Flow route already declares a target");
1426
- }
1427
- this.target = next;
1428
- return this;
1429
- }
1430
- to(turnId) {
1431
- return this.setTarget({ kind: "to", turnId });
1432
- }
1433
- complete() {
1434
- return this.setTarget({ kind: "complete" });
1435
- }
1436
- lifecycleStatus(status) {
1437
- return this.setTarget({ kind: "lifecycleStatus", status });
1438
- }
1439
- stay() {
1440
- this.target = null;
1441
- return this;
1442
- }
1443
- state(fn) {
1444
- this.flowEffect = async (input) => ({ state: await fn(input) });
1445
- return this;
1446
- }
1447
- effect(fn) {
1448
- this.flowEffect = fn;
1449
- return this;
1450
- }
1451
- hasRoute() {
1452
- return this.target !== null;
1453
- }
1454
- buildRouteTarget() {
1455
- return buildRouteTargetSpec(this.target);
1456
- }
1457
- };
1458
- function buildRouteTargetSpec(target) {
1459
- if (!target) {
1460
- return {};
1461
- }
1462
- if (target.kind === "to") {
1463
- return { to: target.turnId };
1464
- }
1465
- if (target.kind === "complete") {
1466
- return { complete: true };
1467
- }
1468
- return { lifecycleStatus: target.status };
1469
- }
1470
- function isStringArray(value) {
1471
- return Array.isArray(value) && value.every((entry) => typeof entry === "string");
1472
- }
1473
- var ParameterizedOutcomeBuilder = class extends RouteAndEffectBuilder {
1474
- outcomeDescription = null;
1475
- parameters = {};
1476
- publishedMarkdownParameter = null;
1477
- description(text) {
1478
- this.outcomeDescription = text;
1479
- return this;
1480
- }
1481
- parameter(name, spec) {
1482
- if (name.trim() === "") {
1483
- throw new Error("Outcome parameter name must be non-empty");
1484
- }
1485
- this.parameters[name] = {
1486
- ...spec,
1487
- description: spec.description ?? ""
1488
- };
1489
- return this;
1490
- }
1491
- withRequired(name, options) {
1492
- const resolved = typeof options === "string" ? { description: options } : options;
1493
- return {
1494
- ...resolved,
1495
- required: true,
1496
- requiredErrorCode: resolved.requiredErrorCode ?? toRequiredErrorCode(name)
1497
- };
1498
- }
1499
- string(name, options = {}) {
1500
- const resolved = typeof options === "string" ? { description: options } : options;
1501
- return this.parameter(name, {
1502
- ...resolved,
1503
- type: "string",
1504
- description: resolved.description ?? ""
1505
- });
1506
- }
1507
- markdown(name, options = {}) {
1508
- const resolved = typeof options === "string" ? { description: options } : options;
1509
- const { publish, ...parameterOptions } = resolved;
1510
- if (publish) {
1511
- if (this.publishedMarkdownParameter && this.publishedMarkdownParameter !== name) {
1512
- throw new Error("Outcome can publish only one markdown parameter");
1513
- }
1514
- normalizeProductName(name);
1515
- this.publishedMarkdownParameter = name;
1516
- }
1517
- return this.parameter(name, {
1518
- ...parameterOptions,
1519
- required: publish ? true : resolved.required,
1520
- requiredErrorCode: resolved.requiredErrorCode ?? (publish ? `${name}_required` : void 0),
1521
- type: "string",
1522
- description: resolved.description ?? ""
1523
- });
1524
- }
1525
- requiredString(name, options = {}) {
1526
- const resolved = this.withRequired(name, options);
1527
- return this.parameter(name, {
1528
- ...resolved,
1529
- type: "string",
1530
- description: resolved.description ?? ""
1531
- });
1532
- }
1533
- number(name, options = {}) {
1534
- const resolved = typeof options === "string" ? { description: options } : options;
1535
- return this.parameter(name, {
1536
- ...resolved,
1537
- type: "number",
1538
- description: resolved.description ?? ""
1539
- });
1540
- }
1541
- requiredNumber(name, options = {}) {
1542
- const resolved = this.withRequired(name, options);
1543
- return this.parameter(name, {
1544
- ...resolved,
1545
- type: "number",
1546
- description: resolved.description ?? ""
1547
- });
1548
- }
1549
- boolean(name, options = {}) {
1550
- const resolved = typeof options === "string" ? { description: options } : options;
1551
- return this.parameter(name, {
1552
- ...resolved,
1553
- type: "boolean",
1554
- description: resolved.description ?? ""
1555
- });
1556
- }
1557
- requiredBoolean(name, options = {}) {
1558
- const resolved = this.withRequired(name, options);
1559
- return this.parameter(name, {
1560
- ...resolved,
1561
- type: "boolean",
1562
- description: resolved.description ?? ""
1563
- });
1564
- }
1565
- stringArray(name, options = {}) {
1566
- const resolved = typeof options === "string" ? { description: options } : options;
1567
- return this.parameter(name, {
1568
- ...resolved,
1569
- type: "array",
1570
- description: resolved.description ?? "",
1571
- items: resolved.items ?? { type: "string" }
1572
- });
1573
- }
1574
- requiredStringArray(name, options = {}) {
1575
- const resolved = this.withRequired(name, options);
1576
- return this.parameter(name, {
1577
- ...resolved,
1578
- type: "array",
1579
- description: resolved.description ?? "",
1580
- items: resolved.items ?? { type: "string" }
1581
- });
1582
- }
1583
- enum(name, valuesOrOptions) {
1584
- const resolved = isStringArray(valuesOrOptions) ? { values: [...valuesOrOptions] } : valuesOrOptions;
1585
- const { values = [], ...options } = resolved;
1586
- return this.parameter(name, {
1587
- ...options,
1588
- type: "string",
1589
- description: options.description ?? "",
1590
- enum: [...values]
1591
- });
1592
- }
1593
- object(name, options = {}) {
1594
- const resolved = typeof options === "string" ? { description: options } : options;
1595
- return this.parameter(name, {
1596
- ...resolved,
1597
- type: "object",
1598
- description: resolved.description ?? ""
1599
- });
1600
- }
1601
- array(name, options = {}) {
1602
- const resolved = typeof options === "string" ? { description: options } : options;
1603
- return this.parameter(name, {
1604
- ...resolved,
1605
- type: "array",
1606
- description: resolved.description ?? "",
1607
- items: resolved.items ?? { type: "string" }
1608
- });
1609
- }
1610
- };
1611
- var OutcomeToolBuilder = class extends ParameterizedOutcomeBuilder {
1612
- build() {
1613
- if (!this.outcomeDescription) {
1614
- throw new Error("LLM outcome tool must declare .description(...)");
1615
- }
1616
- return {
1617
- description: this.outcomeDescription,
1618
- parameters: this.parameters,
1619
- ...this.publishedMarkdownParameter ? {
1620
- publishedProduct: this.publishedMarkdownParameter,
1621
- turnResultMarkdownParameter: this.publishedMarkdownParameter
1622
- } : {},
1623
- ...this.buildRouteTarget(),
1624
- ...this.flowEffect ? { effect: wrapLlmOutcomeEffect(this.flowEffect) } : {}
1625
- };
1626
- }
1627
- };
1628
- var AutomaticOutcomeBuilder = class extends ParameterizedOutcomeBuilder {
1629
- build() {
1630
- if (!this.outcomeDescription) {
1631
- throw new Error("Automatic outcome must declare .description(...)");
1632
- }
1633
- return {
1634
- description: this.outcomeDescription,
1635
- parameters: this.parameters,
1636
- ...this.publishedMarkdownParameter ? {
1637
- publishedProduct: this.publishedMarkdownParameter,
1638
- turnResultMarkdownParameter: this.publishedMarkdownParameter
1639
- } : {},
1640
- ...this.buildRouteTarget(),
1641
- ...this.flowEffect ? { effect: wrapAutomaticOutcomeEffect(this.flowEffect) } : {}
1642
- };
1643
- }
1644
- };
1645
- var PlanResultBuilder = class extends RouteAndEffectBuilder {
1646
- resultDescription = "The candidate plan is ready for operator review";
1647
- summarySpec = null;
1648
- acceptanceCriteriaSpec = null;
1649
- reviewTurnId = null;
1650
- description(text) {
1651
- this.resultDescription = text;
1652
- return this;
1653
- }
1654
- summary(options = {}) {
1655
- const resolved = typeof options === "string" ? { description: options } : options;
1656
- this.summarySpec = textField({
1657
- description: resolved.description ?? "Short summary of the proposed plan",
1658
- requiredErrorCode: resolved.requiredErrorCode ?? "summary_required"
1659
- });
1660
- return this;
1661
- }
1662
- acceptanceCriteria(options = {}) {
1663
- const resolved = typeof options === "string" ? { description: options } : options;
1664
- this.acceptanceCriteriaSpec = stringArrayField({
1665
- description: resolved.description ?? "Acceptance criteria for the requested change",
1666
- requiredErrorCode: resolved.requiredErrorCode ?? "acceptance_criteria_required",
1667
- minItems: resolved.minItems ?? 1,
1668
- minItemsErrorCode: resolved.minItemsErrorCode ?? "acceptance_criteria_required"
1669
- });
1670
- return this;
1671
- }
1672
- review(turnId) {
1673
- this.reviewTurnId = turnId;
1674
- return this.setTarget({ kind: "to", turnId });
1675
- }
1676
- buildOutcome() {
1677
- if (!this.summarySpec) {
1678
- throw new Error("plan result must declare .summary(...)");
1679
- }
1680
- if (!this.acceptanceCriteriaSpec) {
1681
- throw new Error("plan result must declare .acceptanceCriteria(...)");
1682
- }
1683
- if (!this.reviewTurnId) {
1684
- throw new Error("plan result must declare .review(turnId)");
1685
- }
1686
- const stateEffect = this.flowEffect ? wrapLlmOutcomeEffect(this.flowEffect) : void 0;
1687
- return {
1688
- description: this.resultDescription,
1689
- parameters: {
1690
- summary: this.summarySpec,
1691
- acceptanceCriteria: this.acceptanceCriteriaSpec
1692
- },
1693
- to: this.reviewTurnId,
1694
- lifecycleIntent: {
1695
- kind: "save_plan_result",
1696
- summaryParam: "summary",
1697
- acceptanceCriteriaParam: "acceptanceCriteria",
1698
- planMarkdownParam: "planMarkdown",
1699
- emitEventType: DEFAULT_PLAN_RESULT_OUTCOME_ID,
1700
- broadcastType: "plan.updated",
1701
- ...stateEffect ? { state: stateEffect } : {}
1702
- }
1703
- };
1704
- }
1705
- };
1706
- var PublishedResultBuilder = class extends RouteAndEffectBuilder {
1707
- constructor(productName, parent) {
1708
- super();
1709
- this.productName = productName;
1710
- this.parent = parent;
1711
- }
1712
- productName;
1713
- parent;
1714
- get id() {
1715
- if (!this.parent) {
1716
- throw new Error("Published result builder is not attached to a turn");
1717
- }
1718
- return this.parent.id;
1719
- }
1720
- get definition() {
1721
- if (!this.parent) {
1722
- throw new Error("Published result builder is not attached to a turn");
1723
- }
1724
- return this.parent.definition;
1725
- }
1726
- buildTurnEnd() {
1727
- const effect = this.flowEffect ? wrapLlmOutcomeEffect(this.flowEffect) : void 0;
1728
- return {
1729
- outcome: this.productName,
1730
- ...this.buildRouteTarget(),
1731
- ...effect ? { effect } : {}
1732
- };
1733
- }
1734
- };
1735
- var LlmTurnEndBuilder = class extends RouteAndEffectBuilder {
1736
- constructor(outcomeId, parent) {
1737
- super();
1738
- this.outcomeId = outcomeId;
1739
- this.parent = parent;
1740
- if (outcomeId.trim() === "") {
1741
- throw new Error("LLM turn end outcome must be non-empty");
1742
- }
1743
- }
1744
- outcomeId;
1745
- parent;
1746
- get id() {
1747
- if (!this.parent) {
1748
- throw new Error("LLM turn end builder is not attached to a turn");
1749
- }
1750
- return this.parent.id;
1751
- }
1752
- get definition() {
1753
- if (!this.parent) {
1754
- throw new Error("LLM turn end builder is not attached to a turn");
1755
- }
1756
- return this.parent.definition;
1757
- }
1758
- build() {
1759
- const effect = this.flowEffect ? wrapLlmOutcomeEffect(this.flowEffect) : void 0;
1760
- return {
1761
- outcome: this.outcomeId,
1762
- ...this.buildRouteTarget(),
1763
- ...effect ? { effect } : {}
1764
- };
1765
- }
1766
- };
1767
- var LlmFlowBuilder = class {
1768
- turnId;
1769
- turnDescription = null;
1770
- modelPurposeValue;
1771
- availableTools = [];
1772
- promptBuilder = null;
1773
- branchType = "primary";
1774
- context = "fresh";
1775
- completionMode = "turn_end";
1776
- questionsEnabled = false;
1777
- startFrom;
1778
- restorePrimaryLeafAfterTurn;
1779
- reviewSubject;
1780
- consumedProductNames = [];
1781
- optionalConsumedProductNames = [];
1782
- publishedResult = null;
1783
- endResult = null;
1784
- outcomeToolBuilders = /* @__PURE__ */ new Map();
1785
- constructor(turnId) {
1786
- this.turnId = turnId;
1787
- }
1788
- get id() {
1789
- return this.turnId;
1790
- }
1791
- get definition() {
1792
- return this.buildDefinition();
1793
- }
1794
- description(description) {
1795
- this.turnDescription = description;
1796
- return this;
1797
- }
1798
- modelPurpose(purpose) {
1799
- this.modelPurposeValue = purpose;
1800
- return this;
1801
- }
1802
- tools(...tools) {
1803
- this.availableTools = tools;
1804
- return this;
1805
- }
1806
- /** Enable durable operator questions for this LLM turn. */
1807
- askQuestions() {
1808
- this.questionsEnabled = true;
1809
- return this;
1810
- }
1811
- freshPrimary() {
1812
- this.branchType = "primary";
1813
- this.context = "fresh";
1814
- this.completionMode = "turn_end";
1815
- this.startFrom = void 0;
1816
- this.restorePrimaryLeafAfterTurn = void 0;
1817
- return this;
1818
- }
1819
- freshSeededPrimary() {
1820
- this.branchType = "primary";
1821
- this.context = "fresh_seeded";
1822
- this.completionMode = "turn_end";
1823
- this.startFrom = void 0;
1824
- this.restorePrimaryLeafAfterTurn = void 0;
1825
- return this;
1826
- }
1827
- fullPrimary() {
1828
- this.branchType = "primary";
1829
- this.context = "full";
1830
- this.completionMode = "turn_end";
1831
- return this;
1832
- }
1833
- rootBranchReview() {
1834
- this.branchType = "root_branch";
1835
- this.context = "full";
1836
- this.completionMode = "turn_end";
1837
- this.restorePrimaryLeafAfterTurn = true;
1838
- return this;
1839
- }
1840
- continueFromPrimaryLeaf() {
1841
- this.startFrom = {
1842
- kind: "semantic_ref",
1843
- ref: "currentPrimaryPathLeaf",
1844
- fallback: { kind: "current_leaf" }
1845
- };
1846
- return this;
1847
- }
1848
- continueFromReviewBranch() {
1849
- this.startFrom = {
1850
- kind: "semantic_ref",
1851
- ref: "review",
1852
- fallback: { kind: "current_leaf" }
1853
- };
1854
- return this;
1855
- }
1856
- continueFromProductBranch(productName, fallback = { kind: "current_leaf" }) {
1857
- this.startFrom = {
1858
- kind: "product_ref",
1859
- productName: normalizeProductName(productName),
1860
- fallback
1861
- };
1862
- return this;
1863
- }
1864
- startFromReviewBranch() {
1865
- this.startFrom = {
1866
- kind: "semantic_ref",
1867
- ref: "review",
1868
- fallback: { kind: "session_root" }
1869
- };
1870
- return this;
1871
- }
1872
- startFromProductBranch(productName, fallback = { kind: "session_root" }) {
1873
- this.startFrom = {
1874
- kind: "product_ref",
1875
- productName: normalizeProductName(productName),
1876
- fallback
1877
- };
1878
- return this;
1879
- }
1880
- startFromRoot() {
1881
- this.startFrom = { kind: "session_root" };
1882
- return this;
1883
- }
1884
- reviews(subject) {
1885
- this.reviewSubject = subject;
1886
- return this;
1887
- }
1888
- consume(productName) {
1889
- const normalized = normalizeProductName(productName);
1890
- if (!this.consumedProductNames.includes(normalized)) {
1891
- this.consumedProductNames.push(normalized);
1892
- }
1893
- return this;
1894
- }
1895
- optionalConsume(productName) {
1896
- const normalized = normalizeProductName(productName);
1897
- if (!this.optionalConsumedProductNames.includes(normalized)) {
1898
- this.optionalConsumedProductNames.push(normalized);
1899
- }
1900
- return this;
1901
- }
1902
- publish(productName) {
1903
- const normalized = normalizeProductName(productName);
1904
- if (this.publishedResult) {
1905
- throw new Error(`LLM turn '${this.turnId}' can publish only one product in flow v1`);
1906
- }
1907
- if (this.endResult) {
1908
- throw new Error(`LLM turn '${this.turnId}' cannot declare both .publish(...) and .end(...)`);
1909
- }
1910
- const builder = new PublishedResultBuilder(normalized, this);
1911
- this.publishedResult = { productName: normalized, builder };
1912
- return builder;
1913
- }
1914
- end(outcomeId) {
1915
- if (this.endResult) {
1916
- throw new Error(`LLM turn '${this.turnId}' declares duplicate .end(...) completion`);
1917
- }
1918
- if (this.publishedResult) {
1919
- throw new Error(`LLM turn '${this.turnId}' cannot declare both .publish(...) and .end(...)`);
1920
- }
1921
- if (this.outcomeToolBuilders.size > 0) {
1922
- throw new Error(`LLM turn '${this.turnId}' cannot declare both .end(...) and outcome tools`);
1923
- }
1924
- this.endResult = new LlmTurnEndBuilder(outcomeId, this);
1925
- return this.endResult;
1926
- }
1927
- buildPrompt(fn) {
1928
- this.promptBuilder = (ctx) => fn(
1929
- createFlowPromptContext(
1930
- ctx,
1931
- this.consumedProductNames,
1932
- this.optionalConsumedProductNames
1933
- )
1934
- );
1935
- return this;
1936
- }
1937
- prompt(prompt) {
1938
- this.promptBuilder = prompt;
1939
- return this;
1940
- }
1941
- outcomeTool(id, configure) {
1942
- if (id.trim() === "") {
1943
- throw new Error(`LLM turn '${this.turnId}' declares an empty outcome tool id`);
1944
- }
1945
- if (this.endResult) {
1946
- throw new Error(`LLM turn '${this.turnId}' cannot declare both .end(...) and outcome tools`);
1947
- }
1948
- if (this.publishedResult) {
1949
- throw new Error(`LLM turn '${this.turnId}' cannot declare outcome tools after .publish(...)`);
1950
- }
1951
- if (this.outcomeToolBuilders.has(id)) {
1952
- throw new Error(`LLM turn '${this.turnId}' declares duplicate outcome tool '${id}'`);
1953
- }
1954
- const builder = new OutcomeToolBuilder();
1955
- configure(builder);
1956
- this.outcomeToolBuilders.set(id, builder);
1957
- return this;
1958
- }
1959
- buildBaseDefinition() {
1960
- if (!this.turnDescription) {
1961
- throw new Error(`LLM turn '${this.turnId}' must declare .description(...)`);
1962
- }
1963
- const prompt = this.promptBuilder;
1964
- if (!prompt) {
1965
- throw new Error(`LLM turn '${this.turnId}' must declare .buildPrompt(...)`);
1966
- }
1967
- return {
1968
- kind: "llm",
1969
- description: this.turnDescription,
1970
- ...this.modelPurposeValue ? { modelPurpose: this.modelPurposeValue } : {},
1971
- availableTools: this.availableTools,
1972
- ...this.questionsEnabled ? { askQuestions: true } : {},
1973
- completionMode: this.completionMode,
1974
- branchType: this.branchType,
1975
- context: this.context,
1976
- ...this.startFrom ? { startFrom: this.startFrom } : {},
1977
- ...this.restorePrimaryLeafAfterTurn !== void 0 ? { restorePrimaryLeafAfterTurn: this.restorePrimaryLeafAfterTurn } : {},
1978
- prompt
1979
- };
1980
- }
1981
- producesPlan(configure) {
1982
- const definition = this.buildBaseDefinition();
1983
- const plan = configure(new PlanResultBuilder());
1984
- const outcome = plan.buildOutcome();
1985
- return {
1986
- id: this.turnId,
1987
- definition: {
1988
- ...definition,
1989
- outcomes: {
1990
- [DEFAULT_PLAN_RESULT_OUTCOME_ID]: outcome
1991
- },
1992
- turnResultMarkdown: OUTCOME_TOOL_ARGUMENT_TURN_RESULT,
1993
- resultSemanticRef: "plan",
1994
- publishedProduct: "plan"
1995
- }
1996
- };
1997
- }
1998
- buildDefinition() {
1999
- const definition = this.buildBaseDefinition();
2000
- const hasOutcomeTools = this.outcomeToolBuilders.size > 0;
2001
- const explicitTurnEnd = this.endResult;
2002
- const published = this.publishedResult;
2003
- const outcomes = {};
2004
- for (const [outcomeId, builder] of this.outcomeToolBuilders) {
2005
- outcomes[outcomeId] = builder.build();
2006
- }
2007
- const hasOutcomePublishedProduct = Object.values(outcomes).some(
2008
- (outcome) => outcome.publishedProduct
2009
- );
2010
- let turnEnd;
2011
- let resultSemanticRef = this.reviewSubject ? "review" : void 0;
2012
- let turnResultMarkdown;
2013
- let publishedProduct;
2014
- if (published) {
2015
- publishedProduct = published.productName;
2016
- if (published.productName === "plan") {
2017
- resultSemanticRef = "plan";
2018
- }
2019
- if (published.productName === "review") {
2020
- resultSemanticRef = "review";
2021
- }
2022
- const publishHasRoute = published.builder.hasRoute();
2023
- if (publishHasRoute && hasOutcomeTools) {
2024
- throw new Error(
2025
- `LLM turn '${this.turnId}' cannot route published product '${published.productName}' and declare outcome tools in flow v1`
2026
- );
2027
- }
2028
- if (publishHasRoute && !hasOutcomeTools) {
2029
- turnResultMarkdown = ASSISTANT_OUTPUT_TURN_RESULT;
2030
- turnEnd = published.builder.buildTurnEnd();
2031
- }
2032
- if (!publishHasRoute && hasOutcomeTools) {
2033
- turnResultMarkdown = OUTCOME_TOOL_ARGUMENT_TURN_RESULT;
2034
- }
2035
- if (!publishHasRoute && !hasOutcomeTools) {
2036
- throw new Error(
2037
- `LLM turn '${this.turnId}' publishes product '${published.productName}' but declares no route or outcome tool completion path`
2038
- );
2039
- }
2040
- } else if (hasOutcomeTools && !hasOutcomePublishedProduct) {
2041
- turnResultMarkdown = OUTCOME_TOOL_ARGUMENT_TURN_RESULT;
2042
- } else if (explicitTurnEnd) {
2043
- turnResultMarkdown = ASSISTANT_OUTPUT_TURN_RESULT;
2044
- }
2045
- if (hasOutcomeTools) {
2046
- for (const [outcomeId, outcome] of Object.entries(outcomes)) {
2047
- if (OUTCOME_TOOL_MARKDOWN_PARAMETER_NAME in outcome.parameters) {
2048
- throw new Error(
2049
- `LLM turn '${this.turnId}' outcome tool '${outcomeId}' cannot declare reserved markdown parameter '${OUTCOME_TOOL_MARKDOWN_PARAMETER_NAME}'`
2050
- );
2051
- }
2052
- }
2053
- }
2054
- if (explicitTurnEnd) {
2055
- if (turnEnd || Object.keys(outcomes).length > 0) {
2056
- throw new Error(`LLM turn '${this.turnId}' cannot declare multiple completion paths`);
2057
- }
2058
- turnEnd = explicitTurnEnd.build();
2059
- }
2060
- if (Object.keys(outcomes).length === 0 && !turnEnd) {
2061
- throw new Error(`LLM turn '${this.turnId}' must declare a completion path`);
2062
- }
2063
- return {
2064
- ...definition,
2065
- ...this.reviewSubject ? { reviewSubject: this.reviewSubject } : {},
2066
- ...Object.keys(outcomes).length > 0 ? { outcomes } : {},
2067
- ...turnEnd ? { turnEnd } : {},
2068
- ...turnResultMarkdown ? { turnResultMarkdown } : {},
2069
- ...resultSemanticRef ? { resultSemanticRef } : {},
2070
- ...publishedProduct ? { publishedProduct } : {},
2071
- ...this.consumedProductNames.length > 0 ? { consumedProducts: [...this.consumedProductNames] } : {},
2072
- ...this.optionalConsumedProductNames.length > 0 ? { optionalConsumedProducts: [...this.optionalConsumedProductNames] } : {}
2073
- };
2074
- }
2075
- };
2076
- var AutomaticFlowBuilder = class {
2077
- turnId;
2078
- turnDescription = null;
2079
- runFn = null;
2080
- outcomeBuilders = /* @__PURE__ */ new Map();
2081
- constructor(turnId) {
2082
- this.turnId = turnId;
2083
- }
2084
- get id() {
2085
- return this.turnId;
2086
- }
2087
- get definition() {
2088
- return this.buildDefinition();
2089
- }
2090
- description(description) {
2091
- this.turnDescription = description;
2092
- return this;
2093
- }
2094
- run(fn) {
2095
- this.runFn = fn;
2096
- return this;
2097
- }
2098
- outcome(id, configure) {
2099
- if (id.trim() === "") {
2100
- throw new Error(`Automatic turn '${this.turnId}' declares an empty outcome id`);
2101
- }
2102
- if (this.outcomeBuilders.has(id)) {
2103
- throw new Error(`Automatic turn '${this.turnId}' declares duplicate outcome '${id}'`);
2104
- }
2105
- const builder = new AutomaticOutcomeBuilder();
2106
- configure(builder);
2107
- this.outcomeBuilders.set(id, builder);
2108
- return this;
2109
- }
2110
- buildDefinition() {
2111
- if (!this.turnDescription) {
2112
- throw new Error(`Automatic turn '${this.turnId}' must declare .description(...)`);
2113
- }
2114
- if (!this.runFn) {
2115
- throw new Error(`Automatic turn '${this.turnId}' must declare .run(...)`);
2116
- }
2117
- if (this.outcomeBuilders.size === 0) {
2118
- throw new Error(`Automatic turn '${this.turnId}' must declare at least one outcome`);
2119
- }
2120
- const outcomes = {};
2121
- for (const [outcomeId, builder] of this.outcomeBuilders) {
2122
- outcomes[outcomeId] = builder.build();
2123
- }
2124
- const runFn = this.runFn;
2125
- return {
2126
- kind: "automatic",
2127
- description: this.turnDescription,
2128
- outcomes,
2129
- run: (ctx) => runFn(createFlowAutomaticRunContext(ctx))
2130
- };
2131
- }
2132
- };
2133
- var ServerAutomaticFlowBuilder = class {
2134
- turnId;
2135
- turnDescription = null;
2136
- restartBehaviorValue;
2137
- runFn = null;
2138
- outcomeBuilders = /* @__PURE__ */ new Map();
2139
- constructor(turnId) {
2140
- this.turnId = turnId;
2141
- }
2142
- get id() {
2143
- return this.turnId;
2144
- }
2145
- get definition() {
2146
- return this.buildDefinition();
2147
- }
2148
- description(description) {
2149
- this.turnDescription = description;
2150
- return this;
2151
- }
2152
- run(fn) {
2153
- this.runFn = fn;
2154
- return this;
2155
- }
2156
- restartBehavior(behavior) {
2157
- this.restartBehaviorValue = behavior;
2158
- return this;
2159
- }
2160
- outcome(id, configure) {
2161
- if (id.trim() === "") {
2162
- throw new Error(`Server automatic turn '${this.turnId}' declares an empty outcome id`);
2163
- }
2164
- if (this.outcomeBuilders.has(id)) {
2165
- throw new Error(`Server automatic turn '${this.turnId}' declares duplicate outcome '${id}'`);
2166
- }
2167
- const builder = new AutomaticOutcomeBuilder();
2168
- configure(builder);
2169
- this.outcomeBuilders.set(id, builder);
2170
- return this;
2171
- }
2172
- buildDefinition() {
2173
- if (!this.turnDescription) {
2174
- throw new Error(`Server automatic turn '${this.turnId}' must declare .description(...)`);
2175
- }
2176
- if (!this.runFn) {
2177
- throw new Error(`Server automatic turn '${this.turnId}' must declare .run(...)`);
2178
- }
2179
- if (this.outcomeBuilders.size === 0) {
2180
- throw new Error(`Server automatic turn '${this.turnId}' must declare at least one outcome`);
2181
- }
2182
- const outcomes = {};
2183
- for (const [outcomeId, builder] of this.outcomeBuilders) {
2184
- outcomes[outcomeId] = builder.build();
2185
- }
2186
- const runFn = this.runFn;
2187
- return {
2188
- kind: "server_automatic",
2189
- description: this.turnDescription,
2190
- outcomes,
2191
- ...this.restartBehaviorValue ? { restartBehavior: this.restartBehaviorValue } : {},
2192
- run: (ctx) => runFn(createFlowAutomaticRunContext(ctx))
2193
- };
2194
- }
2195
- };
2196
- function formFieldPublishedProductName(field) {
2197
- if (!field.publish) {
2198
- return null;
2199
- }
2200
- return normalizeProductName(
2201
- typeof field.publish === "object" && field.publish.product ? field.publish.product : field.id
2202
- );
2203
- }
2204
- function inferActionLabel(actionId) {
2205
- return humanizeProcessLabel(actionId);
2206
- }
2207
- function inferAcceptanceState(actionId) {
2208
- const normalized = actionId.toLowerCase();
2209
- if (/approve|accept|complete|merged/.test(normalized)) {
2210
- return "accepted";
2211
- }
2212
- if (/request|revision|feedback|change|reject/.test(normalized)) {
2213
- return "requires_changes";
2214
- }
2215
- return "neutral";
2216
- }
2217
- var HumanActionBuilder = class {
2218
- constructor(actionId) {
2219
- this.actionId = actionId;
2220
- }
2221
- actionId;
2222
- spec = {};
2223
- label(label) {
2224
- this.spec.label = label;
2225
- return this;
2226
- }
2227
- description(description) {
2228
- this.spec.description = description;
2229
- return this;
2230
- }
2231
- acceptanceState(state) {
2232
- this.spec.acceptanceState = state;
2233
- return this;
2234
- }
2235
- form(form) {
2236
- this.spec.form = form;
2237
- return this;
2238
- }
2239
- to(turnId) {
2240
- this.spec.to = turnId;
2241
- return this;
2242
- }
2243
- complete() {
2244
- this.spec.complete = true;
2245
- return this;
2246
- }
2247
- lifecycleStatus(status) {
2248
- this.spec.lifecycleStatus = status;
2249
- return this;
2250
- }
2251
- trigger(trigger) {
2252
- this.spec.trigger = trigger;
2253
- return this;
2254
- }
2255
- schedulable(value = true) {
2256
- this.spec.schedulable = value;
2257
- return this;
2258
- }
2259
- effect(effect) {
2260
- this.spec.effect = effect;
2261
- return this;
2262
- }
2263
- build() {
2264
- return {
2265
- label: typeof this.spec.label === "string" ? this.spec.label : inferActionLabel(this.actionId),
2266
- acceptanceState: this.spec.acceptanceState ?? inferAcceptanceState(this.actionId),
2267
- ...this.spec
2268
- };
2269
- }
2270
- };
2271
- var ExternalActionBuilder = class {
2272
- spec;
2273
- constructor(actionId, source) {
2274
- this.spec = { id: actionId, source };
2275
- }
2276
- label(label) {
2277
- this.spec.label = label;
2278
- return this;
2279
- }
2280
- description(description) {
2281
- this.spec.description = description;
2282
- return this;
2283
- }
2284
- to(turnId) {
2285
- this.spec.to = turnId;
2286
- return this;
2287
- }
2288
- complete() {
2289
- this.spec.complete = true;
2290
- return this;
2291
- }
2292
- lifecycleStatus(status) {
2293
- this.spec.lifecycleStatus = status;
2294
- return this;
2295
- }
2296
- publishInput(productName, options) {
2297
- this.spec.publishInput = {
2298
- productName: normalizeProductName(productName),
2299
- inputField: options.inputField
2300
- };
2301
- return this;
2302
- }
2303
- build() {
2304
- return this.spec;
2305
- }
2306
- };
2307
- var HumanFlowBuilder = class {
2308
- constructor(turnId) {
2309
- this.turnId = turnId;
2310
- }
2311
- turnId;
2312
- turnDescription = null;
2313
- reviewSubject = null;
2314
- reviewProductName;
2315
- reviewSemanticRef;
2316
- operatorAttentionValue;
2317
- turnCommentary;
2318
- notes;
2319
- actions = /* @__PURE__ */ new Map();
2320
- externalActionBuilders = /* @__PURE__ */ new Map();
2321
- get id() {
2322
- return this.turnId;
2323
- }
2324
- get definition() {
2325
- if (!this.turnDescription) {
2326
- throw new Error(`Human turn '${this.turnId}' must declare .description(...)`);
2327
- }
2328
- return {
2329
- kind: "human",
2330
- description: this.turnDescription,
2331
- ...this.reviewSubject ? { reviewSubject: this.reviewSubject } : {},
2332
- ...this.reviewProductName ? { reviewProduct: this.reviewProductName } : {},
2333
- ...this.reviewSemanticRef ? { reviewSemanticRef: this.reviewSemanticRef } : {},
2334
- ...this.operatorAttentionValue ? { operatorAttention: this.operatorAttentionValue } : {},
2335
- ...this.notes ? { notesFields: this.notes } : {},
2336
- ...this.turnCommentary ? { commentary: this.turnCommentary } : {},
2337
- actions: Object.fromEntries(
2338
- [...this.actions.entries()].map(([actionId, builder]) => [actionId, builder.build()])
2339
- ),
2340
- ...this.externalActionBuilders.size > 0 ? {
2341
- externalActions: Object.fromEntries(
2342
- [...this.externalActionBuilders.entries()].map(([actionId, builder]) => [
2343
- actionId,
2344
- builder.build()
2345
- ])
2346
- )
2347
- } : {}
2348
- };
2349
- }
2350
- description(description) {
2351
- this.turnDescription = description;
2352
- return this;
2353
- }
2354
- review(subject) {
2355
- this.reviewSubject = typeof subject === "string" ? createReviewSubject(subject) : subject;
2356
- this.reviewProductName = void 0;
2357
- this.reviewSemanticRef = typeof subject === "string" && subject === "plan" ? "plan" : void 0;
2358
- return this;
2359
- }
2360
- reviewProduct(productName, options) {
2361
- const normalized = normalizeProductName(productName);
2362
- this.reviewProductName = normalized;
2363
- this.reviewSubject = typeof options.subject === "string" ? createReviewSubject(options.subject) : options.subject;
2364
- this.reviewSemanticRef = normalized === "plan" ? "plan" : normalized === "review" ? "review" : void 0;
2365
- return this;
2366
- }
2367
- operatorAttention(attention) {
2368
- this.operatorAttentionValue = attention;
2369
- return this;
2370
- }
2371
- commentary(commentary) {
2372
- this.turnCommentary = commentary;
2373
- return this;
2374
- }
2375
- notesFields(notes) {
2376
- this.notes = notes;
2377
- return this;
2378
- }
2379
- action(actionId, configure) {
2380
- if (this.actions.has(actionId)) {
2381
- throw new Error(`Human turn '${this.turnId}' declares duplicate action '${actionId}'`);
2382
- }
2383
- const builder = new HumanActionBuilder(actionId);
2384
- configure(builder);
2385
- this.actions.set(actionId, builder);
2386
- return this;
2387
- }
2388
- externalAction(externalActionId, source, configure) {
2389
- if (this.externalActionBuilders.has(externalActionId)) {
2390
- throw new Error(
2391
- `Human turn '${this.turnId}' declares duplicate external action '${externalActionId}'`
2392
- );
2393
- }
2394
- const builder = new ExternalActionBuilder(
2395
- externalActionId,
2396
- source
2397
- );
2398
- configure(builder);
2399
- this.externalActionBuilders.set(
2400
- externalActionId,
2401
- builder
2402
- );
2403
- return this;
2404
- }
2405
- };
2406
- var ExternalRouteBuilder = class {
2407
- constructor(parent, source) {
2408
- this.parent = parent;
2409
- this.source = source;
2410
- }
2411
- parent;
2412
- source;
2413
- externalEffect;
2414
- target = null;
2415
- get id() {
2416
- return this.parent.id;
2417
- }
2418
- get definition() {
2419
- return this.parent.definition;
2420
- }
2421
- setTarget(next) {
2422
- if (this.target) {
2423
- throw new Error("External source route already declares a target");
2424
- }
2425
- this.target = next;
2426
- return this;
2427
- }
2428
- to(turnId) {
2429
- return this.setTarget({ kind: "to", turnId });
2430
- }
2431
- complete() {
2432
- return this.setTarget({ kind: "complete" });
2433
- }
2434
- lifecycleStatus(status) {
2435
- return this.setTarget({ kind: "lifecycleStatus", status });
2436
- }
2437
- state(fn) {
2438
- this.externalEffect = async (ctx) => ({
2439
- state: await fn({ ctx, event: ctx.event, input: ctx.input })
2440
- });
2441
- return this;
2442
- }
2443
- effect(fn) {
2444
- this.externalEffect = (ctx) => fn({ ctx, event: ctx.event, input: ctx.input });
2445
- return this;
2446
- }
2447
- buildRouteTarget() {
2448
- return buildRouteTargetSpec(this.target);
2449
- }
2450
- build() {
2451
- return {
2452
- source: this.source,
2453
- ...this.buildRouteTarget(),
2454
- ...this.externalEffect ? { effect: this.externalEffect } : {}
2455
- };
2456
- }
2457
- };
2458
- var ExternalFlowBuilder = class {
2459
- constructor(turnId) {
2460
- this.turnId = turnId;
2461
- }
2462
- turnId;
2463
- turnDescription = null;
2464
- routeBuilders = [];
2465
- get id() {
2466
- return this.turnId;
2467
- }
2468
- get definition() {
2469
- if (!this.turnDescription) {
2470
- this.turnDescription = this.routeBuilders[0]?.build().source.description ?? "Wait for an external source";
2471
- }
2472
- if (this.routeBuilders.length === 0) {
2473
- throw new Error(`External turn '${this.turnId}' must declare at least one .from(...) source`);
2474
- }
2475
- return {
2476
- kind: "external",
2477
- description: this.turnDescription,
2478
- transitions: this.routeBuilders.map((builder) => builder.build())
2479
- };
2480
- }
2481
- description(description) {
2482
- this.turnDescription = description;
2483
- return this;
2484
- }
2485
- from(source) {
2486
- const builder = new ExternalRouteBuilder(this, source);
2487
- this.routeBuilders.push(
2488
- builder
2489
- );
2490
- return builder;
2491
- }
2492
- };
2493
- var FlowComponentBuilder = class {
2494
- turns = [];
2495
- serverHooks = [];
2496
- uiHooks = [];
2497
- launcherHooks = [];
2498
- watcherHooks = [];
2499
- turn(turn) {
2500
- this.turns.push(turn);
2501
- return this;
2502
- }
2503
- server(hook) {
2504
- this.serverHooks.push(hook);
2505
- return this;
2506
- }
2507
- action(definition) {
2508
- this.serverHooks.push((api) => api.action(definition));
2509
- return this;
2510
- }
2511
- ui(hook) {
2512
- this.uiHooks.push(hook);
2513
- return this;
2514
- }
2515
- launcher(definitionOrHook) {
2516
- if (typeof definitionOrHook === "function") {
2517
- this.launcherHooks.push(definitionOrHook);
2518
- } else {
2519
- this.launcherHooks.push((api) => api.launcher(definitionOrHook));
2520
- }
2521
- return this;
2522
- }
2523
- watcher(definitionOrHook) {
2524
- if (typeof definitionOrHook === "function") {
2525
- this.watcherHooks.push(definitionOrHook);
2526
- } else {
2527
- this.watcherHooks.push((api) => api.watcher(definitionOrHook));
2528
- }
2529
- return this;
2530
- }
2531
- };
2532
- var FlowFragmentBuilder = class extends FlowComponentBuilder {
2533
- name;
2534
- constructor(name) {
2535
- super();
2536
- if (name.trim() === "") {
2537
- throw new Error("Flow fragment name must be non-empty");
2538
- }
2539
- this.name = name;
2540
- }
2541
- };
2542
- var FlowProcessBuilder = class extends FlowComponentBuilder {
2543
- processId;
2544
- processDisplayName = null;
2545
- entryTurnId = null;
2546
- alternateEntryTurnIds = [];
2547
- happyPathTurnIds = null;
2548
- paramsCodec = null;
2549
- stateCodec = null;
2550
- initialStateFn = null;
2551
- repositoryCredentialsFn;
2552
- processPiConfig;
2553
- constructor(processId) {
2554
- super();
2555
- if (processId.trim() === "") {
2556
- throw new Error("Flow process id must be non-empty");
2557
- }
2558
- this.processId = processId;
2559
- }
2560
- displayName(displayName) {
2561
- this.processDisplayName = displayName;
2562
- return this;
2563
- }
2564
- entry(turnId) {
2565
- this.entryTurnId = turnId;
2566
- return this;
2567
- }
2568
- /** Declare an additional turn that launchers may select as the first turn. */
2569
- alternateEntry(turnId) {
2570
- this.alternateEntryTurnIds.push(turnId);
2571
- return this;
2572
- }
2573
- /**
2574
- * Declare the happy path: the ordered spine of turns a successful run walks
2575
- * through. Flow diagrams render this as the main line. Must start at the entry
2576
- * turn and reference only declared turns without repeats.
2577
- */
2578
- happyPath(...turnIds) {
2579
- this.happyPathTurnIds = turnIds;
2580
- return this;
2581
- }
2582
- codecs(input) {
2583
- this.paramsCodec = input.params;
2584
- this.stateCodec = input.state;
2585
- return this;
2586
- }
2587
- initialState(fn) {
2588
- this.initialStateFn = fn;
2589
- return this;
2590
- }
2591
- repositoryCredentials(fn) {
2592
- this.repositoryCredentialsFn = fn;
2593
- return this;
2594
- }
2595
- piConfig(config) {
2596
- this.processPiConfig = config;
2597
- return this;
2598
- }
2599
- use(fragment) {
2600
- this.turns.push(...fragment.turns);
2601
- this.serverHooks.push(...fragment.serverHooks);
2602
- this.uiHooks.push(...fragment.uiHooks);
2603
- this.launcherHooks.push(...fragment.launcherHooks);
2604
- this.watcherHooks.push(...fragment.watcherHooks);
2605
- return this;
2606
- }
2607
- define() {
2608
- if (!this.processDisplayName) {
2609
- throw new Error(`Flow process '${this.processId}' must declare .displayName(...)`);
2610
- }
2611
- if (!this.entryTurnId) {
2612
- throw new Error(`Flow process '${this.processId}' must declare .entry(turnId)`);
2613
- }
2614
- if (!this.paramsCodec || !this.stateCodec) {
2615
- throw new Error(`Flow process '${this.processId}' must declare .codecs(...)`);
2616
- }
2617
- if (!this.initialStateFn) {
2618
- throw new Error(`Flow process '${this.processId}' must declare .initialState(...)`);
2619
- }
2620
- const turns = {};
2621
- for (const turn of this.turns) {
2622
- if (Object.hasOwn(turns, turn.id)) {
2623
- throw new Error(`Flow process '${this.processId}' declares duplicate turn '${turn.id}'`);
2624
- }
2625
- turns[turn.id] = turn.definition;
2626
- }
2627
- const publishedProducts = /* @__PURE__ */ new Set();
2628
- for (const turnDef of Object.values(turns)) {
2629
- if (turnDef.kind === "llm") {
2630
- if (turnDef.publishedProduct) {
2631
- normalizeProductName(turnDef.publishedProduct);
2632
- publishedProducts.add(turnDef.publishedProduct);
2633
- }
2634
- for (const outcome of Object.values(turnDef.outcomes ?? {})) {
2635
- if (outcome?.publishedProduct) {
2636
- normalizeProductName(outcome.publishedProduct);
2637
- publishedProducts.add(outcome.publishedProduct);
2638
- }
2639
- }
2640
- }
2641
- if (turnDef.kind === "human") {
2642
- for (const action of Object.values(turnDef.actions)) {
2643
- for (const field of action.form?.fields ?? []) {
2644
- const productName = formFieldPublishedProductName(field);
2645
- if (productName) {
2646
- publishedProducts.add(productName);
2647
- }
2648
- }
2649
- }
2650
- for (const externalAction of Object.values(turnDef.externalActions ?? {})) {
2651
- if (externalAction.publishInput) {
2652
- publishedProducts.add(normalizeProductName(externalAction.publishInput.productName));
2653
- }
2654
- }
2655
- }
2656
- }
2657
- for (const [turnId, turnDef] of Object.entries(turns)) {
2658
- if (turnDef.kind !== "llm") {
2659
- continue;
2660
- }
2661
- for (const productName of [
2662
- ...turnDef.consumedProducts ?? [],
2663
- ...turnDef.optionalConsumedProducts ?? []
2664
- ]) {
2665
- normalizeProductName(productName);
2666
- if (!publishedProducts.has(productName)) {
2667
- throw new Error(
2668
- `Flow process '${this.processId}' turn '${turnId}' consumes product '${productName}' that is never published by this process`
2669
- );
2670
- }
2671
- }
2672
- }
2673
- const input = {
2674
- id: this.processId,
2675
- displayName: this.processDisplayName,
2676
- entry: this.entryTurnId,
2677
- ...this.alternateEntryTurnIds.length > 0 ? { alternateEntries: [...this.alternateEntryTurnIds] } : {},
2678
- ...this.happyPathTurnIds ? { happyPath: [...this.happyPathTurnIds] } : {},
2679
- paramsCodec: this.paramsCodec,
2680
- stateCodec: this.stateCodec,
2681
- initialState: this.initialStateFn,
2682
- ...this.repositoryCredentialsFn ? { repositoryCredentials: this.repositoryCredentialsFn } : {},
2683
- ...this.processPiConfig ? { piConfig: this.processPiConfig } : {},
2684
- turns,
2685
- ...this.serverHooks.length > 0 ? {
2686
- server: (api) => {
2687
- for (const hook of this.serverHooks) {
2688
- hook(api);
2689
- }
2690
- }
2691
- } : {},
2692
- ...this.uiHooks.length > 0 ? {
2693
- ui: (api) => {
2694
- for (const hook of this.uiHooks) {
2695
- hook(api);
2696
- }
2697
- }
2698
- } : {},
2699
- ...this.launcherHooks.length > 0 ? {
2700
- launchers: (api) => {
2701
- for (const hook of this.launcherHooks) {
2702
- hook(api);
2703
- }
2704
- }
2705
- } : {},
2706
- ...this.watcherHooks.length > 0 ? {
2707
- watchers: (api) => {
2708
- for (const hook of this.watcherHooks) {
2709
- hook(api);
2710
- }
2711
- }
2712
- } : {}
2713
- };
2714
- return defineProcess(input);
2715
- }
2716
- };
2717
- var flow = {
2718
- llm(turnId) {
2719
- return new LlmFlowBuilder(turnId);
2720
- },
2721
- automatic(turnId) {
2722
- return new AutomaticFlowBuilder(turnId);
2723
- },
2724
- serverAutomatic(turnId) {
2725
- return new ServerAutomaticFlowBuilder(turnId);
2726
- },
2727
- human(turnId) {
2728
- return new HumanFlowBuilder(turnId);
2729
- },
2730
- external(turnId) {
2731
- return new ExternalFlowBuilder(turnId);
2732
- },
2733
- fragment(name) {
2734
- return new FlowFragmentBuilder(name);
2735
- },
2736
- process(processId) {
2737
- return new FlowProcessBuilder(processId);
2738
- }
2739
- };
2740
-
2741
- // src/fs-utils.ts
2742
- import { randomUUID } from "crypto";
2743
- import { mkdir, rename, unlink, writeFile } from "fs/promises";
2744
- import path2 from "path";
2745
- async function atomicWriteUtf8(filePath, content) {
2746
- const dir = path2.dirname(filePath);
2747
- await mkdir(dir, { recursive: true });
2748
- const tempPath = path2.join(
2749
- dir,
2750
- `.${path2.basename(filePath)}.${process.pid}.${Date.now()}.${randomUUID()}.tmp`
2751
- );
2752
- try {
2753
- await writeFile(tempPath, content, "utf8");
2754
- await rename(tempPath, filePath);
2755
- } catch (error) {
2756
- await unlink(tempPath).catch(() => {
2757
- });
2758
- throw error;
2759
- }
2760
- }
2761
- function isEnoent(error) {
2762
- return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
2763
- }
2764
-
2765
- // src/graph-fragments.ts
2766
- function appendQueuedInstruction(input) {
2767
- if (input.bodyMarkdown == null) {
2768
- return input.plan;
2769
- }
2770
- if (input.bodyMarkdown.trim() === "") {
2771
- throw new Error("Queued instruction bodyMarkdown must not be empty");
2772
- }
2773
- return {
2774
- ...input.plan ?? {},
2775
- queueInput: [
2776
- ...input.plan?.queueInput ?? [],
2777
- {
2778
- source: input.queueSource ?? "action_prompt",
2779
- kind: input.queueKind ?? "instruction",
2780
- ...input.queueTarget ? { target: input.queueTarget } : {},
2781
- bodyMarkdown: input.bodyMarkdown
2782
- }
2783
- ]
2784
- };
2785
- }
2786
- function queuedInstructionAction(spec) {
2787
- const { queueTarget, queueSource, queueKind, resolveBodyMarkdown, effect, ...rest } = spec;
2788
- return {
2789
- ...rest,
2790
- async effect(input) {
2791
- const bodyMarkdown = await resolveBodyMarkdown(input);
2792
- const plan = effect ? await effect(input) : void 0;
2793
- return appendQueuedInstruction({
2794
- plan,
2795
- bodyMarkdown,
2796
- queueTarget,
2797
- queueSource,
2798
- queueKind
2799
- });
2800
- }
2801
- };
2802
- }
2803
- function revisionAction(spec) {
2804
- const { messageFieldId = "message", missingMessageError, ...rest } = spec;
2805
- return queuedInstructionAction({
2806
- ...rest,
2807
- resolveBodyMarkdown({ input }) {
2808
- const message = typeof input[messageFieldId] === "string" ? input[messageFieldId].trim() : "";
2809
- if (!message) {
2810
- throw new Error(missingMessageError ?? `${messageFieldId} is required`);
2811
- }
2812
- return message;
2813
- }
2814
- });
2815
- }
2816
- function acceptedReviewHandoffAction(spec) {
2817
- return queuedInstructionAction({
2818
- ...spec,
2819
- queueTarget: spec.queueTarget ?? { semanticRef: "currentPrimaryPathLeaf" }
2820
- });
2821
- }
2822
-
2823
- // src/host-capabilities.ts
2824
- function createCapabilityAccessor(provided = []) {
2825
- const singleCapabilities = /* @__PURE__ */ new Map();
2826
- const multiCapabilities = /* @__PURE__ */ new Map();
2827
- for (const entry of provided) {
2828
- if (entry.token.cardinality === "multi") {
2829
- const list = multiCapabilities.get(entry.token.id) ?? [];
2830
- list.push(entry.value);
2831
- multiCapabilities.set(entry.token.id, list);
2832
- continue;
2833
- }
2834
- singleCapabilities.set(entry.token.id, entry.value);
2835
- }
2836
- return {
2837
- provide(token, value) {
2838
- if (token.cardinality === "multi") {
2839
- const list = multiCapabilities.get(token.id) ?? [];
2840
- list.push(value);
2841
- multiCapabilities.set(token.id, list);
2842
- return;
2843
- }
2844
- if (singleCapabilities.has(token.id)) {
2845
- throw new Error(`Capability '${token.id}' is already provided`);
2846
- }
2847
- singleCapabilities.set(token.id, value);
2848
- },
2849
- get(token) {
2850
- if (token.cardinality === "multi") {
2851
- return [...multiCapabilities.get(token.id) ?? []];
2852
- }
2853
- return singleCapabilities.get(token.id);
2854
- },
2855
- require(token) {
2856
- const value = this.get(token);
2857
- if (value === void 0 || Array.isArray(value) && token.cardinality === "multi" && value.length === 0) {
2858
- throw new Error(`Required capability '${token.id}' is not available`);
2859
- }
2860
- return value;
2861
- }
2862
- };
2863
- }
2864
-
2865
- // src/leaf-outcomes.ts
2866
- import * as v from "valibot";
2867
- var unknownRecordSchema = v.pipe(
2868
- v.unknown(),
2869
- v.check(
2870
- (value) => typeof value === "object" && value !== null && !Array.isArray(value),
2871
- "Expected object"
2872
- ),
2873
- v.record(v.string(), v.unknown())
2874
- );
2875
- function isNonEmptyString(value) {
2876
- return typeof value === "string" && value.trim() !== "";
2877
- }
2878
- function validateProcessLeafOutcomeDefinition(def) {
2879
- const errors = [];
2880
- if (!isNonEmptyString(def.rendererId)) {
2881
- errors.push("Leaf outcome definition must declare a non-empty rendererId");
2882
- }
2883
- if (typeof def.capture !== "function") {
2884
- errors.push(`Leaf outcome '${String(def.rendererId)}' must declare a capture() function`);
2885
- }
2886
- return errors;
2887
- }
2888
- function validateLeafOutcomeCaptureResult(result, expectedRendererId) {
2889
- const errors = [];
2890
- const parsedResult = v.safeParse(unknownRecordSchema, result);
2891
- if (!parsedResult.success) {
2892
- return ["Leaf outcome capture result must be an object"];
2893
- }
2894
- const captureResult = parsedResult.output;
2895
- if (!isNonEmptyString(captureResult.rendererId)) {
2896
- errors.push("Leaf outcome capture result must include a non-empty rendererId");
2897
- } else if (expectedRendererId && captureResult.rendererId.trim() !== expectedRendererId.trim()) {
2898
- errors.push(
2899
- `Leaf outcome capture result rendererId '${captureResult.rendererId}' must match '${expectedRendererId}'`
2900
- );
2901
- }
2902
- if (!v.safeParse(unknownRecordSchema, captureResult.props).success) {
2903
- errors.push("Leaf outcome capture result props must be an object");
2904
- }
2905
- if (captureResult.schemaVersion !== void 0 && (typeof captureResult.schemaVersion !== "number" || !Number.isInteger(captureResult.schemaVersion))) {
2906
- errors.push("Leaf outcome capture result schemaVersion must be an integer when provided");
2907
- }
2908
- if (captureResult.fallbackMarkdown !== void 0 && captureResult.fallbackMarkdown !== null && typeof captureResult.fallbackMarkdown !== "string") {
2909
- errors.push("Leaf outcome capture result fallbackMarkdown must be a string or null");
2910
- }
2911
- return errors;
2912
- }
2913
- function normalizeLeafOutcomeCaptureResult(result) {
2914
- return {
2915
- rendererId: result.rendererId.trim(),
2916
- ...result.schemaVersion !== void 0 ? { schemaVersion: result.schemaVersion } : {},
2917
- props: { ...result.props },
2918
- ...result.fallbackMarkdown !== void 0 ? { fallbackMarkdown: result.fallbackMarkdown } : {}
2919
- };
2920
- }
2921
-
2922
- // src/model-provider.ts
2923
- function defineProviderOptions(definition) {
2924
- for (const [fieldId, field] of Object.entries(definition.fields)) {
2925
- if (fieldId.trim() === "") {
2926
- throw new Error("Provider option field ids must not be empty");
2927
- }
2928
- if (field.minLength !== void 0 && (!Number.isInteger(field.minLength) || field.minLength < 0)) {
2929
- throw new Error(`Provider option '${fieldId}' minLength must be a non-negative integer`);
2930
- }
2931
- if (field.maxLength !== void 0 && (!Number.isInteger(field.maxLength) || field.maxLength < 0)) {
2932
- throw new Error(`Provider option '${fieldId}' maxLength must be a non-negative integer`);
2933
- }
2934
- if (field.minLength !== void 0 && field.maxLength !== void 0 && field.minLength > field.maxLength) {
2935
- throw new Error(`Provider option '${fieldId}' minLength must not exceed maxLength`);
2936
- }
2937
- }
2938
- return { ...definition, fields: { ...definition.fields } };
2939
- }
2940
- function validateOptionValue(fieldId, field, value) {
2941
- if (typeof value !== "string") {
2942
- return {
2943
- fieldId,
2944
- code: "not_string",
2945
- message: `Provider option '${fieldId}' must be a string`
2946
- };
2947
- }
2948
- if (field.minLength !== void 0 && value.length < field.minLength) {
2949
- return {
2950
- fieldId,
2951
- code: "too_short",
2952
- message: `Provider option '${fieldId}' must contain at least ${field.minLength} characters`
2953
- };
2954
- }
2955
- if (field.maxLength !== void 0 && value.length > field.maxLength) {
2956
- return {
2957
- fieldId,
2958
- code: "too_long",
2959
- message: `Provider option '${fieldId}' must contain at most ${field.maxLength} characters`
2960
- };
2961
- }
2962
- return null;
2963
- }
2964
- function resolveProviderOptions(input) {
2965
- const fields = input.definition?.fields ?? {};
2966
- const issues = [];
2967
- for (const source of [input.explicit, input.profileDefaults]) {
2968
- for (const fieldId of Object.keys(source ?? {})) {
2969
- if (!(fieldId in fields)) {
2970
- issues.push({
2971
- fieldId,
2972
- code: "unknown",
2973
- message: `Unknown provider option '${fieldId}'`
2974
- });
2975
- }
2976
- }
2977
- }
2978
- if (issues.length > 0) {
2979
- return { ok: false, issues };
2980
- }
2981
- const resolved = {};
2982
- for (const [fieldId, field] of Object.entries(fields)) {
2983
- const explicit = input.explicit?.[fieldId];
2984
- const profileDefault = input.profileDefaults?.[fieldId];
2985
- const declaredDefault = typeof field.defaultValue === "function" ? field.defaultValue({ config: input.config }) : field.defaultValue;
2986
- const value = explicit ?? profileDefault ?? declaredDefault;
2987
- if (value === void 0 || value === null) {
2988
- if (field.required) {
2989
- issues.push({
2990
- fieldId,
2991
- code: "required",
2992
- message: `Provider option '${fieldId}' is required`
2993
- });
2994
- }
2995
- continue;
2996
- }
2997
- const issue = validateOptionValue(fieldId, field, value);
2998
- if (issue) {
2999
- issues.push(issue);
3000
- continue;
3001
- }
3002
- resolved[fieldId] = value;
3003
- }
3004
- return issues.length > 0 ? { ok: false, issues } : { ok: true, value: resolved };
3005
- }
3006
- function filterProviderOptionsForDefinition(definition, values) {
3007
- const fields = definition?.fields ?? {};
3008
- return Object.fromEntries(Object.entries(values).filter(([fieldId]) => fieldId in fields));
3009
- }
3010
- function defineWorkerConfig(definition) {
3011
- if (!Number.isInteger(definition.version) || definition.version < 1) {
3012
- throw new Error("Provider worker config version must be a positive integer");
3013
- }
3014
- return definition;
3015
- }
3016
- function definePiServerAdapter(adapter) {
3017
- if (!adapter || typeof adapter.generateText !== "function") {
3018
- throw new Error("Pi server adapter must define generateText()");
3019
- }
3020
- return adapter;
3021
- }
3022
- function piWorker(input = {}) {
3023
- const credentialFiles = input.credentialFiles?.map((file) => {
3024
- if (!file || file.startsWith("/") || file.includes("..") || file.includes("\\\\")) {
3025
- throw new Error("Pi worker credential file must be a relative path");
3026
- }
3027
- return file;
3028
- });
3029
- return {
3030
- kind: "extension_pi_worker",
3031
- ...input,
3032
- ...credentialFiles ? { credentialFiles } : {}
3033
- };
3034
- }
3035
- function piServer() {
3036
- return { kind: "extension_pi_server" };
3037
- }
3038
- function builtinPiProvider(providerId) {
3039
- if (providerId.trim() === "") {
3040
- throw new Error("Built-in Pi provider id must not be empty");
3041
- }
3042
- return { kind: "builtin_pi_provider", providerId };
3043
- }
3044
- function configuredPiProvider(providerId, resolveModels) {
3045
- if (providerId.trim() === "") {
3046
- throw new Error("Configured Pi provider id must not be empty");
3047
- }
3048
- return { kind: "configured_pi_provider", providerId, resolveModels };
3049
- }
3050
- function defineModelProvider(definition) {
3051
- if (definition.id.trim() === "") {
3052
- throw new Error("Model provider id must not be empty");
3053
- }
3054
- return definition;
3055
- }
3056
- function defineModelProviders(resolve) {
3057
- return resolve;
3058
- }
3059
- function definePiWorker(contribution) {
3060
- return contribution;
3061
- }
3062
- function credentialBasedModelStatuses(configuredModels, credentialStatus, unavailableReason) {
3063
- const seen = /* @__PURE__ */ new Set();
3064
- const statuses = [];
3065
- for (const configured of configuredModels) {
3066
- if (seen.has(configured.modelId)) continue;
3067
- seen.add(configured.modelId);
3068
- statuses.push({
3069
- modelId: configured.modelId,
3070
- availability: credentialStatus.available ? "available" : "unavailable",
3071
- ...credentialStatus.available ? {} : { safeReason: unavailableReason }
3072
- });
3073
- }
3074
- return statuses;
3075
- }
3076
-
3077
- // src/process-flow-view.ts
3078
- import {
3079
- humanizeProcessLabel as humanizeProcessLabel2
3080
- } from "@leitwerk-dev/domain";
3081
- function trimToNull(value) {
3082
- if (typeof value !== "string") {
3083
- return null;
3084
- }
3085
- const trimmed = value.trim();
3086
- return trimmed === "" ? null : trimmed;
3087
- }
3088
- function isRoutingTurn(turn) {
3089
- return turn.turnType === "human";
3090
- }
3091
- function computeRoutingAnchors(graph, routingIds) {
3092
- const declarationIndex = /* @__PURE__ */ new Map();
3093
- [...graph.turns.keys()].forEach((turnId, index) => {
3094
- declarationIndex.set(turnId, index);
3095
- });
3096
- const happyIndex = /* @__PURE__ */ new Map();
3097
- (graph.happyPath ?? []).forEach((turnId, index) => {
3098
- if (!happyIndex.has(turnId)) {
3099
- happyIndex.set(turnId, index);
3100
- }
3101
- });
3102
- const workPredecessors = /* @__PURE__ */ new Map();
3103
- const routingPredecessors = /* @__PURE__ */ new Map();
3104
- for (const routingId of routingIds) {
3105
- workPredecessors.set(routingId, []);
3106
- routingPredecessors.set(routingId, []);
3107
- }
3108
- for (const [turnId, turn] of graph.turns) {
3109
- for (const transition of turn.transitions) {
3110
- const next = transition.nextTurnId;
3111
- if (next === void 0 || !routingIds.has(next) || next === turnId) {
3112
- continue;
3113
- }
3114
- if (routingIds.has(turnId)) {
3115
- routingPredecessors.get(next)?.push(turnId);
3116
- } else {
3117
- workPredecessors.get(next)?.push(turnId);
3118
- }
3119
- }
3120
- }
3121
- const preferenceKey = (turnId) => [
3122
- happyIndex.get(turnId) ?? Number.POSITIVE_INFINITY,
3123
- declarationIndex.get(turnId) ?? Number.POSITIVE_INFINITY
3124
- ];
3125
- const pickPreferred = (candidates) => {
3126
- let best;
3127
- let bestKey;
3128
- for (const candidate of candidates) {
3129
- const key = preferenceKey(candidate);
3130
- if (bestKey === void 0 || key[0] < bestKey[0] || key[0] === bestKey[0] && key[1] < bestKey[1]) {
3131
- best = candidate;
3132
- bestKey = key;
3133
- }
3134
- }
3135
- return best;
3136
- };
3137
- const anchors = /* @__PURE__ */ new Map();
3138
- for (const routingId of routingIds) {
3139
- const preferred = pickPreferred(workPredecessors.get(routingId) ?? []);
3140
- if (preferred !== void 0) {
3141
- anchors.set(routingId, preferred);
3142
- }
3143
- }
3144
- let changed = true;
3145
- while (changed) {
3146
- changed = false;
3147
- for (const routingId of routingIds) {
3148
- if (anchors.has(routingId)) {
3149
- continue;
3150
- }
3151
- for (const predecessor of routingPredecessors.get(routingId) ?? []) {
3152
- const predecessorAnchor = anchors.get(predecessor);
3153
- if (predecessorAnchor !== void 0) {
3154
- anchors.set(routingId, predecessorAnchor);
3155
- changed = true;
3156
- break;
3157
- }
3158
- }
3159
- }
3160
- }
3161
- const fallbackWork = [...graph.turns.keys()].find((turnId) => !routingIds.has(turnId));
3162
- if (fallbackWork !== void 0) {
3163
- for (const routingId of routingIds) {
3164
- if (!anchors.has(routingId)) {
3165
- anchors.set(routingId, fallbackWork);
3166
- }
3167
- }
3168
- }
3169
- return anchors;
3170
- }
3171
- function redirectTransition(transition, resolveWork) {
3172
- const label = trimToNull(transition.outcome) ?? trimToNull(transition.trigger);
3173
- if (transition.lifecycleStatus !== void 0) {
3174
- return {
3175
- lifecycleStatus: transition.lifecycleStatus,
3176
- ...label ? { outcome: label } : {}
3177
- };
3178
- }
3179
- const next = transition.nextTurnId;
3180
- if (next === void 0) {
3181
- return { ...label ? { outcome: label } : {} };
3182
- }
3183
- return {
3184
- nextTurnId: resolveWork(next),
3185
- ...label ? { outcome: label } : {}
3186
- };
3187
- }
3188
- function dedupeTransitions(transitions) {
3189
- const seen = /* @__PURE__ */ new Set();
3190
- const result = [];
3191
- for (const transition of transitions) {
3192
- const label = trimToNull(transition.outcome) ?? trimToNull(transition.trigger);
3193
- const key = `${transition.nextTurnId ?? ""}|${transition.lifecycleStatus ?? ""}|${label ?? ""}`;
3194
- if (seen.has(key)) {
3195
- continue;
3196
- }
3197
- seen.add(key);
3198
- result.push(transition);
3199
- }
3200
- return result;
3201
- }
3202
- function collapseRoutingTurns(graph) {
3203
- const routingIds = /* @__PURE__ */ new Set();
3204
- for (const [turnId, turn] of graph.turns) {
3205
- if (isRoutingTurn(turn)) {
3206
- routingIds.add(turnId);
3207
- }
3208
- }
3209
- if (routingIds.size === 0) {
3210
- return graph;
3211
- }
3212
- if (routingIds.size === graph.turns.size) {
3213
- return graph;
3214
- }
3215
- const anchors = computeRoutingAnchors(graph, routingIds);
3216
- const resolveWork = (turnId) => routingIds.has(turnId) ? anchors.get(turnId) ?? turnId : turnId;
3217
- const inheritedByAnchor = /* @__PURE__ */ new Map();
3218
- for (const routingId of routingIds) {
3219
- const anchor = anchors.get(routingId);
3220
- if (anchor === void 0) {
3221
- continue;
3222
- }
3223
- const routingTurn = graph.turns.get(routingId);
3224
- if (!routingTurn) {
3225
- continue;
3226
- }
3227
- const bucket = inheritedByAnchor.get(anchor) ?? [];
3228
- for (const transition of routingTurn.transitions) {
3229
- bucket.push(redirectTransition(transition, resolveWork));
3230
- }
3231
- inheritedByAnchor.set(anchor, bucket);
3232
- }
3233
- const turns = /* @__PURE__ */ new Map();
3234
- for (const [turnId, turn] of graph.turns) {
3235
- if (routingIds.has(turnId)) {
3236
- continue;
3237
- }
3238
- const transitions = [
3239
- ...turn.transitions.map((transition) => redirectTransition(transition, resolveWork)),
3240
- ...inheritedByAnchor.get(turnId) ?? []
3241
- ];
3242
- turns.set(turnId, { ...turn, transitions: dedupeTransitions(transitions) });
3243
- }
3244
- const entryTurnIds = /* @__PURE__ */ new Set();
3245
- for (const entry of graph.entryTurnIds) {
3246
- if (graph.turns.has(entry)) {
3247
- entryTurnIds.add(resolveWork(entry));
3248
- }
3249
- }
3250
- const filteredHappyPath = graph.happyPath?.filter((turnId) => !routingIds.has(turnId)) ?? null;
3251
- return {
3252
- id: graph.id,
3253
- primaryEntryTurnId: resolveWork(graph.primaryEntryTurnId),
3254
- entryTurnIds,
3255
- happyPath: filteredHappyPath && filteredHappyPath.length > 0 ? filteredHappyPath : null,
3256
- turns
3257
- };
3258
- }
3259
- function deriveSpine(graph, entry) {
3260
- const turnsWithCompletedTerminal = /* @__PURE__ */ new Set();
3261
- for (const [turnId, turn] of graph.turns) {
3262
- if (turn.transitions.some((transition) => transition.lifecycleStatus === "completed")) {
3263
- turnsWithCompletedTerminal.add(turnId);
3264
- }
3265
- }
3266
- if (turnsWithCompletedTerminal.size === 0) {
3267
- return [entry];
3268
- }
3269
- const predecessor = /* @__PURE__ */ new Map([[entry, null]]);
3270
- const queue = [entry];
3271
- let goal = null;
3272
- while (queue.length > 0) {
3273
- const current = queue.shift();
3274
- if (turnsWithCompletedTerminal.has(current)) {
3275
- goal = current;
3276
- break;
3277
- }
3278
- const turn = graph.turns.get(current);
3279
- if (!turn) {
3280
- continue;
3281
- }
3282
- for (const transition of turn.transitions) {
3283
- const next = transition.nextTurnId;
3284
- if (next === void 0 || predecessor.has(next) || !graph.turns.has(next)) {
3285
- continue;
3286
- }
3287
- predecessor.set(next, current);
3288
- queue.push(next);
3289
- }
3290
- }
3291
- if (goal === null) {
3292
- return [entry];
3293
- }
3294
- const reversed = [];
3295
- let cursor = goal;
3296
- while (cursor !== null) {
3297
- reversed.push(cursor);
3298
- cursor = predecessor.get(cursor) ?? null;
3299
- }
3300
- return reversed.reverse();
3301
- }
3302
- function deriveBranchAnchors(graph, spineIndexByTurn) {
3303
- const anchorByTurn = /* @__PURE__ */ new Map();
3304
- const orderedSpine = [...spineIndexByTurn.entries()].sort((left, right) => left[1] - right[1]).map(([turnId]) => turnId);
3305
- for (const spineTurnId of orderedSpine) {
3306
- const stack = [spineTurnId];
3307
- const visited = /* @__PURE__ */ new Set([spineTurnId]);
3308
- while (stack.length > 0) {
3309
- const current = stack.pop();
3310
- const turn = graph.turns.get(current);
3311
- if (!turn) {
3312
- continue;
3313
- }
3314
- for (const transition of turn.transitions) {
3315
- const next = transition.nextTurnId;
3316
- if (next === void 0 || !graph.turns.has(next) || visited.has(next)) {
3317
- continue;
3318
- }
3319
- visited.add(next);
3320
- if (spineIndexByTurn.has(next)) {
3321
- continue;
3322
- }
3323
- if (!anchorByTurn.has(next)) {
3324
- anchorByTurn.set(next, spineTurnId);
3325
- }
3326
- stack.push(next);
3327
- }
3328
- }
3329
- }
3330
- return anchorByTurn;
3331
- }
3332
- function transitionLabel(transition) {
3333
- const raw = trimToNull(transition.outcome) ?? trimToNull(transition.trigger);
3334
- return raw === null ? null : humanizeProcessLabel2(raw);
3335
- }
3336
- function buildNode(input) {
3337
- return {
3338
- turnId: input.turnId,
3339
- description: trimToNull(input.turn.description) ?? input.turnId,
3340
- turnType: input.turn.turnType,
3341
- role: input.spineIndex === null ? "branch" : "spine",
3342
- spineIndex: input.spineIndex,
3343
- anchorTurnId: input.spineIndex === null ? input.anchorTurnId : null,
3344
- isEntry: input.isEntry
3345
- };
3346
- }
3347
- function buildProcessFlowView(rawGraph) {
3348
- const graph = collapseRoutingTurns(rawGraph);
3349
- const entryTurnIds = [...graph.entryTurnIds].filter((turnId) => graph.turns.has(turnId));
3350
- const primaryEntry = graph.turns.has(graph.primaryEntryTurnId) ? graph.primaryEntryTurnId : [...graph.turns.keys()][0];
3351
- const declaredSpine = graph.happyPath?.filter((turnId) => graph.turns.has(turnId)) ?? null;
3352
- const spine = declaredSpine && declaredSpine.length > 0 ? [...declaredSpine] : primaryEntry !== void 0 ? deriveSpine(graph, primaryEntry) : [];
3353
- const spineIndexByTurn = /* @__PURE__ */ new Map();
3354
- spine.forEach((turnId, index) => {
3355
- spineIndexByTurn.set(turnId, index);
3356
- });
3357
- const anchorByTurn = deriveBranchAnchors(graph, spineIndexByTurn);
3358
- const entrySet = new Set(entryTurnIds);
3359
- const nodes = [];
3360
- for (const [turnId, turn] of graph.turns) {
3361
- const spineIndex = spineIndexByTurn.get(turnId) ?? null;
3362
- nodes.push(
3363
- buildNode({
3364
- turnId,
3365
- turn,
3366
- spineIndex,
3367
- anchorTurnId: anchorByTurn.get(turnId) ?? null,
3368
- isEntry: entrySet.has(turnId)
3369
- })
3370
- );
3371
- }
3372
- const edges = [];
3373
- const terminalStatuses = /* @__PURE__ */ new Set();
3374
- for (const [turnId, turn] of graph.turns) {
3375
- for (const transition of turn.transitions) {
3376
- const label = transitionLabel(transition);
3377
- if (transition.lifecycleStatus !== void 0) {
3378
- terminalStatuses.add(transition.lifecycleStatus);
3379
- edges.push({
3380
- from: turnId,
3381
- to: null,
3382
- lifecycleStatus: transition.lifecycleStatus,
3383
- kind: "terminal",
3384
- label
3385
- });
3386
- continue;
3387
- }
3388
- const next = transition.nextTurnId;
3389
- if (next === void 0) {
3390
- continue;
3391
- }
3392
- if (next === turnId) {
3393
- continue;
3394
- }
3395
- const fromIndex = spineIndexByTurn.get(turnId);
3396
- const toIndex = spineIndexByTurn.get(next);
3397
- let kind;
3398
- if (fromIndex !== void 0 && toIndex !== void 0) {
3399
- kind = toIndex === fromIndex + 1 ? "forward" : "loopback";
3400
- } else {
3401
- kind = "branch";
3402
- }
3403
- edges.push({ from: turnId, to: next, lifecycleStatus: null, kind, label });
3404
- }
3405
- }
3406
- const endStates = [];
3407
- for (const status of terminalStatuses) {
3408
- endStates.push({ lifecycleStatus: status, synthetic: false });
3409
- }
3410
- if (!terminalStatuses.has("aborted")) {
3411
- endStates.push({ lifecycleStatus: "aborted", synthetic: true });
3412
- }
3413
- endStates.sort((left, right) => left.lifecycleStatus.localeCompare(right.lifecycleStatus));
3414
- return {
3415
- processId: graph.id,
3416
- entryTurnIds,
3417
- spine,
3418
- nodes,
3419
- edges,
3420
- endStates
3421
- };
3422
- }
3423
-
3424
- // src/process-graph.ts
3425
- import { isValidProcessProductName } from "@leitwerk-dev/domain";
3426
- function toTurnType(definition) {
3427
- switch (definition.kind) {
3428
- case "llm":
3429
- case "human":
3430
- case "external":
3431
- case "automatic":
3432
- case "server_automatic":
3433
- return definition.kind;
3434
- }
3435
- }
3436
- function humanPublishedProducts(definition) {
3437
- if (definition.kind !== "human") {
3438
- return [];
3439
- }
3440
- const products = [];
3441
- for (const action of Object.values(definition.actions)) {
3442
- for (const field of action.form?.fields ?? []) {
3443
- if (!field.publish) {
3444
- continue;
3445
- }
3446
- products.push(
3447
- typeof field.publish === "object" && field.publish.product ? field.publish.product : field.id
3448
- );
3449
- }
3450
- }
3451
- for (const externalAction of Object.values(definition.externalActions ?? {})) {
3452
- if (externalAction.publishInput) {
3453
- products.push(externalAction.publishInput.productName);
3454
- }
3455
- }
3456
- return [...new Set(products)];
3457
- }
3458
- function outcomePublishedProducts(definition) {
3459
- if (definition.kind !== "llm" && definition.kind !== "automatic" && definition.kind !== "server_automatic") {
3460
- return [];
3461
- }
3462
- return [
3463
- ...new Set(
3464
- Object.values(definition.outcomes ?? {}).map((outcome) => outcome?.publishedProduct).filter((productName) => typeof productName === "string")
3465
- )
3466
- ];
3467
- }
3468
- function toTurnView(binding) {
3469
- const definition = binding.definition;
3470
- const publishedProducts = [
3471
- .../* @__PURE__ */ new Set([...humanPublishedProducts(definition), ...outcomePublishedProducts(definition)])
3472
- ];
3473
- return {
3474
- turnType: toTurnType(definition),
3475
- description: definition.description,
3476
- transitions: getProcessTurnTransitions(binding),
3477
- ...definition.reviewSubject ? { reviewSubject: { ...definition.reviewSubject } } : {},
3478
- ...definition.kind === "human" && definition.reviewProduct ? { reviewProduct: definition.reviewProduct } : {},
3479
- ...definition.kind === "llm" && definition.resultSemanticRef ? { resultSemanticRef: definition.resultSemanticRef } : {},
3480
- ...definition.kind === "llm" && definition.publishedProduct ? { publishedProduct: definition.publishedProduct } : {},
3481
- ...publishedProducts.length > 0 ? { publishedProducts } : {},
3482
- ...definition.kind === "llm" && definition.consumedProducts?.length ? { consumedProducts: [...definition.consumedProducts] } : {},
3483
- ...definition.kind === "llm" && definition.optionalConsumedProducts?.length ? { optionalConsumedProducts: [...definition.optionalConsumedProducts] } : {},
3484
- ...definition.kind === "llm" && definition.requiredSemanticMarkdownRefs?.length ? { requiredSemanticMarkdownRefs: [...definition.requiredSemanticMarkdownRefs] } : {},
3485
- ...definition.kind === "llm" && definition.optionalSemanticMarkdownRefs?.length ? { optionalSemanticMarkdownRefs: [...definition.optionalSemanticMarkdownRefs] } : {},
3486
- ...definition.kind === "llm" && definition.turnResultMarkdown && "required" in definition.turnResultMarkdown && definition.turnResultMarkdown.required === true ? { turnResultMarkdownRequired: true } : {}
3487
- };
3488
- }
3489
- function toProcessGraphView(definition) {
3490
- const turns = /* @__PURE__ */ new Map();
3491
- for (const [turnId, binding] of definition.turns) {
3492
- turns.set(turnId, toTurnView(binding));
3493
- }
3494
- return {
3495
- id: definition.id,
3496
- primaryEntryTurnId: definition.entryTurnId,
3497
- entryTurnIds: /* @__PURE__ */ new Set([definition.entryTurnId, ...definition.alternateEntryTurnIds ?? []]),
3498
- happyPath: definition.happyPath ? [...definition.happyPath] : null,
3499
- turns
3500
- };
3501
- }
3502
- function hasProcessGraph(registry, processId) {
3503
- return registry.has(processId);
3504
- }
3505
- function getProcessGraph(registry, processId) {
3506
- const definition = registry.get(processId);
3507
- if (!definition) {
3508
- throw new Error(`Unknown process definition: ${processId}`);
3509
- }
3510
- return toProcessGraphView(definition);
3511
- }
3512
- function getAllProcessGraphs(registry) {
3513
- return [...registry.values()].map((definition) => toProcessGraphView(definition));
3514
- }
3515
- function getProcessTurnGraph(registry, processId, turnId) {
3516
- return getProcessGraph(registry, processId).turns.get(turnId);
3517
- }
3518
- function getTurnTransitionsForProcessGraph(registry, processId, turnId) {
3519
- return getProcessTurnGraph(registry, processId, turnId)?.transitions ?? [];
3520
- }
3521
- function getReachableTurnIdsForProcessGraph(registry, processId) {
3522
- return [...getProcessGraph(registry, processId).turns.keys()];
3523
- }
3524
- function isTurnAvailableForProcessGraph(registry, processId, turnId) {
3525
- return getProcessGraph(registry, processId).turns.has(turnId);
3526
- }
3527
- function serializeProcessGraph(registry, processId) {
3528
- const definition = getProcessGraph(registry, processId);
3529
- const turnTransitions = {};
3530
- for (const [turnId, turn] of definition.turns) {
3531
- turnTransitions[turnId] = turn.transitions.map((transition) => ({ ...transition }));
3532
- }
3533
- return {
3534
- id: definition.id,
3535
- entryTurnIds: [...definition.entryTurnIds],
3536
- reachableTurnIds: [...definition.turns.keys()],
3537
- turnTransitions
3538
- };
3539
- }
3540
- function listLlmTurnIdsForProcessGraph(registry, processId) {
3541
- return [...getProcessGraph(registry, processId).turns.entries()].filter(([, turn]) => turn.turnType === "llm").map(([turnId]) => turnId);
3542
- }
3543
- function isTerminalLifecycleStatus(value) {
3544
- return value === "completed" || value === "aborted";
3545
- }
3546
- function validateProcessGraphEntryTurns(graph) {
3547
- const errors = [];
3548
- for (const turnId of graph.entryTurnIds) {
3549
- if (!graph.turns.has(turnId)) {
3550
- errors.push(`Entry turn '${turnId}' is not declared in turns`);
3551
- }
3552
- }
3553
- return errors;
3554
- }
3555
- function validateProcessGraphProducts(graph) {
3556
- const errors = [];
3557
- const publishedProducts = /* @__PURE__ */ new Set();
3558
- for (const [turnId, turn] of graph.turns) {
3559
- const productNames = [
3560
- ...turn.publishedProduct ? [turn.publishedProduct] : [],
3561
- ...turn.publishedProducts ?? []
3562
- ];
3563
- for (const productName of productNames) {
3564
- if (!isValidProcessProductName(productName)) {
3565
- errors.push(`Turn '${turnId}' publishes invalid product '${productName}'`);
3566
- continue;
3567
- }
3568
- publishedProducts.add(productName);
3569
- }
3570
- }
3571
- for (const [turnId, turn] of graph.turns) {
3572
- for (const productName of [
3573
- ...turn.consumedProducts ?? [],
3574
- ...turn.optionalConsumedProducts ?? []
3575
- ]) {
3576
- if (!isValidProcessProductName(productName)) {
3577
- errors.push(`Turn '${turnId}' consumes invalid product '${productName}'`);
3578
- continue;
3579
- }
3580
- if (!publishedProducts.has(productName)) {
3581
- errors.push(
3582
- `Turn '${turnId}' consumes product '${productName}' that is never published by this process`
3583
- );
3584
- }
3585
- }
3586
- }
3587
- return errors;
3588
- }
3589
- function validateProcessGraphTurnTransitions(graph) {
3590
- const errors = [];
3591
- for (const [turnId, turn] of graph.turns) {
3592
- for (const transition of turn.transitions) {
3593
- const hasNextTurn = transition.nextTurnId !== void 0;
3594
- const hasLifecycleStatus = transition.lifecycleStatus !== void 0;
3595
- if (hasNextTurn === hasLifecycleStatus) {
3596
- errors.push(
3597
- `Turn transition from '${turnId}' must declare exactly one target: nextTurnId or lifecycleStatus`
3598
- );
3599
- continue;
3600
- }
3601
- if (transition.nextTurnId !== void 0 && !graph.turns.has(transition.nextTurnId)) {
3602
- errors.push(
3603
- `Turn transition from '${turnId}' references undeclared nextTurnId '${transition.nextTurnId}'`
3604
- );
3605
- }
3606
- if (transition.lifecycleStatus !== void 0 && !isTerminalLifecycleStatus(transition.lifecycleStatus)) {
3607
- errors.push(
3608
- `Turn transition from '${turnId}' references invalid lifecycleStatus '${transition.lifecycleStatus}'`
3609
- );
3610
- }
3611
- }
3612
- }
3613
- return errors;
3614
- }
3615
-
3616
- // src/process-launcher-builder.ts
3617
- function validateLauncherDefinition(def) {
3618
- if (!def.id.trim()) {
3619
- throw new Error("Launcher id is required");
3620
- }
3621
- if (!def.label.trim()) {
3622
- throw new Error(`Launcher '${def.id}' must define a non-empty label`);
3623
- }
3624
- if (!def.description.trim()) {
3625
- throw new Error(`Launcher '${def.id}' must define a non-empty description`);
3626
- }
3627
- if (def.visibility !== "ui") {
3628
- throw new Error(`Launcher '${def.id}' has unsupported visibility`);
3629
- }
3630
- if (!def.ui) {
3631
- throw new Error(`UI launcher '${def.id}' must define a ui block`);
3632
- }
3633
- }
3634
- function createProcessLauncherBuilder() {
3635
- const launchers = /* @__PURE__ */ new Map();
3636
- return {
3637
- launcher(def) {
3638
- registerUnique(launchers, def.id, def, {
3639
- duplicateMessage: `Launcher '${def.id}' is already registered`,
3640
- validate: validateLauncherDefinition
3641
- });
3642
- },
3643
- getDefinition() {
3644
- return {
3645
- launchers: cloneMap(launchers)
3646
- };
3647
- }
3648
- };
3649
- }
3650
- function buildProcessLaunchers(process2) {
3651
- if (!process2.launchers) {
3652
- return void 0;
3653
- }
3654
- const builder = createProcessLauncherBuilder();
3655
- process2.launchers(builder);
3656
- return builder.getDefinition();
3657
- }
3658
-
3659
- // src/process-watcher-builder.ts
3660
- function validateWatcherDefinition(def) {
3661
- if (!def.id.trim()) {
3662
- throw new Error("Process watcher id is required");
3663
- }
3664
- if (!def.label.trim()) {
3665
- throw new Error(`Process watcher '${def.id}' must define a non-empty label`);
3666
- }
3667
- if (!def.description.trim()) {
3668
- throw new Error(`Process watcher '${def.id}' must define a non-empty description`);
3669
- }
3670
- if (def.type !== "jira" && def.type !== "gitlab_mr" && def.type !== "filesystem") {
3671
- throw new Error(`Process watcher '${def.id}' has unsupported type '${String(def.type)}'`);
3672
- }
3673
- }
3674
- function createProcessWatcherBuilder() {
3675
- const watchers = /* @__PURE__ */ new Map();
3676
- return {
3677
- watcher(def) {
3678
- registerUnique(
3679
- watchers,
3680
- def.id,
3681
- def,
3682
- {
3683
- duplicateMessage: `Process watcher '${def.id}' is already registered`,
3684
- validate: validateWatcherDefinition
3685
- }
3686
- );
3687
- },
3688
- getDefinition() {
3689
- return {
3690
- watchers: cloneMap(watchers)
3691
- };
3692
- }
3693
- };
3694
- }
3695
- function buildProcessWatchers(process2) {
3696
- if (!process2.watchers) {
3697
- return void 0;
3698
- }
3699
- const builder = createProcessWatcherBuilder();
3700
- process2.watchers(builder);
3701
- return builder.getDefinition();
3702
- }
3703
-
3704
- // src/subprocess-env.ts
3705
- import {
3706
- WORKER_IPC_CONNECT_TOKEN_ENV,
3707
- WORKER_IPC_RECONNECT_ENV,
3708
- WORKER_SNAPSHOT_TOKEN_ENV
3709
- } from "@leitwerk-dev/worker-protocol";
3710
- var INTERNAL_REPOSITORY_GIT_SSH_ENV_PREFIX = "LEITWERK_INTERNAL_REPOSITORY_GIT_SSH_";
3711
- var WORKER_SUBPROCESS_SENSITIVE_ENV_KEYS = [
3712
- WORKER_IPC_CONNECT_TOKEN_ENV,
3713
- WORKER_IPC_RECONNECT_ENV,
3714
- WORKER_SNAPSHOT_TOKEN_ENV
3715
- ];
3716
- var SENSITIVE_ENV_KEYS = /* @__PURE__ */ new Set([
3717
- ...WORKER_SUBPROCESS_SENSITIVE_ENV_KEYS,
3718
- "SSH_AUTH_SOCK",
3719
- "SSH_AGENT_PID",
3720
- "GIT_SSH",
3721
- "GIT_SSH_COMMAND"
3722
- ]);
3723
- function sanitizeWorkerSubprocessEnv(baseEnv = process.env, overrides = {}) {
3724
- const sanitized = {};
3725
- for (const [key, value] of Object.entries({ ...baseEnv, ...overrides })) {
3726
- if (SENSITIVE_ENV_KEYS.has(key) || key.startsWith(INTERNAL_REPOSITORY_GIT_SSH_ENV_PREFIX) || value === void 0) {
3727
- continue;
3728
- }
3729
- sanitized[key] = value;
3730
- }
3731
- return sanitized;
3732
- }
3733
-
3734
- // src/repository-git-env.ts
3735
- function wrapperKey(projectKey) {
3736
- return `${INTERNAL_REPOSITORY_GIT_SSH_ENV_PREFIX}${encodeURIComponent(projectKey).replace(/%/g, "_")}`;
3737
- }
3738
- function setRepositoryGitSshWrapper(projectKey, wrapperPath) {
3739
- process.env[wrapperKey(projectKey)] = wrapperPath;
3740
- }
3741
- function clearRepositoryGitSshWrappers() {
3742
- for (const key of Object.keys(process.env)) {
3743
- if (key.startsWith(INTERNAL_REPOSITORY_GIT_SSH_ENV_PREFIX)) delete process.env[key];
3744
- }
3745
- }
3746
- function repositoryGitSubprocessEnv(projectKey, overrides = {}) {
3747
- const env = sanitizeWorkerSubprocessEnv(process.env, overrides);
3748
- const wrapper = process.env[wrapperKey(projectKey)];
3749
- if (wrapper) env.GIT_SSH = wrapper;
3750
- return env;
3751
- }
3752
- function repositoryGitArgs(args) {
3753
- return ["-c", "core.hooksPath=/dev/null", ...args];
3754
- }
3755
-
3756
- // src/turn-semantics.ts
3757
- import {
3758
- assertValidProcessProductName as assertValidProcessProductName3,
3759
- defaultProcessTurnStartSelection,
3760
- resolveProcessTurnStartSelection
3761
- } from "@leitwerk-dev/domain";
3762
-
3763
- // src/tool-renderers.ts
3764
- import {
3765
- TOOL_CALL_RENDERER_VALUE_KINDS,
3766
- TOOL_CALL_RENDERER_VALUE_SOURCES
3767
- } from "@leitwerk-dev/protocol/tool-renderer-contract";
3768
- var MARKDOWN_RESULT_TOOL_NAME = "markdown_result";
3769
- var MARKDOWN_RESULT_TOOL_MARKDOWN_PATH = "markdown";
3770
- var MARKDOWN_RESULT_TOOL_RENDERER = {
3771
- toolName: MARKDOWN_RESULT_TOOL_NAME,
3772
- title: "Markdown result",
3773
- fields: [
3774
- {
3775
- id: "markdown",
3776
- label: "Rendered markdown",
3777
- kind: "markdown",
3778
- source: "arguments",
3779
- path: MARKDOWN_RESULT_TOOL_MARKDOWN_PATH
3780
- }
3781
- ]
3782
- };
3783
- var CORE_TOOL_CALL_RENDERERS = [
3784
- MARKDOWN_RESULT_TOOL_RENDERER
3785
- ];
3786
- var REQUIRED_MARKDOWN_RESULT_TURN_RESULT = {
3787
- mode: "tool_call",
3788
- toolName: MARKDOWN_RESULT_TOOL_NAME,
3789
- path: MARKDOWN_RESULT_TOOL_MARKDOWN_PATH,
3790
- required: true
3791
- };
3792
- function isNonEmptyString2(value) {
3793
- return typeof value === "string" && value.trim() !== "";
3794
- }
3795
- function validateToolCallRendererDefinition(def) {
3796
- const errors = [];
3797
- if (!isNonEmptyString2(def.toolName)) {
3798
- errors.push("Tool renderer must declare a non-empty toolName");
3799
- }
3800
- if (!Array.isArray(def.fields) || def.fields.length === 0) {
3801
- errors.push(`Tool renderer '${def.toolName}' must declare at least one field`);
3802
- return errors;
3803
- }
3804
- const fieldIds = /* @__PURE__ */ new Set();
3805
- for (const field of def.fields) {
3806
- if (!isNonEmptyString2(field.id)) {
3807
- errors.push(`Tool renderer '${def.toolName}' contains a field with an empty id`);
3808
- }
3809
- if (fieldIds.has(field.id)) {
3810
- errors.push(`Tool renderer '${def.toolName}' contains duplicate field id '${field.id}'`);
3811
- }
3812
- fieldIds.add(field.id);
3813
- if (!isNonEmptyString2(field.label)) {
3814
- errors.push(
3815
- `Tool renderer '${def.toolName}' field '${field.id}' must declare a non-empty label`
3816
- );
3817
- }
3818
- if (!TOOL_CALL_RENDERER_VALUE_KINDS.includes(field.kind)) {
3819
- errors.push(
3820
- `Tool renderer '${def.toolName}' field '${field.id}' uses unknown kind '${String(field.kind)}'`
3821
- );
3822
- }
3823
- if (!TOOL_CALL_RENDERER_VALUE_SOURCES.includes(field.source)) {
3824
- errors.push(
3825
- `Tool renderer '${def.toolName}' field '${field.id}' uses unknown source '${String(field.source)}'`
3826
- );
3827
- }
3828
- if (field.path !== void 0 && !isNonEmptyString2(field.path)) {
3829
- errors.push(
3830
- `Tool renderer '${def.toolName}' field '${field.id}' path must be non-empty when provided`
3831
- );
3832
- }
3833
- }
3834
- return errors;
3835
- }
3836
-
3837
- // src/turn-semantics.ts
3838
- function isLlmTurnDefinition(turnDef) {
3839
- return turnDef.kind === "llm";
3840
- }
3841
- function isAutomaticTurnDefinition(turnDef) {
3842
- return turnDef.kind === "automatic";
3843
- }
3844
- function isServerAutomaticTurnDefinition(turnDef) {
3845
- return turnDef.kind === "server_automatic";
3846
- }
3847
- function isHumanTurnDefinition(turnDef) {
3848
- return turnDef.kind === "human";
3849
- }
3850
- function isExternalTurnDefinition(turnDef) {
3851
- return turnDef.kind === "external";
3852
- }
3853
- function defaultTurnStartSelection(branchType) {
3854
- return defaultProcessTurnStartSelection(branchType);
3855
- }
3856
- function resolveLlmTurnStartSelection(turnDef) {
3857
- return resolveProcessTurnStartSelection(turnDef);
3858
- }
3859
- function resolveLlmTurnRestorePrimaryLeafAfterTurn(turnDef) {
3860
- return turnDef.restorePrimaryLeafAfterTurn ?? turnDef.branchType !== "primary";
3861
- }
3862
- function validateProcessActionPreviewDefinition(preview, context) {
3863
- if (!preview) {
3864
- return [];
3865
- }
3866
- if (preview.kind === "trigger") {
3867
- return preview.trigger.trim() ? [] : [`${context} must declare a non-empty trigger preview`];
3868
- }
3869
- if (preview.kind === "terminal") {
3870
- return [];
3871
- }
3872
- if (preview.turnId === null || preview.turnId.trim()) {
3873
- return [];
3874
- }
3875
- return [`${context} must declare a non-empty fixed turn id when turnId is not null`];
3876
- }
3877
- function validateProcessActionSchedulingDefinition(scheduling, context) {
3878
- return validateProcessActionPreviewDefinition(scheduling?.preview, context);
3879
- }
3880
- function hasDuplicateBy(items, selectKey) {
3881
- const ids = /* @__PURE__ */ new Set();
3882
- for (const item of items) {
3883
- const key = selectKey(item);
3884
- if (ids.has(key)) {
3885
- return true;
3886
- }
3887
- ids.add(key);
3888
- }
3889
- return false;
3890
- }
3891
- function validateOutcomeTurnResultContract(turnKindLabel, turnId, outcomes, turnEnd) {
3892
- const errors = [];
3893
- const hasOutcomeTools = Object.keys(outcomes ?? {}).length > 0;
3894
- const hasTurnEndResult = turnEnd !== void 0;
3895
- if (!hasOutcomeTools && !hasTurnEndResult) {
3896
- errors.push(
3897
- `${turnKindLabel} turn '${turnId}' must declare at least one outcome tool or a turnEnd result`
3898
- );
3899
- }
3900
- if (hasOutcomeTools && hasTurnEndResult) {
3901
- errors.push(`${turnKindLabel} turn '${turnId}' cannot declare both outcomes and turnEnd`);
3902
- }
3903
- return errors;
3904
- }
3905
- function isValidOutcomeToolArrayItemType(type) {
3906
- return type === "string" || type === "number" || type === "boolean" || type === "object";
3907
- }
3908
- function validateOutcomeToolParameters(turnKindLabel, turnId, outcomes) {
3909
- const errors = [];
3910
- for (const [outcome, outcomeSpec] of Object.entries(outcomes ?? {})) {
3911
- if (outcomeSpec.publishedProduct) {
3912
- try {
3913
- assertValidProcessProductName3(outcomeSpec.publishedProduct);
3914
- } catch (error) {
3915
- errors.push(error instanceof Error ? error.message : String(error));
3916
- }
3917
- const parameterName = outcomeSpec.turnResultMarkdownParameter?.trim() ?? "";
3918
- if (!parameterName) {
3919
- errors.push(
3920
- `${turnKindLabel} turn '${turnId}' outcome '${outcome}' publishes product '${outcomeSpec.publishedProduct}' but does not declare a turn-result markdown parameter`
3921
- );
3922
- } else if (!Object.hasOwn(outcomeSpec.parameters, parameterName)) {
3923
- errors.push(
3924
- `${turnKindLabel} turn '${turnId}' outcome '${outcome}' publishes product '${outcomeSpec.publishedProduct}' from missing parameter '${parameterName}'`
3925
- );
3926
- }
3927
- }
3928
- for (const [paramName, paramSpec] of Object.entries(outcomeSpec.parameters)) {
3929
- if (paramSpec.minItems !== void 0 && paramSpec.type !== "array") {
3930
- errors.push(
3931
- `${turnKindLabel} turn '${turnId}' outcome '${outcome}' parameter '${paramName}' uses minItems but is not an array`
3932
- );
3933
- }
3934
- if (paramSpec.minimum !== void 0 && paramSpec.type !== "number") {
3935
- errors.push(
3936
- `${turnKindLabel} turn '${turnId}' outcome '${outcome}' parameter '${paramName}' uses minimum but is not a number`
3937
- );
3938
- }
3939
- if (paramSpec.items !== void 0 && paramSpec.type !== "array") {
3940
- errors.push(
3941
- `${turnKindLabel} turn '${turnId}' outcome '${outcome}' parameter '${paramName}' declares array items but is not an array`
3942
- );
3943
- }
3944
- if (paramSpec.type === "array") {
3945
- if (!paramSpec.items) {
3946
- errors.push(
3947
- `${turnKindLabel} turn '${turnId}' outcome '${outcome}' parameter '${paramName}' is an array and must declare items`
3948
- );
3949
- } else if (!isValidOutcomeToolArrayItemType(paramSpec.items.type)) {
3950
- errors.push(
3951
- `${turnKindLabel} turn '${turnId}' outcome '${outcome}' parameter '${paramName}' declares unsupported array item type '${String(paramSpec.items.type)}'`
3952
- );
3953
- }
3954
- }
3955
- }
3956
- }
3957
- return errors;
3958
- }
3959
- function assertNoValidationErrors(errors) {
3960
- if (errors.length > 0) {
3961
- throw new Error(errors.join("; "));
3962
- }
3963
- }
3964
- function validateTurnStartSelection(turnId, startFrom, context = "startFrom") {
3965
- const errors = [];
3966
- if (startFrom.kind === "entry" && startFrom.entryId.trim() === "") {
3967
- errors.push(`LLM turn '${turnId}' ${context} entry id must be non-empty`);
3968
- }
3969
- if (startFrom.kind === "product_ref") {
3970
- try {
3971
- assertValidProcessProductName3(startFrom.productName);
3972
- } catch (error) {
3973
- errors.push(error instanceof Error ? error.message : String(error));
3974
- }
3975
- }
3976
- if ("fallback" in startFrom && startFrom.fallback) {
3977
- errors.push(...validateTurnStartSelection(turnId, startFrom.fallback, `${context} fallback`));
3978
- }
3979
- return errors;
3980
- }
3981
- function validateLlmTurnDefinition(turnId, turnDef) {
3982
- const errors = [];
3983
- const declaredOutcomes = turnDef.outcomes;
3984
- const startFrom = resolveLlmTurnStartSelection(turnDef);
3985
- if ((turnDef.completionMode ?? "turn_end") !== "turn_end") {
3986
- errors.push(`LLM turn '${turnId}' must use completionMode 'turn_end'`);
3987
- }
3988
- const declaredTurnEnd = turnDef.turnEnd;
3989
- errors.push(
3990
- ...validateOutcomeTurnResultContract("LLM", turnId, declaredOutcomes, declaredTurnEnd)
3991
- );
3992
- if (turnDef.branchType === "root_branch" && startFrom.kind === "current_leaf") {
3993
- errors.push(
3994
- `LLM turn '${turnId}' uses branchType 'root_branch' but starts from the current leaf`
3995
- );
3996
- }
3997
- if (turnDef.branchType === "leaf_branch" && startFrom.kind === "session_root") {
3998
- errors.push(
3999
- `LLM turn '${turnId}' uses branchType 'leaf_branch' but starts from the session root`
4000
- );
4001
- }
4002
- errors.push(...validateTurnStartSelection(turnId, startFrom));
4003
- if (turnDef.askQuestions !== void 0 && turnDef.askQuestions !== true) {
4004
- errors.push(`LLM turn '${turnId}' askQuestions must be true when declared`);
4005
- }
4006
- if (!Array.isArray(turnDef.availableTools)) {
4007
- errors.push(`LLM turn '${turnId}' must declare availableTools as an array`);
4008
- } else {
4009
- errors.push(
4010
- ...validatePiBuiltInToolArray(turnDef.availableTools, `LLM turn '${turnId}' availableTools`)
4011
- );
4012
- }
4013
- if (turnDef.turnResultMarkdown?.mode === "tool_call") {
4014
- if (turnDef.turnResultMarkdown.toolName.trim() === "") {
4015
- errors.push(
4016
- `LLM turn '${turnId}' tool-call turnResultMarkdown must use a non-empty toolName`
4017
- );
4018
- }
4019
- if (turnDef.turnResultMarkdown.path.trim() === "") {
4020
- errors.push(`LLM turn '${turnId}' tool-call turnResultMarkdown must use a non-empty path`);
4021
- }
4022
- }
4023
- if (turnDef.turnResultMarkdown?.mode === "outcome_tool_argument") {
4024
- const parameterName = turnDef.turnResultMarkdown.parameterName.trim();
4025
- const outcomeEntries = Object.entries(declaredOutcomes ?? {});
4026
- if (parameterName === "") {
4027
- errors.push(
4028
- `LLM turn '${turnId}' outcome-tool turnResultMarkdown must use a non-empty parameterName`
4029
- );
4030
- }
4031
- if (outcomeEntries.length === 0) {
4032
- errors.push(
4033
- `LLM turn '${turnId}' outcome-tool turnResultMarkdown requires at least one outcome tool`
4034
- );
4035
- }
4036
- for (const [outcomeId, spec] of outcomeEntries) {
4037
- if (parameterName in spec.parameters) {
4038
- errors.push(
4039
- `LLM turn '${turnId}' outcome tool '${outcomeId}' cannot declare reserved markdown parameter '${parameterName}'`
4040
- );
4041
- }
4042
- }
4043
- }
4044
- errors.push(...validateOutcomeToolParameters("LLM", turnId, declaredOutcomes));
4045
- return errors;
4046
- }
4047
- function validateAutomaticTurnDefinition(turnId, turnDef) {
4048
- const errors = [];
4049
- const declaredOutcomes = turnDef.outcomes;
4050
- const declaredTurnEnd = turnDef.turnEnd;
4051
- errors.push(
4052
- ...validateOutcomeTurnResultContract("Automatic", turnId, declaredOutcomes, declaredTurnEnd)
4053
- );
4054
- errors.push(...validateOutcomeToolParameters("Automatic", turnId, declaredOutcomes));
4055
- return errors;
4056
- }
4057
- function validateHumanTurnDefinition(turnId, turnDef) {
4058
- const errors = [];
4059
- try {
4060
- resolveHumanTurnView({ turnId, turn: turnDef });
4061
- } catch (error) {
4062
- errors.push(error instanceof Error ? error.message : String(error));
4063
- }
4064
- if (turnDef.reviewProduct) {
4065
- try {
4066
- assertValidProcessProductName3(turnDef.reviewProduct);
4067
- } catch (error) {
4068
- errors.push(error instanceof Error ? error.message : String(error));
4069
- }
4070
- }
4071
- const actionEntries = Object.entries(turnDef.actions);
4072
- if (actionEntries.length === 0) {
4073
- errors.push(`Human turn '${turnId}' must declare at least one action`);
4074
- }
4075
- for (const [actionId, action] of actionEntries) {
4076
- if (!action.acceptanceState) {
4077
- errors.push(`Human turn '${turnId}' is missing an acceptance state for action '${actionId}'`);
4078
- }
4079
- errors.push(
4080
- ...validateProcessActionPreviewDefinition(
4081
- action.preview,
4082
- `Human turn '${turnId}' action '${actionId}' preview`
4083
- )
4084
- );
4085
- }
4086
- const externalTriggers = actionEntries.flatMap(
4087
- ([actionId, action]) => (action.externalTriggers ?? []).map((trigger) => ({ actionId, trigger }))
4088
- );
4089
- if (hasDuplicateBy(externalTriggers, ({ trigger }) => trigger.id)) {
4090
- errors.push(`Human turn '${turnId}' contains duplicate external trigger ids`);
4091
- }
4092
- if (hasDuplicateBy(externalTriggers, ({ actionId }) => actionId)) {
4093
- errors.push(`Human turn '${turnId}' contains duplicate external trigger action ids`);
4094
- }
4095
- for (const { actionId, trigger } of externalTriggers) {
4096
- if (trigger.id.trim() === "") {
4097
- errors.push(`Human turn '${turnId}' contains an external trigger with an empty id`);
4098
- }
4099
- if (actionId.trim() === "") {
4100
- errors.push(
4101
- `Human turn '${turnId}' external trigger '${trigger.id}' must declare a non-empty actionId`
4102
- );
4103
- }
4104
- if (trigger.label.trim() === "") {
4105
- errors.push(
4106
- `Human turn '${turnId}' external trigger '${trigger.id}' must declare a non-empty label`
4107
- );
4108
- }
4109
- if (trigger.description.trim() === "") {
4110
- errors.push(
4111
- `Human turn '${turnId}' external trigger '${trigger.id}' must declare a non-empty description`
4112
- );
4113
- }
4114
- }
4115
- const externalActionEntries = Object.entries(turnDef.externalActions ?? {});
4116
- if (hasDuplicateBy(externalActionEntries, ([externalActionId]) => externalActionId)) {
4117
- errors.push(`Human turn '${turnId}' contains duplicate external action ids`);
4118
- }
4119
- for (const [externalActionId, externalAction] of externalActionEntries) {
4120
- if (externalActionId.trim() === "") {
4121
- errors.push(`Human turn '${turnId}' contains an external action with an empty id`);
4122
- }
4123
- if (externalAction.id !== externalActionId) {
4124
- errors.push(
4125
- `Human turn '${turnId}' external action '${externalActionId}' has mismatched id '${externalAction.id}'`
4126
- );
4127
- }
4128
- if (externalAction.source.kind.trim() === "") {
4129
- errors.push(
4130
- `Human turn '${turnId}' external action '${externalActionId}' must declare a non-empty source kind`
4131
- );
4132
- }
4133
- const targetCount = (externalAction.to !== void 0 ? 1 : 0) + (externalAction.complete === true ? 1 : 0) + (externalAction.lifecycleStatus !== void 0 ? 1 : 0);
4134
- if (targetCount !== 1) {
4135
- errors.push(
4136
- `Human turn '${turnId}' external action '${externalActionId}' must declare exactly one target`
4137
- );
4138
- }
4139
- if (externalAction.publishInput) {
4140
- try {
4141
- assertValidProcessProductName3(externalAction.publishInput.productName);
4142
- } catch (error) {
4143
- errors.push(error instanceof Error ? error.message : String(error));
4144
- }
4145
- if (externalAction.publishInput.inputField.trim() === "") {
4146
- errors.push(
4147
- `Human turn '${turnId}' external action '${externalActionId}' publishInput must declare a non-empty inputField`
4148
- );
4149
- }
4150
- if (externalAction.complete === true || externalAction.lifecycleStatus !== void 0) {
4151
- errors.push(
4152
- `Human turn '${turnId}' external action '${externalActionId}' cannot publish input on a terminal route`
4153
- );
4154
- }
4155
- }
4156
- }
4157
- const notesFields = turnDef.notesFields ?? [];
4158
- if (hasDuplicateBy(notesFields, (field) => field.id)) {
4159
- const noteIds = /* @__PURE__ */ new Set();
4160
- for (const field of notesFields) {
4161
- if (noteIds.has(field.id)) {
4162
- errors.push(`Human turn '${turnId}' contains duplicate notes field id '${field.id}'`);
4163
- break;
4164
- }
4165
- noteIds.add(field.id);
4166
- }
4167
- }
4168
- return errors;
4169
- }
4170
- function validateExternalTurnDefinition(turnId, turnDef) {
4171
- const errors = [];
4172
- if (turnDef.transitions.length === 0) {
4173
- errors.push(`External turn '${turnId}' must declare at least one source transition`);
4174
- }
4175
- for (const [index, transition] of turnDef.transitions.entries()) {
4176
- if (transition.source.kind.trim() === "") {
4177
- errors.push(
4178
- `External turn '${turnId}' source transition ${index} must declare a non-empty kind`
4179
- );
4180
- }
4181
- const targetCount = (transition.to !== void 0 ? 1 : 0) + (transition.complete === true ? 1 : 0) + (transition.lifecycleStatus !== void 0 ? 1 : 0);
4182
- if (targetCount !== 1) {
4183
- errors.push(
4184
- `External turn '${turnId}' source transition ${index} must declare exactly one target`
4185
- );
4186
- }
4187
- }
4188
- return errors;
4189
- }
4190
- function validateTurnDefinition(turnIdOrDef, turnDef) {
4191
- const effectiveTurnDef = typeof turnIdOrDef === "string" ? turnDef : turnIdOrDef;
4192
- const effectiveTurnId = typeof turnIdOrDef === "string" ? turnIdOrDef : turnIdOrDef.id ?? "unknown_turn";
4193
- if (!effectiveTurnDef) {
4194
- return ["Turn definition is required"];
4195
- }
4196
- return isLlmTurnDefinition(effectiveTurnDef) ? validateLlmTurnDefinition(effectiveTurnId, effectiveTurnDef) : isAutomaticTurnDefinition(effectiveTurnDef) || isServerAutomaticTurnDefinition(effectiveTurnDef) ? validateAutomaticTurnDefinition(effectiveTurnId, effectiveTurnDef) : isHumanTurnDefinition(effectiveTurnDef) ? validateHumanTurnDefinition(effectiveTurnId, effectiveTurnDef) : validateExternalTurnDefinition(effectiveTurnId, effectiveTurnDef);
4197
- }
4198
- function assertValidLlmTurnDefinition(turnId, turnDef) {
4199
- assertNoValidationErrors(validateLlmTurnDefinition(turnId, turnDef));
4200
- }
4201
- function createRootBranchReviewTurn(def) {
4202
- const {
4203
- completionMode = "turn_end",
4204
- startFrom = { kind: "session_root" },
4205
- restorePrimaryLeafAfterTurn = true,
4206
- turnResultMarkdown = REQUIRED_MARKDOWN_RESULT_TURN_RESULT,
4207
- ...rest
4208
- } = def;
4209
- return llmTurn({
4210
- completionMode,
4211
- branchType: "root_branch",
4212
- startFrom,
4213
- restorePrimaryLeafAfterTurn,
4214
- turnResultMarkdown,
4215
- ...rest
4216
- });
4217
- }
4218
-
4219
- // src/server-process-builder.ts
4220
- function createServerProcessBuilder() {
4221
- const actions = /* @__PURE__ */ new Map();
4222
- const turnOutcomeHandlers = /* @__PURE__ */ new Map();
4223
- const cleanupHandlers = [];
4224
- return {
4225
- action(def) {
4226
- registerUnique(actions, def.id, def, {
4227
- duplicateMessage: `Process action '${def.id}' is already registered`,
4228
- validate: (value) => {
4229
- if (!value.plan && !value.execute) {
4230
- throw new Error(
4231
- `Process action '${value.id}' must declare plan(...) or side-effect execute(...)`
4232
- );
4233
- }
4234
- if (value.execute && !value.plan && value.executionMode !== "side_effect") {
4235
- throw new Error(
4236
- `Process action '${value.id}' with execute(...) must set executionMode: "side_effect"`
4237
- );
4238
- }
4239
- if (value.executionMode === "side_effect" && !value.execute) {
4240
- throw new Error(
4241
- `Process action '${value.id}' with executionMode: "side_effect" must declare execute(...)`
4242
- );
4243
- }
4244
- if (value.executionMode === "side_effect" && value.scheduling) {
4245
- throw new Error(
4246
- `Process action '${value.id}' with executionMode: "side_effect" cannot declare scheduling metadata`
4247
- );
4248
- }
4249
- const previewErrors = validateProcessActionPreviewDefinition(
4250
- value.preview,
4251
- `Process action '${value.id}' preview`
4252
- );
4253
- if (previewErrors.length > 0) {
4254
- throw new Error(previewErrors.join("; "));
4255
- }
4256
- const schedulingErrors = validateProcessActionSchedulingDefinition(
4257
- value.scheduling,
4258
- `Process action '${value.id}' scheduling`
4259
- );
4260
- if (schedulingErrors.length > 0) {
4261
- throw new Error(schedulingErrors.join("; "));
4262
- }
4263
- }
4264
- });
4265
- },
4266
- onTurnOutcome(turnId, handler) {
4267
- const handlers = turnOutcomeHandlers.get(turnId) ?? [];
4268
- handlers.push(handler);
4269
- turnOutcomeHandlers.set(turnId, handlers);
4270
- },
4271
- onCleanup(handler) {
4272
- cleanupHandlers.push(handler);
4273
- },
4274
- getDefinition() {
4275
- return {
4276
- actions: cloneMap(actions),
4277
- turnOutcomeHandlers: cloneArrayValueMap(turnOutcomeHandlers),
4278
- cleanupHandlers: [...cleanupHandlers]
4279
- };
4280
- }
4281
- };
4282
- }
4283
-
4284
- // src/state-helpers.ts
4285
- import {
4286
- createEmptyProcessProductRefs,
4287
- createEmptyProcessSemanticEntryRefs,
4288
- parseProcessProductRefs,
4289
- parseProcessSemanticEntryRefs,
4290
- parseReviewSubject
4291
- } from "@leitwerk-dev/domain";
4292
- function createEmptyStructuralProcessState() {
4293
- return {
4294
- semanticEntryRefs: createEmptyProcessSemanticEntryRefs(),
4295
- productRefs: createEmptyProcessProductRefs(),
4296
- reviewSubject: null
4297
- };
4298
- }
4299
- function parseStructuralProcessState(value) {
4300
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
4301
- return createEmptyStructuralProcessState();
4302
- }
4303
- const record2 = value;
4304
- return {
4305
- semanticEntryRefs: parseProcessSemanticEntryRefs(record2.semanticEntryRefs),
4306
- productRefs: parseProcessProductRefs(record2.productRefs),
4307
- reviewSubject: parseReviewSubject(record2.reviewSubject)
4308
- };
4309
- }
4310
-
4311
- // src/ui-process-builder.ts
4312
- function createUiProcessBuilder() {
4313
- let leafOutcome = null;
4314
- return {
4315
- leafOutcome(def) {
4316
- if (leafOutcome) {
4317
- throw new Error("Leaf outcome is already registered");
4318
- }
4319
- const validationErrors = validateProcessLeafOutcomeDefinition(def);
4320
- if (validationErrors.length > 0) {
4321
- throw new Error(validationErrors.join("; "));
4322
- }
4323
- leafOutcome = def;
4324
- },
4325
- getDefinition() {
4326
- return {
4327
- leafOutcome
4328
- };
4329
- }
4330
- };
4331
- }
4332
- function buildUiProcessDefinition(process2) {
4333
- if (!process2.ui) {
4334
- return void 0;
4335
- }
4336
- const builder = createUiProcessBuilder();
4337
- process2.ui(builder);
4338
- return builder.getDefinition();
4339
- }
4340
-
4341
- // src/worker-process-builder.ts
4342
- function createWorkerProcessBuilder() {
4343
- const turns = /* @__PURE__ */ new Map();
4344
- let startTurnId = null;
4345
- return {
4346
- start(turnId) {
4347
- startTurnId = turnId;
4348
- },
4349
- turn(turnId, handler) {
4350
- registerUnique(turns, turnId, handler, {
4351
- duplicateMessage: `Worker turn '${turnId}' is already registered`
4352
- });
4353
- },
4354
- getDefinition() {
4355
- return {
4356
- startTurnId,
4357
- turns: cloneMap(turns)
4358
- };
4359
- }
4360
- };
4361
- }
4362
- export {
4363
- AutomaticFlowBuilder,
4364
- AutomaticOutcomeBuilder,
4365
- BUILT_IN_COMMIT_MESSAGE_RULES,
4366
- COMMIT_MESSAGE_PROJECT_METADATA_KEY,
4367
- CORE_TOOL_CALL_RENDERERS,
4368
- DEFAULT_FLOW_PRODUCT_NAME,
4369
- DEFAULT_PLAN_RESULT_OUTCOME_ID,
4370
- ExternalActionBuilder,
4371
- ExternalFlowBuilder,
4372
- ExternalRouteBuilder,
4373
- FlowFragmentBuilder,
4374
- FlowProcessBuilder,
4375
- HumanActionBuilder,
4376
- HumanFlowBuilder,
4377
- LlmFlowBuilder,
4378
- LlmTurnEndBuilder,
4379
- MARKDOWN_RESULT_TOOL_MARKDOWN_PATH,
4380
- MARKDOWN_RESULT_TOOL_NAME,
4381
- MARKDOWN_RESULT_TOOL_RENDERER,
4382
- OutcomeToolBuilder,
4383
- PI_BUILT_IN_TOOL_NAMES,
4384
- PlanResultBuilder,
4385
- PublishedResultBuilder,
4386
- REQUIRED_MARKDOWN_RESULT_TURN_RESULT,
4387
- ServerAutomaticFlowBuilder,
4388
- TOOL_CALL_RENDERER_VALUE_KINDS,
4389
- TOOL_CALL_RENDERER_VALUE_SOURCES,
4390
- TURN_COMPLETION_MODES,
4391
- TURN_CONTEXT_MODES,
4392
- WORKER_SUBPROCESS_SENSITIVE_ENV_KEYS,
4393
- acceptedReviewHandoffAction,
4394
- assertValidLlmTurnDefinition,
4395
- atomicWriteUtf8,
4396
- automaticTurn,
4397
- buildPlanSavedEventPayload,
4398
- buildProcessFlowView,
4399
- buildProcessLaunchers,
4400
- buildProcessWatchers,
4401
- buildReviewCompletedEventPayload,
4402
- buildReviewRequestedEventPayload,
4403
- buildUiProcessDefinition,
4404
- builtinPiProvider,
4405
- clearRepositoryGitSshWrappers,
4406
- collapseRoutingTurns,
4407
- collectProcessAvailableToolNames,
4408
- configuredPiProvider,
4409
- coreHostCapabilities,
4410
- createCapabilityAccessor,
4411
- createCapabilityToken,
4412
- createEmptyStructuralProcessState,
4413
- createEventBus,
4414
- createFlowAutomaticRunContext,
4415
- createFlowPromptContext,
4416
- createProcessLauncherBuilder,
4417
- createProcessWatcherBuilder,
4418
- createRootBranchReviewTurn,
4419
- createServerProcessBuilder,
4420
- createUiProcessBuilder,
4421
- createWorkerProcessBuilder,
4422
- credentialBasedModelStatuses,
4423
- defaultTurnStartSelection,
4424
- defineModelProvider,
4425
- defineModelProviders,
4426
- definePiServerAdapter,
4427
- definePiWorker,
4428
- defineProcess,
4429
- defineProviderOptions,
4430
- defineWorkerConfig,
4431
- emptyParamsCodec,
4432
- externalTurn,
4433
- filterProviderOptionsForDefinition,
4434
- filterStringArray,
4435
- findUiLauncherById,
4436
- flow,
4437
- getAllProcessGraphs,
4438
- getExternalActionArmingId,
4439
- getExternalActionTransitionTrigger,
4440
- getExternalSourceTransitionId,
4441
- getProcessGraph,
4442
- getProcessTurnGraph,
4443
- getReachableTurnIdsForProcessGraph,
4444
- getTurnTransitionsForProcessGraph,
4445
- hasProcessGraph,
4446
- humanTurn,
4447
- isAutomaticTurnDefinition,
4448
- isEnoent,
4449
- isExternalTurnDefinition,
4450
- isHumanTurnDefinition,
4451
- isLlmTurnDefinition,
4452
- isServerAutomaticTurnDefinition,
4453
- isTurnAvailableForProcessGraph,
4454
- listLlmTurnIdsForProcessGraph,
4455
- llmTurn,
4456
- normalizeLeafOutcomeCaptureResult,
4457
- parseStructuralProcessState,
4458
- piServer,
4459
- piWorker,
4460
- queuedInstructionAction,
4461
- repositoryGitArgs,
4462
- repositoryGitSubprocessEnv,
4463
- resolveHumanTurnView,
4464
- resolveLlmTurnRestorePrimaryLeafAfterTurn,
4465
- resolveLlmTurnStartSelection,
4466
- resolveProviderOptions,
4467
- resolveTurnActiveToolNames,
4468
- resolveTurnAvailableToolNames,
4469
- revisionAction,
4470
- routeTurnOutcomes,
4471
- sanitizeWorkerSubprocessEnv,
4472
- serializeProcessGraph,
4473
- serverAutomaticTurn,
4474
- setRepositoryGitSshWrapper,
4475
- toProcessGraphView,
4476
- validateAutomaticTurnDefinition,
4477
- validateExternalTurnDefinition,
4478
- validateHumanTurnDefinition,
4479
- validateLeafOutcomeCaptureResult,
4480
- validateLlmTurnDefinition,
4481
- validatePiBuiltInToolArray,
4482
- validateProcessGraphEntryTurns,
4483
- validateProcessGraphProducts,
4484
- validateProcessGraphTurnTransitions,
4485
- validateProcessLeafOutcomeDefinition,
4486
- validateToolCallRendererDefinition,
4487
- validateTurnDefinition
4488
- };
1
+ export { createCapabilityToken, } from "./capabilities.js";
2
+ export { emptyParamsCodec } from "./codecs.js";
3
+ export { BUILT_IN_COMMIT_MESSAGE_RULES, COMMIT_MESSAGE_PROJECT_METADATA_KEY, } from "./commit-message.js";
4
+ export { coreHostCapabilities, } from "./core-capabilities.js";
5
+ export { automaticTurn, defineProcess, externalTurn, getExternalActionArmingId, getExternalActionTransitionTrigger, getExternalSourceTransitionId, humanTurn, llmTurn, resolveHumanTurnView, routeTurnOutcomes, serverAutomaticTurn, } from "./define-process.js";
6
+ export { createEventBus } from "./event-bus.js";
7
+ export { findUiLauncherById } from "./extension-api.js";
8
+ export { AutomaticFlowBuilder, AutomaticOutcomeBuilder, createFlowAutomaticRunContext, createFlowPromptContext, DEFAULT_FLOW_PRODUCT_NAME, DEFAULT_PLAN_RESULT_OUTCOME_ID, ExternalActionBuilder, ExternalFlowBuilder, ExternalRouteBuilder, FlowFragmentBuilder, FlowProcessBuilder, flow, HumanActionBuilder, HumanFlowBuilder, LlmFlowBuilder, LlmTurnEndBuilder, OutcomeToolBuilder, PlanResultBuilder, PublishedResultBuilder, ServerAutomaticFlowBuilder, } from "./flow.js";
9
+ export { atomicWriteUtf8, isEnoent } from "./fs-utils.js";
10
+ export { acceptedReviewHandoffAction, queuedInstructionAction, revisionAction, } from "./graph-fragments.js";
11
+ export { createCapabilityAccessor, } from "./host-capabilities.js";
12
+ export { normalizeLeafOutcomeCaptureResult, validateLeafOutcomeCaptureResult, validateProcessLeafOutcomeDefinition, } from "./leaf-outcomes.js";
13
+ export { builtinPiProvider, configuredPiProvider, credentialBasedModelStatuses, defineModelProvider, defineModelProviders, definePiServerAdapter, definePiWorker, defineProviderOptions, defineWorkerConfig, filterProviderOptionsForDefinition, piServer, piWorker, resolveProviderOptions, } from "./model-provider.js";
14
+ export { collectProcessAvailableToolNames, resolveTurnActiveToolNames, resolveTurnAvailableToolNames, validatePiBuiltInToolArray, } from "./pi-config.js";
15
+ export { buildProcessFlowView, collapseRoutingTurns } from "./process-flow-view.js";
16
+ export { getAllProcessGraphs, getProcessGraph, getProcessTurnGraph, getReachableTurnIdsForProcessGraph, getTurnTransitionsForProcessGraph, hasProcessGraph, isTurnAvailableForProcessGraph, listLlmTurnIdsForProcessGraph, serializeProcessGraph, toProcessGraphView, validateProcessGraphEntryTurns, validateProcessGraphProducts, validateProcessGraphTurnTransitions, } from "./process-graph.js";
17
+ export { buildProcessLaunchers, createProcessLauncherBuilder, } from "./process-launcher-builder.js";
18
+ export { buildProcessWatchers, createProcessWatcherBuilder, } from "./process-watcher-builder.js";
19
+ export { clearRepositoryGitSshWrappers, repositoryGitArgs, repositoryGitSubprocessEnv, setRepositoryGitSshWrapper, } from "./repository-git-env.js";
20
+ export { buildPlanSavedEventPayload, buildReviewCompletedEventPayload, buildReviewRequestedEventPayload, filterStringArray, } from "./review-flow.js";
21
+ export { createServerProcessBuilder, } from "./server-process-builder.js";
22
+ export { createEmptyStructuralProcessState, parseStructuralProcessState, } from "./state-helpers.js";
23
+ export { sanitizeWorkerSubprocessEnv, WORKER_SUBPROCESS_SENSITIVE_ENV_KEYS, } from "./subprocess-env.js";
24
+ export { CORE_TOOL_CALL_RENDERERS, MARKDOWN_RESULT_TOOL_MARKDOWN_PATH, MARKDOWN_RESULT_TOOL_NAME, MARKDOWN_RESULT_TOOL_RENDERER, REQUIRED_MARKDOWN_RESULT_TURN_RESULT, TOOL_CALL_RENDERER_VALUE_KINDS, TOOL_CALL_RENDERER_VALUE_SOURCES, validateToolCallRendererDefinition, } from "./tool-renderers.js";
25
+ export { assertValidLlmTurnDefinition, createRootBranchReviewTurn, defaultTurnStartSelection, isAutomaticTurnDefinition, isExternalTurnDefinition, isHumanTurnDefinition, isLlmTurnDefinition, isServerAutomaticTurnDefinition, resolveLlmTurnRestorePrimaryLeafAfterTurn, resolveLlmTurnStartSelection, validateAutomaticTurnDefinition, validateExternalTurnDefinition, validateHumanTurnDefinition, validateLlmTurnDefinition, validateTurnDefinition, } from "./turn-semantics.js";
26
+ export { PI_BUILT_IN_TOOL_NAMES, TURN_COMPLETION_MODES, TURN_CONTEXT_MODES } from "./types.js";
27
+ export { buildUiProcessDefinition, createUiProcessBuilder, } from "./ui-process-builder.js";
28
+ export { createWorkerProcessBuilder, } from "./worker-process-builder.js";
4489
29
  //# sourceMappingURL=index.js.map