@leitwerk-dev/process-sdk 0.1.9 → 0.2.0

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