@leitwerk-dev/process-sdk 0.1.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 (199) hide show
  1. package/dist/LICENSE +13 -0
  2. package/dist/browser-ui-extension.d.ts +27 -0
  3. package/dist/browser-ui-extension.d.ts.map +1 -0
  4. package/dist/browser-ui-extension.js +2 -0
  5. package/dist/browser-ui-extension.js.map +1 -0
  6. package/dist/capabilities.d.ts +9 -0
  7. package/dist/capabilities.d.ts.map +1 -0
  8. package/dist/capabilities.js +7 -0
  9. package/dist/capabilities.js.map +1 -0
  10. package/dist/chunk-5RJZ2E7D.js +58 -0
  11. package/dist/chunk-5RJZ2E7D.js.map +1 -0
  12. package/dist/chunk-ITPH65G6.js +197 -0
  13. package/dist/chunk-ITPH65G6.js.map +1 -0
  14. package/dist/chunk-LIIP7FMU.js +48 -0
  15. package/dist/chunk-LIIP7FMU.js.map +1 -0
  16. package/dist/codecs.d.ts +3 -0
  17. package/dist/codecs.d.ts.map +1 -0
  18. package/dist/codecs.js +9 -0
  19. package/dist/codecs.js.map +1 -0
  20. package/dist/commit-message.d.ts +7 -0
  21. package/dist/commit-message.d.ts.map +1 -0
  22. package/dist/commit-message.js +3 -0
  23. package/dist/commit-message.js.map +1 -0
  24. package/dist/core-capabilities.d.ts +393 -0
  25. package/dist/core-capabilities.d.ts.map +1 -0
  26. package/dist/core-capabilities.js +6 -0
  27. package/dist/core-capabilities.js.map +1 -0
  28. package/dist/define-process.d.ts +269 -0
  29. package/dist/define-process.d.ts.map +1 -0
  30. package/dist/define-process.js +1040 -0
  31. package/dist/define-process.js.map +1 -0
  32. package/dist/event-bus.d.ts +3 -0
  33. package/dist/event-bus.d.ts.map +1 -0
  34. package/dist/event-bus.js +31 -0
  35. package/dist/event-bus.js.map +1 -0
  36. package/dist/extension-api-CnlL69Tu.d.ts +1281 -0
  37. package/dist/extension-api.d.ts +425 -0
  38. package/dist/extension-api.d.ts.map +1 -0
  39. package/dist/extension-api.js +5 -0
  40. package/dist/extension-api.js.map +1 -0
  41. package/dist/flow.d.ts +456 -0
  42. package/dist/flow.d.ts.map +1 -0
  43. package/dist/flow.js +1557 -0
  44. package/dist/flow.js.map +1 -0
  45. package/dist/form-contract.d.ts +2 -0
  46. package/dist/form-contract.d.ts.map +1 -0
  47. package/dist/form-contract.js +2 -0
  48. package/dist/form-contract.js.map +1 -0
  49. package/dist/fs-utils.d.ts +3 -0
  50. package/dist/fs-utils.d.ts.map +1 -0
  51. package/dist/fs-utils.js +23 -0
  52. package/dist/fs-utils.js.map +1 -0
  53. package/dist/git-binary.d.ts +11 -0
  54. package/dist/git-binary.d.ts.map +1 -0
  55. package/dist/git-binary.js +38 -0
  56. package/dist/git-binary.js.map +1 -0
  57. package/dist/graph-fragments.d.ts +23 -0
  58. package/dist/graph-fragments.d.ts.map +1 -0
  59. package/dist/graph-fragments.js +57 -0
  60. package/dist/graph-fragments.js.map +1 -0
  61. package/dist/host-capabilities.d.ts +12 -0
  62. package/dist/host-capabilities.d.ts.map +1 -0
  63. package/dist/host-capabilities.js +42 -0
  64. package/dist/host-capabilities.js.map +1 -0
  65. package/dist/index.d.ts +35 -0
  66. package/dist/index.d.ts.map +1 -0
  67. package/dist/index.js +29 -0
  68. package/dist/index.js.map +1 -0
  69. package/dist/launcher-contract.d.ts +2 -0
  70. package/dist/launcher-contract.d.ts.map +1 -0
  71. package/dist/launcher-contract.js +2 -0
  72. package/dist/launcher-contract.js.map +1 -0
  73. package/dist/leaf-outcome-renderer.d.ts +48 -0
  74. package/dist/leaf-outcome-renderer.d.ts.map +1 -0
  75. package/dist/leaf-outcome-renderer.js +69 -0
  76. package/dist/leaf-outcome-renderer.js.map +1 -0
  77. package/dist/leaf-outcomes.d.ts +5 -0
  78. package/dist/leaf-outcomes.d.ts.map +1 -0
  79. package/dist/leaf-outcomes.js +52 -0
  80. package/dist/leaf-outcomes.js.map +1 -0
  81. package/dist/model-provider.d.ts +210 -0
  82. package/dist/model-provider.d.ts.map +1 -0
  83. package/dist/model-provider.js +171 -0
  84. package/dist/model-provider.js.map +1 -0
  85. package/dist/pi-config.d.ts +59 -0
  86. package/dist/pi-config.d.ts.map +1 -0
  87. package/dist/pi-config.js +182 -0
  88. package/dist/pi-config.js.map +1 -0
  89. package/dist/process-definition-internals.d.ts +7 -0
  90. package/dist/process-definition-internals.d.ts.map +1 -0
  91. package/dist/process-definition-internals.js +25 -0
  92. package/dist/process-definition-internals.js.map +1 -0
  93. package/dist/process-flow-view.d.ts +20 -0
  94. package/dist/process-flow-view.d.ts.map +1 -0
  95. package/dist/process-flow-view.js +418 -0
  96. package/dist/process-flow-view.js.map +1 -0
  97. package/dist/process-graph.d.ts +45 -0
  98. package/dist/process-graph.d.ts.map +1 -0
  99. package/dist/process-graph.js +213 -0
  100. package/dist/process-graph.js.map +1 -0
  101. package/dist/process-launcher-builder.d.ts +9 -0
  102. package/dist/process-launcher-builder.d.ts.map +1 -0
  103. package/dist/process-launcher-builder.js +43 -0
  104. package/dist/process-launcher-builder.js.map +1 -0
  105. package/dist/process-watcher-builder.d.ts +10 -0
  106. package/dist/process-watcher-builder.d.ts.map +1 -0
  107. package/dist/process-watcher-builder.js +40 -0
  108. package/dist/process-watcher-builder.js.map +1 -0
  109. package/dist/registry-utils.d.ts +8 -0
  110. package/dist/registry-utils.d.ts.map +1 -0
  111. package/dist/registry-utils.js +18 -0
  112. package/dist/registry-utils.js.map +1 -0
  113. package/dist/repository-git-env.d.ts +8 -0
  114. package/dist/repository-git-env.d.ts.map +1 -0
  115. package/dist/repository-git-env.js +26 -0
  116. package/dist/repository-git-env.js.map +1 -0
  117. package/dist/review-flow.d.ts +10 -0
  118. package/dist/review-flow.d.ts.map +1 -0
  119. package/dist/review-flow.js +44 -0
  120. package/dist/review-flow.js.map +1 -0
  121. package/dist/runtime-internals.d.ts +3 -0
  122. package/dist/runtime-internals.d.ts.map +1 -0
  123. package/dist/runtime-internals.js +3 -0
  124. package/dist/runtime-internals.js.map +1 -0
  125. package/dist/server-events.d.ts +84 -0
  126. package/dist/server-events.d.ts.map +1 -0
  127. package/dist/server-events.js +2 -0
  128. package/dist/server-events.js.map +1 -0
  129. package/dist/server-process-builder.d.ts +11 -0
  130. package/dist/server-process-builder.d.ts.map +1 -0
  131. package/dist/server-process-builder.js +52 -0
  132. package/dist/server-process-builder.js.map +1 -0
  133. package/dist/state-helpers.d.ts +9 -0
  134. package/dist/state-helpers.d.ts.map +1 -0
  135. package/dist/state-helpers.js +20 -0
  136. package/dist/state-helpers.js.map +1 -0
  137. package/dist/subprocess-env.d.ts +12 -0
  138. package/dist/subprocess-env.d.ts.map +1 -0
  139. package/dist/subprocess-env.js +34 -0
  140. package/dist/subprocess-env.js.map +1 -0
  141. package/dist/tool-renderers.d.ts +10 -0
  142. package/dist/tool-renderers.d.ts.map +1 -0
  143. package/dist/tool-renderers.js +63 -0
  144. package/dist/tool-renderers.js.map +1 -0
  145. package/dist/turn-semantics.d.ts +22 -0
  146. package/dist/turn-semantics.d.ts.map +1 -0
  147. package/dist/turn-semantics.js +339 -0
  148. package/dist/turn-semantics.js.map +1 -0
  149. package/dist/types.d.ts +295 -0
  150. package/dist/types.d.ts.map +1 -0
  151. package/dist/types.js +12 -0
  152. package/dist/types.js.map +1 -0
  153. package/dist/ui-process-builder.d.ts +9 -0
  154. package/dist/ui-process-builder.d.ts.map +1 -0
  155. package/dist/ui-process-builder.js +30 -0
  156. package/dist/ui-process-builder.js.map +1 -0
  157. package/dist/worker-process-builder.d.ts +10 -0
  158. package/dist/worker-process-builder.d.ts.map +1 -0
  159. package/dist/worker-process-builder.js +22 -0
  160. package/dist/worker-process-builder.js.map +1 -0
  161. package/package.json +72 -0
  162. package/src/browser-ui-extension.ts +32 -0
  163. package/src/capabilities.ts +16 -0
  164. package/src/codecs.ts +10 -0
  165. package/src/commit-message.ts +9 -0
  166. package/src/core-capabilities.ts +526 -0
  167. package/src/define-process.ts +1879 -0
  168. package/src/event-bus.ts +35 -0
  169. package/src/extension-api.ts +600 -0
  170. package/src/flow.ts +2268 -0
  171. package/src/form-contract.ts +11 -0
  172. package/src/fs-utils.ts +28 -0
  173. package/src/git-binary.ts +40 -0
  174. package/src/graph-fragments.ts +110 -0
  175. package/src/host-capabilities.ts +60 -0
  176. package/src/index.ts +468 -0
  177. package/src/launcher-contract.ts +8 -0
  178. package/src/leaf-outcome-renderer.ts +112 -0
  179. package/src/leaf-outcomes.ts +74 -0
  180. package/src/model-provider.ts +461 -0
  181. package/src/pi-config.ts +268 -0
  182. package/src/process-definition-internals.ts +46 -0
  183. package/src/process-flow-view.ts +479 -0
  184. package/src/process-graph.ts +309 -0
  185. package/src/process-launcher-builder.ts +59 -0
  186. package/src/process-watcher-builder.ts +72 -0
  187. package/src/registry-utils.ts +31 -0
  188. package/src/repository-git-env.ts +35 -0
  189. package/src/review-flow.ts +66 -0
  190. package/src/runtime-internals.ts +7 -0
  191. package/src/server-events.ts +105 -0
  192. package/src/server-process-builder.ts +90 -0
  193. package/src/state-helpers.ts +36 -0
  194. package/src/subprocess-env.ts +48 -0
  195. package/src/tool-renderers.ts +92 -0
  196. package/src/turn-semantics.ts +554 -0
  197. package/src/types.ts +391 -0
  198. package/src/ui-process-builder.ts +46 -0
  199. package/src/worker-process-builder.ts +33 -0
@@ -0,0 +1,1879 @@
1
+ import {
2
+ assertValidProcessProductName,
3
+ type InputKind,
4
+ type InputSource,
5
+ type ProcessInputTarget,
6
+ type ProcessInstance,
7
+ type ProcessSemanticEntryRefKey,
8
+ type ProcessTurnStartSelection,
9
+ type ProcessTurnTerminalLifecycleStatus,
10
+ type ProcessTurnTransition,
11
+ type ReviewSubject,
12
+ type TurnId,
13
+ } from "@leitwerk-dev/domain";
14
+ import type {
15
+ Codec,
16
+ ExtensionProcessDefinition,
17
+ ExternalActionSource,
18
+ ExternalSourceEffect,
19
+ FormDefinition,
20
+ ProcessLauncherAPI,
21
+ ProcessTurnBinding,
22
+ ProcessTurnOutcomeEvent,
23
+ ProcessWatcherAPI,
24
+ RepositoryCredentialProject,
25
+ RepositoryCredentialRequirement,
26
+ ServerProcessAPI,
27
+ ServerProcessContext,
28
+ ServerTransitionRequest,
29
+ UiProcessAPI,
30
+ WorkerCompleteInput,
31
+ WorkerProcessAPI,
32
+ WorkerProcessContext,
33
+ } from "./extension-api.js";
34
+ import {
35
+ getProcessTurnTransitions,
36
+ markDefinedProcess,
37
+ setProcessTurnTransitions,
38
+ } from "./process-definition-internals.js";
39
+ import type { ServerExtensionEventMap } from "./server-events.js";
40
+ import type {
41
+ HumanTurnActionView,
42
+ HumanTurnExternalActionView,
43
+ HumanTurnExternalTrigger,
44
+ HumanTurnNotesField,
45
+ OutcomeToolParameterSpec,
46
+ PiBuiltInToolName,
47
+ ProcessActionPreviewDefinition,
48
+ ProcessActionSchedulingDefinition,
49
+ ProcessPiConfig,
50
+ TurnAcceptanceState,
51
+ TurnBranchType,
52
+ TurnCompletionMode,
53
+ TurnContextMode,
54
+ TurnResultMarkdownBehavior,
55
+ } from "./types.js";
56
+
57
+ type ProcessEventName = keyof ServerExtensionEventMap & string;
58
+
59
+ type ProcessEmittedEvent = {
60
+ type: ProcessEventName;
61
+ data: unknown;
62
+ };
63
+
64
+ type ProcessQueuedInput = {
65
+ source: InputSource;
66
+ kind: InputKind;
67
+ bodyMarkdown: string;
68
+ target?: ProcessInputTarget;
69
+ };
70
+
71
+ type MaybePromise<T> = T | Promise<T>;
72
+
73
+ type StaticRouteTarget = {
74
+ to?: TurnId;
75
+ complete?: boolean;
76
+ lifecycleStatus?: ProcessTurnTerminalLifecycleStatus;
77
+ };
78
+
79
+ type NormalizedRouteTarget = {
80
+ nextTurnId?: TurnId;
81
+ lifecycleStatus?: ProcessTurnTerminalLifecycleStatus;
82
+ };
83
+
84
+ type NormalizedActionRoute = NormalizedRouteTarget & {
85
+ trigger: string;
86
+ };
87
+
88
+ export interface ProcessRuntimeTurnContext<TParams = unknown, TState = unknown>
89
+ extends WorkerProcessContext<TParams, TState> {}
90
+
91
+ export interface ProcessServerRuntimeContext<TParams = unknown, TState = unknown> {
92
+ readonly process: ServerProcessContext<TParams, TState>["process"];
93
+ readonly projects: ServerProcessContext<TParams, TState>["projects"];
94
+ readonly params: TParams;
95
+ readonly state: TState;
96
+ readSemanticTurnResultMarkdown(ref: ProcessSemanticEntryRefKey): string | null;
97
+ readProductTurnResultMarkdown(productName: string): string | null;
98
+ }
99
+
100
+ export interface ProcessBroadcastEffect {
101
+ type: string;
102
+ payload: Record<string, unknown>;
103
+ }
104
+
105
+ export type ProcessPatchEffect = Partial<
106
+ Pick<
107
+ ProcessInstance,
108
+ | "planRevision"
109
+ | "title"
110
+ | "externalId"
111
+ | "externalUrl"
112
+ | "metadata"
113
+ | "defaultModelProfileId"
114
+ | "turnConfigsJson"
115
+ >
116
+ >;
117
+
118
+ export interface ProcessLifecycleEffects {
119
+ processPatch?: ProcessPatchEffect;
120
+ broadcasts?: readonly ProcessBroadcastEffect[];
121
+ }
122
+
123
+ export interface ProcessEffectPlan<TState = unknown> extends ProcessLifecycleEffects {
124
+ state?: TState;
125
+ emit?: readonly ProcessEmittedEvent[];
126
+ queueInput?: readonly ProcessQueuedInput[];
127
+ }
128
+
129
+ export interface SavePlanResultLifecycleIntent<TParams = unknown, TState = unknown> {
130
+ kind: "save_plan_result";
131
+ summaryParam: string;
132
+ acceptanceCriteriaParam: string;
133
+ planMarkdownParam: string;
134
+ emitEventType: ProcessEventName;
135
+ broadcastType: string;
136
+ state?: ProcessOutcomeEffect<TParams, TState>;
137
+ }
138
+
139
+ export type ProcessOutcomeLifecycleIntent<
140
+ TParams = unknown,
141
+ TState = unknown,
142
+ > = SavePlanResultLifecycleIntent<TParams, TState>;
143
+
144
+ export interface ProcessActionExecution<TParams = unknown, TState = unknown> {
145
+ readonly ctx: ProcessServerRuntimeContext<TParams, TState>;
146
+ readonly input: Record<string, unknown>;
147
+ readonly turnId: TurnId;
148
+ readonly actionId: string;
149
+ readonly selectedBranchId?: string;
150
+ }
151
+
152
+ export interface ProcessOutcomeExecution<TParams = unknown, TState = unknown> {
153
+ readonly ctx: ProcessServerRuntimeContext<TParams, TState>;
154
+ readonly event: ProcessTurnOutcomeEvent;
155
+ readonly turnId: TurnId;
156
+ readonly outcome: string;
157
+ }
158
+
159
+ export type ProcessActionEffect<TParams = unknown, TState = unknown> = (
160
+ input: ProcessActionExecution<TParams, TState>,
161
+ ) => MaybePromise<ProcessEffectPlan<TState> | undefined>;
162
+
163
+ export type ProcessActionBranchSelector<TParams = unknown, TState = unknown> = (
164
+ input: Omit<ProcessActionExecution<TParams, TState>, "selectedBranchId">,
165
+ ) => MaybePromise<string>;
166
+
167
+ export type ProcessOutcomeEffect<TParams = unknown, TState = unknown> = (
168
+ input: ProcessOutcomeExecution<TParams, TState>,
169
+ ) => MaybePromise<ProcessEffectPlan<TState> | undefined>;
170
+
171
+ export interface ProcessActionExternalTrigger {
172
+ id: string;
173
+ label: string;
174
+ description: string;
175
+ }
176
+
177
+ export interface ExternalActionInputPublication {
178
+ productName: string;
179
+ inputField: string;
180
+ }
181
+
182
+ export interface ProcessHumanTurnExternalActionSpec<
183
+ TParams = unknown,
184
+ TState = unknown,
185
+ TEvent = unknown,
186
+ TInput extends Record<string, unknown> = Record<string, unknown>,
187
+ > extends StaticRouteTarget {
188
+ id: string;
189
+ source: ExternalActionSource<TParams, TState, TEvent, TInput>;
190
+ label?: string;
191
+ description?: string;
192
+ publishInput?: ExternalActionInputPublication;
193
+ }
194
+
195
+ export interface ProcessActionBranchSpec extends StaticRouteTarget {
196
+ trigger?: string;
197
+ }
198
+
199
+ type StaticActionRouting = StaticRouteTarget & {
200
+ trigger?: string;
201
+ };
202
+
203
+ type BranchingActionRouting<TParams, TState> = {
204
+ branches: Record<string, ProcessActionBranchSpec>;
205
+ choose: ProcessActionBranchSelector<TParams, TState>;
206
+ };
207
+
208
+ interface BaseActionSpec<TParams, TState> {
209
+ label: string;
210
+ description?: string;
211
+ form?: FormDefinition;
212
+ preview?: ProcessActionPreviewDefinition;
213
+ schedulable?: boolean;
214
+ effect?: ProcessActionEffect<TParams, TState>;
215
+ }
216
+
217
+ export type ProcessHumanTurnActionSpec<TParams = unknown, TState = unknown> = BaseActionSpec<
218
+ TParams,
219
+ TState
220
+ > & {
221
+ acceptanceState: TurnAcceptanceState;
222
+ externalTriggers?: readonly ProcessActionExternalTrigger[];
223
+ } & (StaticActionRouting | BranchingActionRouting<TParams, TState>);
224
+
225
+ export interface ProcessToolOutcomeSpec<TParams = unknown, TState = unknown>
226
+ extends StaticRouteTarget {
227
+ description: string;
228
+ parameters: Record<string, OutcomeToolParameterSpec>;
229
+ /** Product published from this outcome's turn-result markdown, when this outcome is selected. */
230
+ publishedProduct?: string;
231
+ /** Outcome parameter whose markdown value is captured as the turn result. */
232
+ turnResultMarkdownParameter?: string;
233
+ effect?: ProcessOutcomeEffect<TParams, TState>;
234
+ lifecycleIntent?: ProcessOutcomeLifecycleIntent<TParams, TState>;
235
+ }
236
+ export type HumanTurnOperatorAttention = "required" | "passive";
237
+
238
+ export interface HumanTurnDefinition<TParams = unknown, TState = unknown> {
239
+ kind: "human";
240
+ description: string;
241
+ /** Optional for generic operator-waiting turns; review turns should set it. */
242
+ reviewSubject?: ReviewSubject;
243
+ reviewProduct?: string;
244
+ reviewSemanticRef?: ProcessSemanticEntryRefKey;
245
+ /** Controls whether entering this turn should raise an action-required toast. */
246
+ operatorAttention?: HumanTurnOperatorAttention;
247
+ notesFields?: readonly HumanTurnNotesField[];
248
+ commentary?: string;
249
+ actions: Record<string, ProcessHumanTurnActionSpec<TParams, TState>>;
250
+ externalActions?: Record<string, ProcessHumanTurnExternalActionSpec<TParams, TState>>;
251
+ }
252
+
253
+ export interface ProcessTurnEndSpec<
254
+ TParams = unknown,
255
+ TState = unknown,
256
+ TOutcome extends string = string,
257
+ > extends StaticRouteTarget {
258
+ outcome: TOutcome;
259
+ params?: Record<string, unknown>;
260
+ effect?: ProcessOutcomeEffect<TParams, TState>;
261
+ }
262
+
263
+ export type OutcomeRouteSpec<TParams = unknown, TState = unknown> = StaticRouteTarget &
264
+ Partial<Pick<ProcessToolOutcomeSpec<TParams, TState>, "description" | "parameters" | "effect">>;
265
+
266
+ export interface OutcomeRouteOptions {
267
+ strict?: boolean;
268
+ }
269
+
270
+ export type LlmModelPurpose = "process_title_generation";
271
+
272
+ export interface LlmTurnDefinition<
273
+ TOutcome extends string = string,
274
+ TParams = unknown,
275
+ TState = unknown,
276
+ > {
277
+ kind: "llm";
278
+ description: string;
279
+ /** Code-defined model policy purpose. Purpose selections cannot be overridden per launch/action. */
280
+ modelPurpose?: LlmModelPurpose;
281
+ /** Built-in Pi tools active while this turn runs. */
282
+ availableTools: readonly PiBuiltInToolName[];
283
+ /** Opt in to the durable, operator-facing ask_questions custom tool. */
284
+ askQuestions?: boolean;
285
+ completionMode?: TurnCompletionMode;
286
+ branchType: TurnBranchType;
287
+ context: TurnContextMode;
288
+ startFrom?: ProcessTurnStartSelection;
289
+ restorePrimaryLeafAfterTurn?: boolean;
290
+ prompt(ctx: ProcessRuntimeTurnContext<TParams, TState>): string | Promise<string>;
291
+ outcomes?: Partial<Record<TOutcome, ProcessToolOutcomeSpec<TParams, TState>>>;
292
+ turnEnd?: ProcessTurnEndSpec<TParams, TState, TOutcome>;
293
+ turnResultMarkdown?: TurnResultMarkdownBehavior;
294
+ reviewSubject?: ReviewSubject;
295
+ reviewSemanticRef?: ProcessSemanticEntryRefKey;
296
+ resultSemanticRef?: ProcessSemanticEntryRefKey;
297
+ publishedProduct?: string;
298
+ consumedProducts?: readonly string[];
299
+ optionalConsumedProducts?: readonly string[];
300
+ requiredSemanticMarkdownRefs?: readonly ProcessSemanticEntryRefKey[];
301
+ optionalSemanticMarkdownRefs?: readonly ProcessSemanticEntryRefKey[];
302
+ }
303
+
304
+ export interface AutomaticTurnDefinition<
305
+ TOutcome extends string = string,
306
+ TParams = unknown,
307
+ TState = unknown,
308
+ > {
309
+ kind: "automatic";
310
+ description: string;
311
+ outcomes?: Partial<Record<TOutcome, ProcessToolOutcomeSpec<TParams, TState>>>;
312
+ turnEnd?: ProcessTurnEndSpec<TParams, TState, TOutcome>;
313
+ reviewSubject?: ReviewSubject;
314
+ reviewSemanticRef?: ProcessSemanticEntryRefKey;
315
+ run(
316
+ ctx: ProcessRuntimeTurnContext<TParams, TState>,
317
+ ): Promise<WorkerCompleteInput<TOutcome>> | WorkerCompleteInput<TOutcome>;
318
+ }
319
+
320
+ export interface ServerAutomaticTurnRunResult<TOutcome extends string = string, TState = unknown>
321
+ extends WorkerCompleteInput<TOutcome> {
322
+ state?: TState;
323
+ }
324
+
325
+ export type ServerAutomaticTurnRestartBehavior = "rerun" | "fail_running";
326
+
327
+ export interface ServerAutomaticTurnDefinition<
328
+ TOutcome extends string = string,
329
+ TParams = unknown,
330
+ TState = unknown,
331
+ > {
332
+ kind: "server_automatic";
333
+ description: string;
334
+ outcomes?: Partial<Record<TOutcome, ProcessToolOutcomeSpec<TParams, TState>>>;
335
+ turnEnd?: ProcessTurnEndSpec<TParams, TState, TOutcome>;
336
+ reviewSubject?: ReviewSubject;
337
+ reviewSemanticRef?: ProcessSemanticEntryRefKey;
338
+ /**
339
+ * Controls startup/drainer behavior when a durable running turn record already exists.
340
+ * The default reruns the deterministic handler. Use fail_running for non-idempotent
341
+ * host side effects that must not be replayed after a server crash/restart.
342
+ */
343
+ restartBehavior?: ServerAutomaticTurnRestartBehavior;
344
+ run(
345
+ ctx: ProcessServerRuntimeContext<TParams, TState>,
346
+ ):
347
+ | Promise<ServerAutomaticTurnRunResult<TOutcome, TState>>
348
+ | ServerAutomaticTurnRunResult<TOutcome, TState>;
349
+ }
350
+
351
+ export interface ExternalSourceTransition<
352
+ TParams = unknown,
353
+ TState = unknown,
354
+ TEvent = unknown,
355
+ TInput extends Record<string, unknown> = Record<string, unknown>,
356
+ > extends StaticRouteTarget {
357
+ source: ExternalActionSource<TParams, TState, TEvent, TInput>;
358
+ effect?: ExternalSourceEffect<TParams, TState, TEvent, TInput>;
359
+ }
360
+
361
+ export interface ExternalTurnDefinition<TParams = unknown, TState = unknown> {
362
+ kind: "external";
363
+ description: string;
364
+ transitions: readonly ExternalSourceTransition<TParams, TState>[];
365
+ reviewSubject?: ReviewSubject;
366
+ reviewSemanticRef?: ProcessSemanticEntryRefKey;
367
+ }
368
+
369
+ export type TurnDefinition<TParams = unknown, TState = unknown> =
370
+ | LlmTurnDefinition<string, TParams, TState>
371
+ | AutomaticTurnDefinition<string, TParams, TState>
372
+ | ServerAutomaticTurnDefinition<string, TParams, TState>
373
+ | HumanTurnDefinition<TParams, TState>
374
+ | ExternalTurnDefinition<TParams, TState>;
375
+
376
+ export type TurnDefinitionRecord<TParams = unknown, TState = unknown> = Record<
377
+ TurnId,
378
+ TurnDefinition<TParams, TState>
379
+ >;
380
+
381
+ export type ProcessDefinition<TParams = unknown, TState = unknown> = ExtensionProcessDefinition<
382
+ TParams,
383
+ TState
384
+ >;
385
+
386
+ export interface DefinedProcessInput<TParams = unknown, TState = unknown> {
387
+ id: string;
388
+ displayName: string;
389
+ /** Primary entry used when a launch does not select a start turn explicitly. */
390
+ entry: TurnId;
391
+ /** Additional entry turns that launchers may select explicitly. */
392
+ alternateEntries?: readonly TurnId[];
393
+ happyPath?: readonly TurnId[];
394
+ paramsCodec: Codec<TParams>;
395
+ stateCodec: Codec<TState>;
396
+ initialState(params: TParams): TState;
397
+ repositoryCredentials?(input: {
398
+ params: TParams;
399
+ projects: readonly RepositoryCredentialProject[];
400
+ }): readonly RepositoryCredentialRequirement[];
401
+ piConfig?: ProcessPiConfig;
402
+ turns: TurnDefinitionRecord<TParams, TState>;
403
+ worker?: (api: WorkerProcessAPI<TParams, TState>) => void;
404
+ server?: (api: ServerProcessAPI<TParams, TState>) => void;
405
+ ui?: (api: UiProcessAPI<TParams, TState>) => void;
406
+ launchers?: (api: ProcessLauncherAPI<TParams>) => void;
407
+ watchers?: (api: ProcessWatcherAPI<TParams>) => void;
408
+ }
409
+
410
+ type CompiledActionRouting<TParams, TState> =
411
+ | {
412
+ kind: "static";
413
+ route: NormalizedActionRoute;
414
+ }
415
+ | {
416
+ kind: "branches";
417
+ routes: Record<string, NormalizedActionRoute>;
418
+ choose: ProcessActionBranchSelector<TParams, TState>;
419
+ };
420
+
421
+ type CompiledActionUse<TParams, TState> = {
422
+ turnId: TurnId;
423
+ label?: string;
424
+ form?: FormDefinition;
425
+ effect?: ProcessActionEffect<TParams, TState>;
426
+ routing: CompiledActionRouting<TParams, TState>;
427
+ };
428
+
429
+ type CompiledExecutableTurn<TParams, TState> =
430
+ | {
431
+ kind: "llm";
432
+ id: TurnId;
433
+ spec: LlmTurnDefinition<string, TParams, TState>;
434
+ }
435
+ | {
436
+ kind: "automatic";
437
+ id: TurnId;
438
+ spec: AutomaticTurnDefinition<string, TParams, TState>;
439
+ };
440
+
441
+ function createTransitionTargetError(context: string, detail: string): Error {
442
+ return new Error(`${context} ${detail}`);
443
+ }
444
+
445
+ function createProcessTurnBinding<TTurn>(
446
+ definition: TTurn,
447
+ transitions?: readonly ProcessTurnTransition[],
448
+ ): ProcessTurnBinding<TTurn> {
449
+ const binding: ProcessTurnBinding<TTurn> = { definition };
450
+ if (transitions && transitions.length > 0) {
451
+ setProcessTurnTransitions(binding, transitions);
452
+ }
453
+ return binding;
454
+ }
455
+
456
+ function normalizeStaticRouteTarget(
457
+ context: string,
458
+ target: StaticRouteTarget,
459
+ knownTurnIds?: ReadonlySet<TurnId>,
460
+ ): NormalizedRouteTarget {
461
+ const declaredTargetCount =
462
+ (target.to !== undefined ? 1 : 0) +
463
+ (target.complete === true ? 1 : 0) +
464
+ (target.lifecycleStatus !== undefined ? 1 : 0);
465
+ if (declaredTargetCount !== 1) {
466
+ throw createTransitionTargetError(
467
+ context,
468
+ "must declare exactly one target via 'to', 'complete', or 'lifecycleStatus'",
469
+ );
470
+ }
471
+ if (target.to !== undefined) {
472
+ if (knownTurnIds && !knownTurnIds.has(target.to)) {
473
+ throw createTransitionTargetError(context, `references unknown turn '${target.to}'`);
474
+ }
475
+ return { nextTurnId: target.to };
476
+ }
477
+ if (target.complete === true) {
478
+ return { lifecycleStatus: "completed" };
479
+ }
480
+ return { lifecycleStatus: target.lifecycleStatus };
481
+ }
482
+
483
+ function buildOutcomeTransition<TParams, TState>(
484
+ turnId: TurnId,
485
+ outcome: string,
486
+ target: ProcessToolOutcomeSpec<TParams, TState> | ProcessTurnEndSpec<TParams, TState>,
487
+ knownTurnIds?: ReadonlySet<TurnId>,
488
+ ): NormalizedRouteTarget {
489
+ if (!hasDeclaredStaticRouteTarget(target)) {
490
+ return { nextTurnId: turnId };
491
+ }
492
+ return normalizeStaticRouteTarget(`Turn '${turnId}' outcome '${outcome}'`, target, knownTurnIds);
493
+ }
494
+
495
+ function resolveActionRouting<TParams, TState>(input: {
496
+ turnId: TurnId;
497
+ actionId: string;
498
+ spec: ProcessHumanTurnActionSpec<TParams, TState>;
499
+ knownTurnIds?: ReadonlySet<TurnId>;
500
+ }): {
501
+ routing: CompiledActionRouting<TParams, TState>;
502
+ transitions: readonly NormalizedActionRoute[];
503
+ } {
504
+ if ("branches" in input.spec) {
505
+ const entries = Object.entries(input.spec.branches) as Array<[string, ProcessActionBranchSpec]>;
506
+ if (entries.length === 0) {
507
+ throw new Error(
508
+ `Action '${input.actionId}' on turn '${input.turnId}' must declare at least one branch`,
509
+ );
510
+ }
511
+ const routes: Record<string, NormalizedActionRoute> = {};
512
+ const resolvedTransitions: NormalizedActionRoute[] = [];
513
+ const usedTriggers = new Set<string>();
514
+ for (const [branchId, branchSpec] of entries) {
515
+ if (branchId.trim() === "") {
516
+ throw new Error(
517
+ `Action '${input.actionId}' on turn '${input.turnId}' contains an empty branch id`,
518
+ );
519
+ }
520
+ const target = normalizeStaticRouteTarget(
521
+ `Action '${input.actionId}' branch '${branchId}' on turn '${input.turnId}'`,
522
+ branchSpec,
523
+ input.knownTurnIds,
524
+ );
525
+ const trigger = branchSpec.trigger ?? branchId;
526
+ if (usedTriggers.has(trigger)) {
527
+ throw new Error(
528
+ `Action '${input.actionId}' on turn '${input.turnId}' contains duplicate branch trigger '${trigger}'`,
529
+ );
530
+ }
531
+ usedTriggers.add(trigger);
532
+ const normalized = {
533
+ ...(target.nextTurnId ? { nextTurnId: target.nextTurnId } : {}),
534
+ ...(target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {}),
535
+ trigger,
536
+ };
537
+ routes[branchId] = normalized;
538
+ resolvedTransitions.push(normalized);
539
+ }
540
+ return {
541
+ routing: {
542
+ kind: "branches",
543
+ routes,
544
+ choose: input.spec.choose,
545
+ },
546
+ transitions: resolvedTransitions,
547
+ };
548
+ }
549
+ const target = normalizeStaticRouteTarget(
550
+ `Action '${input.actionId}' on turn '${input.turnId}'`,
551
+ input.spec,
552
+ input.knownTurnIds,
553
+ );
554
+ const route = {
555
+ ...(target.nextTurnId ? { nextTurnId: target.nextTurnId } : {}),
556
+ ...(target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {}),
557
+ trigger: input.spec.trigger ?? input.actionId,
558
+ };
559
+ return {
560
+ routing: {
561
+ kind: "static",
562
+ route,
563
+ },
564
+ transitions: [route],
565
+ };
566
+ }
567
+
568
+ function externalSourceTransitionId(input: {
569
+ turnId: TurnId;
570
+ source: ExternalActionSource;
571
+ index: number;
572
+ }): string {
573
+ return `${input.turnId}:${input.source.kind}:${input.index}`;
574
+ }
575
+
576
+ function externalActionArmingId(input: { turnId: TurnId; externalActionId: string }): string {
577
+ return `${input.turnId}:${input.externalActionId}`;
578
+ }
579
+
580
+ function externalActionTransitionTrigger(input: { externalActionId: string }): string {
581
+ return `external:${input.externalActionId}`;
582
+ }
583
+
584
+ function compileExternalSourceTransitions<TParams, TState>(input: {
585
+ turnId: TurnId;
586
+ spec: ExternalTurnDefinition<TParams, TState>;
587
+ knownTurnIds: ReadonlySet<TurnId>;
588
+ }): readonly ProcessTurnTransition[] {
589
+ if (input.spec.transitions.length === 0) {
590
+ throw new Error(`External turn '${input.turnId}' must declare at least one source transition`);
591
+ }
592
+ return input.spec.transitions.map((transition, index) => {
593
+ if (transition.source.kind.trim() === "") {
594
+ throw new Error(
595
+ `External turn '${input.turnId}' source transition ${index} has an empty kind`,
596
+ );
597
+ }
598
+ const target = normalizeStaticRouteTarget(
599
+ `External turn '${input.turnId}' source '${transition.source.kind}'`,
600
+ transition,
601
+ input.knownTurnIds,
602
+ );
603
+ return {
604
+ ...(target.nextTurnId ? { nextTurnId: target.nextTurnId } : {}),
605
+ ...(target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {}),
606
+ trigger: externalSourceTransitionId({
607
+ turnId: input.turnId,
608
+ source: transition.source,
609
+ index,
610
+ }),
611
+ };
612
+ });
613
+ }
614
+
615
+ export function getExternalSourceTransitionId(input: {
616
+ turnId: TurnId;
617
+ source: ExternalActionSource;
618
+ index: number;
619
+ }): string {
620
+ return externalSourceTransitionId(input);
621
+ }
622
+
623
+ export function getExternalActionArmingId(input: {
624
+ turnId: TurnId;
625
+ externalActionId: string;
626
+ }): string {
627
+ return externalActionArmingId(input);
628
+ }
629
+
630
+ export function getExternalActionTransitionTrigger(input: { externalActionId: string }): string {
631
+ return externalActionTransitionTrigger(input);
632
+ }
633
+
634
+ function previewMatchesTransition(
635
+ preview: ProcessActionPreviewDefinition,
636
+ transition: NormalizedActionRoute,
637
+ ): boolean {
638
+ if (preview.kind === "trigger") {
639
+ return transition.trigger === preview.trigger;
640
+ }
641
+ if (preview.kind === "terminal") {
642
+ return transition.lifecycleStatus === preview.lifecycleStatus;
643
+ }
644
+ return transition.nextTurnId === preview.turnId;
645
+ }
646
+
647
+ function validateActionPreviewMatchesTransitions(input: {
648
+ turnId: TurnId;
649
+ actionId: string;
650
+ preview: ProcessActionPreviewDefinition;
651
+ transitions: readonly NormalizedActionRoute[];
652
+ context: "preview" | "scheduling";
653
+ }): void {
654
+ const matches = input.transitions.filter((transition) =>
655
+ previewMatchesTransition(input.preview, transition),
656
+ );
657
+ if (matches.length === 1) {
658
+ return;
659
+ }
660
+ const previewLabel =
661
+ input.preview.kind === "trigger"
662
+ ? `trigger '${input.preview.trigger}'`
663
+ : input.preview.kind === "terminal"
664
+ ? `terminal '${input.preview.lifecycleStatus}'`
665
+ : `fixed turn '${String(input.preview.turnId)}'`;
666
+ throw new Error(
667
+ `Action '${input.actionId}' on turn '${input.turnId}' ${input.context} does not match a compiled transition for ${previewLabel}`,
668
+ );
669
+ }
670
+
671
+ function buildActionPreviewAndScheduling(
672
+ turnId: TurnId,
673
+ actionId: string,
674
+ spec: Pick<BaseActionSpec<unknown, unknown>, "preview" | "schedulable">,
675
+ transitions: readonly NormalizedActionRoute[],
676
+ ): {
677
+ preview?: ProcessActionPreviewDefinition;
678
+ scheduling?: ProcessActionSchedulingDefinition;
679
+ } {
680
+ const preview = (() => {
681
+ if (spec.preview) {
682
+ return spec.preview;
683
+ }
684
+ if (transitions.length !== 1) {
685
+ return undefined;
686
+ }
687
+ const [transition] = transitions;
688
+ if (!transition) {
689
+ return undefined;
690
+ }
691
+ if (transition.lifecycleStatus !== undefined) {
692
+ return {
693
+ kind: "terminal",
694
+ lifecycleStatus: transition.lifecycleStatus,
695
+ } satisfies ProcessActionPreviewDefinition;
696
+ }
697
+ return {
698
+ kind: "trigger",
699
+ trigger: transition.trigger,
700
+ } satisfies ProcessActionPreviewDefinition;
701
+ })();
702
+ if (spec.preview && preview) {
703
+ validateActionPreviewMatchesTransitions({
704
+ turnId,
705
+ actionId,
706
+ preview,
707
+ transitions,
708
+ context: "preview",
709
+ });
710
+ }
711
+ if (spec.schedulable && preview) {
712
+ validateActionPreviewMatchesTransitions({
713
+ turnId,
714
+ actionId,
715
+ preview,
716
+ transitions,
717
+ context: "scheduling",
718
+ });
719
+ }
720
+ if (spec.schedulable && !preview) {
721
+ throw new Error(
722
+ `Action '${actionId}' is schedulable but does not resolve to a unique preview transition`,
723
+ );
724
+ }
725
+ return {
726
+ ...(preview ? { preview } : {}),
727
+ ...(spec.schedulable && preview ? { scheduling: { preview } } : {}),
728
+ };
729
+ }
730
+
731
+ function mergeProcessEffectPlans<TState>(
732
+ left: ProcessEffectPlan<TState> | undefined,
733
+ right: ProcessEffectPlan<TState> | undefined,
734
+ ): ProcessEffectPlan<TState> | undefined {
735
+ if (!left) {
736
+ return right;
737
+ }
738
+ if (!right) {
739
+ return left;
740
+ }
741
+ return {
742
+ ...left,
743
+ ...right,
744
+ ...(left.processPatch || right.processPatch
745
+ ? { processPatch: { ...(left.processPatch ?? {}), ...(right.processPatch ?? {}) } }
746
+ : {}),
747
+ ...(left.broadcasts || right.broadcasts
748
+ ? { broadcasts: [...(left.broadcasts ?? []), ...(right.broadcasts ?? [])] }
749
+ : {}),
750
+ ...(left.emit || right.emit ? { emit: [...(left.emit ?? []), ...(right.emit ?? [])] } : {}),
751
+ ...(left.queueInput || right.queueInput
752
+ ? { queueInput: [...(left.queueInput ?? []), ...(right.queueInput ?? [])] }
753
+ : {}),
754
+ };
755
+ }
756
+
757
+ function normalizeEffectString(value: unknown): string {
758
+ return typeof value === "string" ? value.trim() : "";
759
+ }
760
+
761
+ function normalizeEffectStringArray(value: unknown): string[] {
762
+ return Array.isArray(value)
763
+ ? value
764
+ .map((entry) => (typeof entry === "string" ? entry.trim() : ""))
765
+ .filter((entry) => entry !== "")
766
+ : [];
767
+ }
768
+
769
+ function getTurnReviewSubject(turnDef: TurnDefinition<unknown, unknown> | undefined) {
770
+ if (!turnDef || !("reviewSubject" in turnDef)) {
771
+ return null;
772
+ }
773
+ return turnDef.reviewSubject ?? null;
774
+ }
775
+
776
+ function patchReviewSubjectIntoState<TState>(
777
+ state: TState,
778
+ reviewSubject: ReviewSubject | null,
779
+ ): TState {
780
+ if (typeof state !== "object" || state === null || Array.isArray(state)) {
781
+ return state;
782
+ }
783
+ return {
784
+ ...(state as Record<string, unknown>),
785
+ reviewSubject,
786
+ } as TState;
787
+ }
788
+
789
+ async function buildSavePlanResultEffect<TParams, TState>(input: {
790
+ intent: SavePlanResultLifecycleIntent<TParams, TState>;
791
+ execution: ProcessOutcomeExecution<TParams, TState>;
792
+ targetTurn: TurnDefinition<unknown, unknown> | undefined;
793
+ }): Promise<ProcessEffectPlan<TState>> {
794
+ const statePlan = input.intent.state ? await input.intent.state(input.execution) : undefined;
795
+ const targetReviewSubject = getTurnReviewSubject(input.targetTurn);
796
+ const baseState = statePlan?.state ?? input.execution.ctx.state;
797
+ const planRevision = input.execution.ctx.process.planRevision + 1;
798
+ const summary = normalizeEffectString(input.execution.event.params[input.intent.summaryParam]);
799
+ const acceptanceCriteria = normalizeEffectStringArray(
800
+ input.execution.event.params[input.intent.acceptanceCriteriaParam],
801
+ );
802
+ const planMarkdown =
803
+ typeof input.execution.event.turnResultMarkdown === "string"
804
+ ? input.execution.event.turnResultMarkdown
805
+ : normalizeEffectString(input.execution.event.params[input.intent.planMarkdownParam]);
806
+
807
+ return mergeProcessEffectPlans(statePlan, {
808
+ state: patchReviewSubjectIntoState(baseState, targetReviewSubject),
809
+ processPatch: { planRevision },
810
+ broadcasts: [
811
+ {
812
+ type: input.intent.broadcastType,
813
+ payload: {
814
+ planRevision,
815
+ reviewState: "awaiting_approval",
816
+ approved: false,
817
+ summary,
818
+ },
819
+ },
820
+ ],
821
+ emit: [
822
+ {
823
+ type: input.intent.emitEventType,
824
+ data: {
825
+ planRevision,
826
+ summary,
827
+ planMarkdown,
828
+ acceptanceCriteria,
829
+ },
830
+ },
831
+ ],
832
+ }) as ProcessEffectPlan<TState>;
833
+ }
834
+
835
+ function resolveOutcomeEffect<TParams, TState>(input: {
836
+ spec: ProcessToolOutcomeSpec<TParams, TState> | ProcessTurnEndSpec<TParams, TState, string>;
837
+ targetTurn: TurnDefinition<unknown, unknown> | undefined;
838
+ }): ProcessOutcomeEffect<TParams, TState> | undefined {
839
+ const lifecycleIntent = "lifecycleIntent" in input.spec ? input.spec.lifecycleIntent : undefined;
840
+ if (!lifecycleIntent) {
841
+ return input.spec.effect;
842
+ }
843
+ return async (execution) => {
844
+ const explicitPlan = input.spec.effect ? await input.spec.effect(execution) : undefined;
845
+ let lifecyclePlan: ProcessEffectPlan<TState> | undefined;
846
+ switch (lifecycleIntent.kind) {
847
+ case "save_plan_result":
848
+ lifecyclePlan = await buildSavePlanResultEffect({
849
+ intent: lifecycleIntent,
850
+ execution,
851
+ targetTurn: input.targetTurn,
852
+ });
853
+ break;
854
+ }
855
+ return mergeProcessEffectPlans(explicitPlan, lifecyclePlan);
856
+ };
857
+ }
858
+
859
+ function areFormsEquivalent(
860
+ left: FormDefinition | undefined,
861
+ right: FormDefinition | undefined,
862
+ ): boolean {
863
+ if (left === right) {
864
+ return true;
865
+ }
866
+ return JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
867
+ }
868
+
869
+ function cloneStateForFormPatch<TState>(state: TState): TState {
870
+ if (typeof state !== "object" || state === null) {
871
+ throw new Error("Declarative form state fields require object process state");
872
+ }
873
+ return structuredClone(state);
874
+ }
875
+
876
+ function normalizeFormStateValue(field: FormDefinition["fields"][number], value: unknown): unknown {
877
+ if (field.kind === "number") {
878
+ const parsed = typeof value === "number" ? value : Number(String(value).trim());
879
+ if (!Number.isFinite(parsed)) {
880
+ throw new Error(`Field '${field.id}' must be a number`);
881
+ }
882
+ return parsed;
883
+ }
884
+ return value;
885
+ }
886
+
887
+ function applyFormStateFields<TState>(input: {
888
+ form?: FormDefinition;
889
+ inputValue: Record<string, unknown>;
890
+ state: TState;
891
+ }): TState | undefined {
892
+ const stateFields = (input.form?.fields ?? []).filter((field) => field.state);
893
+ if (stateFields.length === 0) {
894
+ return undefined;
895
+ }
896
+ const nextState = cloneStateForFormPatch(input.state) as Record<string, unknown>;
897
+ for (const field of stateFields) {
898
+ const rawValue = input.inputValue[field.id];
899
+ if (rawValue === undefined) {
900
+ continue;
901
+ }
902
+ const path = field.state?.path.trim();
903
+ if (!path) {
904
+ throw new Error(`Form field '${field.id}' declares an empty state path`);
905
+ }
906
+ const segments = path.split(".").map((segment) => segment.trim());
907
+ if (segments.some((segment) => segment === "")) {
908
+ throw new Error(`Form field '${field.id}' declares invalid state path '${path}'`);
909
+ }
910
+ let target: Record<string, unknown> = nextState;
911
+ for (const segment of segments.slice(0, -1)) {
912
+ const existing = target[segment];
913
+ if (typeof existing !== "object" || existing === null || Array.isArray(existing)) {
914
+ target[segment] = {};
915
+ }
916
+ target = target[segment] as Record<string, unknown>;
917
+ }
918
+ target[segments[segments.length - 1] as string] = normalizeFormStateValue(field, rawValue);
919
+ }
920
+ return nextState as TState;
921
+ }
922
+
923
+ function makeProcessServerRuntimeContext<TParams, TState>(
924
+ ctx: ServerProcessContext<TParams, TState>,
925
+ ): ProcessServerRuntimeContext<TParams, TState> {
926
+ return {
927
+ process: ctx.process,
928
+ projects: ctx.projects,
929
+ params: ctx.params,
930
+ state: ctx.state,
931
+ readSemanticTurnResultMarkdown: (ref) => ctx.readSemanticTurnResultMarkdown(ref),
932
+ readProductTurnResultMarkdown: (productName) => ctx.readProductTurnResultMarkdown(productName),
933
+ };
934
+ }
935
+
936
+ function mergeTransitionWithState<TState>(input: {
937
+ result: ProcessEffectPlan<TState> | undefined;
938
+ transition?: Omit<ServerTransitionRequest<TState>, "state">;
939
+ }): ServerTransitionRequest<TState> | null {
940
+ const next = {
941
+ ...(input.transition ?? {}),
942
+ ...(input.result?.state !== undefined ? { state: input.result.state } : {}),
943
+ };
944
+ const hasFields =
945
+ next.turnId !== undefined ||
946
+ next.lifecycleStatus !== undefined ||
947
+ next.trigger !== undefined ||
948
+ next.effect !== undefined ||
949
+ next.state !== undefined;
950
+ return hasFields ? next : null;
951
+ }
952
+
953
+ function hasLifecycleEffects(result: ProcessEffectPlan | undefined): result is ProcessEffectPlan {
954
+ return Boolean(
955
+ result?.processPatch !== undefined ||
956
+ (result?.broadcasts !== undefined && result.broadcasts.length > 0),
957
+ );
958
+ }
959
+
960
+ async function applyProcessEffectPlan<TParams, TState>(input: {
961
+ ctx: ServerProcessContext<TParams, TState>;
962
+ result: ProcessEffectPlan<TState> | undefined;
963
+ transition?: Omit<ServerTransitionRequest<TState>, "state">;
964
+ }): Promise<void> {
965
+ const transition = mergeTransitionWithState({
966
+ result: input.result,
967
+ transition: input.transition,
968
+ });
969
+ if (transition) {
970
+ await input.ctx.transition(transition);
971
+ }
972
+ if (hasLifecycleEffects(input.result)) {
973
+ if (!input.ctx.applyLifecycleEffects) {
974
+ throw new Error("Process lifecycle effects are not supported by this server context");
975
+ }
976
+ input.ctx.applyLifecycleEffects({
977
+ ...(input.result.processPatch ? { processPatch: input.result.processPatch } : {}),
978
+ ...(input.result.broadcasts ? { broadcasts: input.result.broadcasts } : {}),
979
+ });
980
+ }
981
+ for (const emitted of input.result?.emit ?? []) {
982
+ input.ctx.emitEvent(emitted.type, emitted.data as never);
983
+ }
984
+ for (const queuedInput of input.result?.queueInput ?? []) {
985
+ input.ctx.queueInput(queuedInput);
986
+ }
987
+ }
988
+
989
+ function compileTurnOutcomeDefinitions<TParams, TState>(input: {
990
+ turnId: TurnId;
991
+ outcomes?: Partial<Record<string, ProcessToolOutcomeSpec<TParams, TState>>>;
992
+ turnEnd?: ProcessTurnEndSpec<TParams, TState, string>;
993
+ knownTurnIds: ReadonlySet<TurnId>;
994
+ turnDefinitionsById: ReadonlyMap<TurnId, TurnDefinition<unknown, unknown>>;
995
+ }): {
996
+ transitions: readonly ProcessTurnTransition[];
997
+ effects: ReadonlyMap<string, ProcessOutcomeEffect<TParams, TState> | undefined>;
998
+ } {
999
+ const outcomeEntries = Object.entries(input.outcomes ?? {}) as Array<
1000
+ [string, ProcessToolOutcomeSpec<TParams, TState>]
1001
+ >;
1002
+ if (outcomeEntries.length > 0 && input.turnEnd) {
1003
+ throw new Error(
1004
+ `Turn '${input.turnId}' cannot declare both tool outcomes and a turnEnd result`,
1005
+ );
1006
+ }
1007
+ if (outcomeEntries.length === 0 && !input.turnEnd) {
1008
+ throw new Error(
1009
+ `Turn '${input.turnId}' must declare at least one tool outcome or a turnEnd result`,
1010
+ );
1011
+ }
1012
+
1013
+ const transitions: ProcessTurnTransition[] = [];
1014
+ const effects = new Map<string, ProcessOutcomeEffect<TParams, TState> | undefined>();
1015
+ for (const [outcome, spec] of outcomeEntries) {
1016
+ if (outcome.trim() === "") {
1017
+ throw new Error(`Turn '${input.turnId}' declares an empty outcome id`);
1018
+ }
1019
+ const target = buildOutcomeTransition(input.turnId, outcome, spec, input.knownTurnIds);
1020
+ transitions.push({
1021
+ ...(target.nextTurnId ? { nextTurnId: target.nextTurnId } : {}),
1022
+ ...(target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {}),
1023
+ outcome,
1024
+ });
1025
+ effects.set(
1026
+ outcome,
1027
+ resolveOutcomeEffect({
1028
+ spec,
1029
+ targetTurn: target.nextTurnId
1030
+ ? input.turnDefinitionsById.get(target.nextTurnId)
1031
+ : undefined,
1032
+ }),
1033
+ );
1034
+ }
1035
+
1036
+ if (input.turnEnd) {
1037
+ if (input.turnEnd.outcome.trim() === "") {
1038
+ throw new Error(`Turn '${input.turnId}' declares an empty turnEnd outcome id`);
1039
+ }
1040
+ const target = buildOutcomeTransition(
1041
+ input.turnId,
1042
+ input.turnEnd.outcome,
1043
+ input.turnEnd,
1044
+ input.knownTurnIds,
1045
+ );
1046
+ transitions.push({
1047
+ ...(target.nextTurnId ? { nextTurnId: target.nextTurnId } : {}),
1048
+ ...(target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {}),
1049
+ outcome: input.turnEnd.outcome,
1050
+ });
1051
+ effects.set(
1052
+ input.turnEnd.outcome,
1053
+ resolveOutcomeEffect({
1054
+ spec: input.turnEnd,
1055
+ targetTurn: target.nextTurnId
1056
+ ? input.turnDefinitionsById.get(target.nextTurnId)
1057
+ : undefined,
1058
+ }),
1059
+ );
1060
+ }
1061
+
1062
+ return {
1063
+ transitions,
1064
+ effects,
1065
+ };
1066
+ }
1067
+
1068
+ function addActionUse<TParams, TState>(input: {
1069
+ actionUses: Map<string, CompiledActionUse<TParams, TState>[]>;
1070
+ actionId: string;
1071
+ use: CompiledActionUse<TParams, TState>;
1072
+ }) {
1073
+ const existing = input.actionUses.get(input.actionId) ?? [];
1074
+ if (existing.some((candidate) => candidate.turnId === input.use.turnId)) {
1075
+ throw new Error(
1076
+ `Turn '${input.use.turnId}' declares action '${input.actionId}' more than once`,
1077
+ );
1078
+ }
1079
+ existing.push(input.use);
1080
+ input.actionUses.set(input.actionId, existing);
1081
+ }
1082
+
1083
+ type DerivedHumanTurnAction<TParams, TState> = {
1084
+ actionId: string;
1085
+ actionSpec: ProcessHumanTurnActionSpec<TParams, TState>;
1086
+ routing: CompiledActionRouting<TParams, TState>;
1087
+ transitions: readonly NormalizedActionRoute[];
1088
+ actionView: HumanTurnActionView;
1089
+ externalTriggers: readonly HumanTurnExternalTrigger[];
1090
+ };
1091
+
1092
+ type DerivedHumanTurnExternalAction<TParams, TState> = {
1093
+ externalActionId: string;
1094
+ actionSpec: ProcessHumanTurnExternalActionSpec<TParams, TState>;
1095
+ transition: NormalizedActionRoute;
1096
+ view: HumanTurnExternalActionView;
1097
+ };
1098
+
1099
+ function hasDeclaredStaticRouteTarget(target: StaticRouteTarget): boolean {
1100
+ return (
1101
+ target.to !== undefined || target.complete === true || target.lifecycleStatus !== undefined
1102
+ );
1103
+ }
1104
+
1105
+ function resolveExternalActionRoute<TParams, TState>(input: {
1106
+ turnId: TurnId;
1107
+ externalActionId: string;
1108
+ spec: ProcessHumanTurnExternalActionSpec<TParams, TState>;
1109
+ knownTurnIds?: ReadonlySet<TurnId>;
1110
+ }): NormalizedActionRoute {
1111
+ if (input.externalActionId.trim() === "") {
1112
+ throw new Error(`Human turn '${input.turnId}' declares an empty external action id`);
1113
+ }
1114
+ if (input.spec.id !== input.externalActionId) {
1115
+ throw new Error(
1116
+ `Human turn '${input.turnId}' external action '${input.externalActionId}' has mismatched spec id '${input.spec.id}'`,
1117
+ );
1118
+ }
1119
+ if (input.spec.source.kind.trim() === "") {
1120
+ throw new Error(
1121
+ `Human turn '${input.turnId}' external action '${input.externalActionId}' must declare a non-empty source kind`,
1122
+ );
1123
+ }
1124
+ const target = normalizeStaticRouteTarget(
1125
+ `Human turn '${input.turnId}' external action '${input.externalActionId}'`,
1126
+ input.spec,
1127
+ input.knownTurnIds,
1128
+ );
1129
+ return {
1130
+ ...(target.nextTurnId ? { nextTurnId: target.nextTurnId } : {}),
1131
+ ...(target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {}),
1132
+ trigger: externalActionTransitionTrigger({ externalActionId: input.externalActionId }),
1133
+ };
1134
+ }
1135
+
1136
+ function validateExternalActionPublishedInputTarget<TParams, TState>(input: {
1137
+ turnId: TurnId;
1138
+ externalActionId: string;
1139
+ spec: ProcessHumanTurnExternalActionSpec<TParams, TState>;
1140
+ turnDefinitionsById?: ReadonlyMap<TurnId, TurnDefinition<unknown, unknown>>;
1141
+ }): void {
1142
+ const publication = input.spec.publishInput;
1143
+ if (!publication || !input.turnDefinitionsById) {
1144
+ return;
1145
+ }
1146
+ if (input.spec.to === undefined) {
1147
+ throw new Error(
1148
+ `Human turn '${input.turnId}' external action '${input.externalActionId}' publishes input '${publication.productName}' but does not route to a consuming turn`,
1149
+ );
1150
+ }
1151
+ const targetTurn = input.turnDefinitionsById.get(input.spec.to);
1152
+ if (!targetTurn || targetTurn.kind !== "llm") {
1153
+ throw new Error(
1154
+ `Human turn '${input.turnId}' external action '${input.externalActionId}' publishes input '${publication.productName}' but target turn '${input.spec.to}' is not an LLM turn`,
1155
+ );
1156
+ }
1157
+ const consumed = new Set([
1158
+ ...(targetTurn.consumedProducts ?? []),
1159
+ ...(targetTurn.optionalConsumedProducts ?? []),
1160
+ ]);
1161
+ if (!consumed.has(publication.productName)) {
1162
+ throw new Error(
1163
+ `Human turn '${input.turnId}' external action '${input.externalActionId}' publishes input '${publication.productName}' but target turn '${input.spec.to}' does not consume it`,
1164
+ );
1165
+ }
1166
+ }
1167
+
1168
+ function validateActionPrimaryPrompt(
1169
+ turnId: TurnId,
1170
+ actionId: string,
1171
+ action: { form?: FormDefinition },
1172
+ ): void {
1173
+ const fields = action.form?.fields ?? [];
1174
+ const textualFields = fields.filter(
1175
+ (field) => field.kind === "text" || field.kind === "textarea",
1176
+ );
1177
+ const primaryPrompts = fields.filter((field) => field.primaryPrompt);
1178
+ if (primaryPrompts.some((field) => field.kind !== "text" && field.kind !== "textarea")) {
1179
+ throw new Error(
1180
+ `Human turn '${turnId}' action '${actionId}' primary prompt must be a text or textarea field`,
1181
+ );
1182
+ }
1183
+ if (primaryPrompts.length > 1) {
1184
+ throw new Error(
1185
+ `Human turn '${turnId}' action '${actionId}' must declare at most one primary prompt`,
1186
+ );
1187
+ }
1188
+ if (textualFields.length > 0 && primaryPrompts.length === 0) {
1189
+ throw new Error(
1190
+ `Human turn '${turnId}' action '${actionId}' with textual fields must declare a primary prompt`,
1191
+ );
1192
+ }
1193
+ }
1194
+
1195
+ function deriveHumanTurnActions<TParams, TState>(input: {
1196
+ turnId: TurnId;
1197
+ spec: HumanTurnDefinition<TParams, TState>;
1198
+ knownTurnIds?: ReadonlySet<TurnId>;
1199
+ turnDefinitionsById?: ReadonlyMap<TurnId, TurnDefinition<unknown, unknown>>;
1200
+ }): {
1201
+ actions: readonly DerivedHumanTurnAction<TParams, TState>[];
1202
+ externalActions: readonly DerivedHumanTurnExternalAction<TParams, TState>[];
1203
+ transitions: readonly ProcessTurnTransition[];
1204
+ } {
1205
+ const actionEntries = Object.entries(input.spec.actions) as Array<
1206
+ [string, ProcessHumanTurnActionSpec<TParams, TState>]
1207
+ >;
1208
+ if (actionEntries.length === 0 && input.knownTurnIds) {
1209
+ throw new Error(`Human turn '${input.turnId}' must declare at least one action`);
1210
+ }
1211
+
1212
+ const derivedActions: DerivedHumanTurnAction<TParams, TState>[] = [];
1213
+ const transitions: ProcessTurnTransition[] = [];
1214
+ const actionIdByTrigger = new Map<string, string>();
1215
+ for (const [actionId, actionSpec] of actionEntries) {
1216
+ if (actionId.trim() === "") {
1217
+ throw new Error(`Human turn '${input.turnId}' declares an empty action id`);
1218
+ }
1219
+ validateActionPrimaryPrompt(input.turnId, actionId, actionSpec);
1220
+ const resolved =
1221
+ !input.knownTurnIds &&
1222
+ !("branches" in actionSpec) &&
1223
+ !hasDeclaredStaticRouteTarget(actionSpec)
1224
+ ? {
1225
+ routing: {
1226
+ kind: "static",
1227
+ route: { trigger: actionSpec.trigger ?? actionId },
1228
+ } satisfies CompiledActionRouting<TParams, TState>,
1229
+ transitions: [] as readonly NormalizedActionRoute[],
1230
+ }
1231
+ : resolveActionRouting({
1232
+ turnId: input.turnId,
1233
+ actionId,
1234
+ spec: actionSpec,
1235
+ knownTurnIds: input.knownTurnIds,
1236
+ });
1237
+ for (const transition of resolved.transitions) {
1238
+ const existingActionId = actionIdByTrigger.get(transition.trigger);
1239
+ if (existingActionId && existingActionId !== actionId) {
1240
+ throw new Error(
1241
+ `Human turn '${input.turnId}' contains duplicate action trigger '${transition.trigger}' across actions '${existingActionId}' and '${actionId}'`,
1242
+ );
1243
+ }
1244
+ actionIdByTrigger.set(transition.trigger, actionId);
1245
+ transitions.push({
1246
+ ...(transition.nextTurnId ? { nextTurnId: transition.nextTurnId } : {}),
1247
+ ...(transition.lifecycleStatus ? { lifecycleStatus: transition.lifecycleStatus } : {}),
1248
+ trigger: transition.trigger,
1249
+ });
1250
+ }
1251
+ const previewAndScheduling =
1252
+ !input.knownTurnIds && resolved.transitions.length === 0
1253
+ ? {
1254
+ ...(actionSpec.preview ? { preview: actionSpec.preview } : {}),
1255
+ ...(actionSpec.schedulable && actionSpec.preview
1256
+ ? { scheduling: { preview: actionSpec.preview } }
1257
+ : {}),
1258
+ }
1259
+ : buildActionPreviewAndScheduling(input.turnId, actionId, actionSpec, resolved.transitions);
1260
+ derivedActions.push({
1261
+ actionId,
1262
+ actionSpec,
1263
+ routing: resolved.routing,
1264
+ transitions: resolved.transitions,
1265
+ actionView: {
1266
+ actionId,
1267
+ label: actionSpec.label,
1268
+ description: actionSpec.description,
1269
+ acceptanceState: actionSpec.acceptanceState,
1270
+ ...previewAndScheduling,
1271
+ },
1272
+ externalTriggers:
1273
+ actionSpec.externalTriggers?.map((trigger) => ({
1274
+ id: trigger.id,
1275
+ actionId,
1276
+ label: trigger.label,
1277
+ description: trigger.description,
1278
+ })) ?? [],
1279
+ });
1280
+ }
1281
+
1282
+ const externalActionEntries = Object.entries(input.spec.externalActions ?? {}) as Array<
1283
+ [string, ProcessHumanTurnExternalActionSpec<TParams, TState>]
1284
+ >;
1285
+ const derivedExternalActions: DerivedHumanTurnExternalAction<TParams, TState>[] = [];
1286
+ const externalActionIds = new Set<string>();
1287
+ for (const [externalActionId, actionSpec] of externalActionEntries) {
1288
+ if (externalActionIds.has(externalActionId)) {
1289
+ throw new Error(
1290
+ `Human turn '${input.turnId}' declares duplicate external action '${externalActionId}'`,
1291
+ );
1292
+ }
1293
+ externalActionIds.add(externalActionId);
1294
+ if (actionSpec.publishInput) {
1295
+ assertValidProcessProductName(actionSpec.publishInput.productName);
1296
+ if (actionSpec.publishInput.inputField.trim() === "") {
1297
+ throw new Error(
1298
+ `Human turn '${input.turnId}' external action '${externalActionId}' publishInput must declare a non-empty inputField`,
1299
+ );
1300
+ }
1301
+ }
1302
+ validateExternalActionPublishedInputTarget({
1303
+ turnId: input.turnId,
1304
+ externalActionId,
1305
+ spec: actionSpec,
1306
+ turnDefinitionsById: input.turnDefinitionsById,
1307
+ });
1308
+ const transition = resolveExternalActionRoute({
1309
+ turnId: input.turnId,
1310
+ externalActionId,
1311
+ spec: actionSpec,
1312
+ knownTurnIds: input.knownTurnIds,
1313
+ });
1314
+ const existingActionId = actionIdByTrigger.get(transition.trigger);
1315
+ if (existingActionId) {
1316
+ throw new Error(
1317
+ `Human turn '${input.turnId}' contains duplicate trigger '${transition.trigger}' across action '${existingActionId}' and external action '${externalActionId}'`,
1318
+ );
1319
+ }
1320
+ actionIdByTrigger.set(transition.trigger, externalActionId);
1321
+ transitions.push({
1322
+ ...(transition.nextTurnId ? { nextTurnId: transition.nextTurnId } : {}),
1323
+ ...(transition.lifecycleStatus ? { lifecycleStatus: transition.lifecycleStatus } : {}),
1324
+ trigger: transition.trigger,
1325
+ });
1326
+ derivedExternalActions.push({
1327
+ externalActionId,
1328
+ actionSpec,
1329
+ transition,
1330
+ view: {
1331
+ id: externalActionArmingId({ turnId: input.turnId, externalActionId }),
1332
+ externalActionId,
1333
+ sourceKind: actionSpec.source.kind,
1334
+ label: actionSpec.label ?? actionSpec.source.label ?? null,
1335
+ description: actionSpec.description ?? actionSpec.source.description ?? null,
1336
+ },
1337
+ });
1338
+ }
1339
+
1340
+ return {
1341
+ actions: derivedActions,
1342
+ externalActions: derivedExternalActions,
1343
+ transitions,
1344
+ };
1345
+ }
1346
+
1347
+ export function resolveHumanTurnView<TParams, TState>(input: {
1348
+ turnId: TurnId;
1349
+ turn: HumanTurnDefinition<TParams, TState>;
1350
+ }): {
1351
+ actions: readonly HumanTurnActionView[];
1352
+ externalTriggers: readonly HumanTurnExternalTrigger[];
1353
+ externalActions: readonly HumanTurnExternalActionView[];
1354
+ } {
1355
+ const derived = deriveHumanTurnActions({
1356
+ turnId: input.turnId,
1357
+ spec: input.turn,
1358
+ });
1359
+ return {
1360
+ actions: derived.actions.map((action) => action.actionView),
1361
+ externalTriggers: derived.actions.flatMap((action) => action.externalTriggers),
1362
+ externalActions: derived.externalActions.map((action) => action.view),
1363
+ };
1364
+ }
1365
+
1366
+ function compileHumanTurn<TParams, TState>(input: {
1367
+ turnId: TurnId;
1368
+ spec: HumanTurnDefinition<TParams, TState>;
1369
+ knownTurnIds: ReadonlySet<TurnId>;
1370
+ turnDefinitionsById: ReadonlyMap<TurnId, TurnDefinition<unknown, unknown>>;
1371
+ actionUses: Map<string, CompiledActionUse<TParams, TState>[]>;
1372
+ }): {
1373
+ binding: ProcessTurnBinding<HumanTurnDefinition<TParams, TState>>;
1374
+ } {
1375
+ const derived = deriveHumanTurnActions({
1376
+ turnId: input.turnId,
1377
+ spec: input.spec,
1378
+ knownTurnIds: input.knownTurnIds,
1379
+ turnDefinitionsById: input.turnDefinitionsById,
1380
+ });
1381
+ for (const action of derived.actions) {
1382
+ addActionUse({
1383
+ actionUses: input.actionUses,
1384
+ actionId: action.actionId,
1385
+ use: {
1386
+ turnId: input.turnId,
1387
+ label: action.actionSpec.label,
1388
+ ...(action.actionSpec.form ? { form: action.actionSpec.form } : {}),
1389
+ ...(action.actionSpec.effect ? { effect: action.actionSpec.effect } : {}),
1390
+ routing: action.routing,
1391
+ },
1392
+ });
1393
+ }
1394
+
1395
+ return {
1396
+ binding: createProcessTurnBinding(input.spec, derived.transitions),
1397
+ };
1398
+ }
1399
+
1400
+ function compileExternalTurn<TParams, TState>(input: {
1401
+ turnId: TurnId;
1402
+ spec: ExternalTurnDefinition<TParams, TState>;
1403
+ knownTurnIds: ReadonlySet<TurnId>;
1404
+ }): {
1405
+ binding: ProcessTurnBinding<ExternalTurnDefinition<TParams, TState>>;
1406
+ } {
1407
+ const transitions = compileExternalSourceTransitions({
1408
+ turnId: input.turnId,
1409
+ spec: input.spec,
1410
+ knownTurnIds: input.knownTurnIds,
1411
+ });
1412
+ return {
1413
+ binding: createProcessTurnBinding(input.spec, transitions),
1414
+ };
1415
+ }
1416
+
1417
+ function getTurnEntries<TParams, TState>(
1418
+ turns: TurnDefinitionRecord<TParams, TState>,
1419
+ ): Array<[TurnId, TurnDefinition<TParams, TState>]> {
1420
+ return Object.entries(turns) as Array<[TurnId, TurnDefinition<TParams, TState>]>;
1421
+ }
1422
+
1423
+ function resolveActionRouteForExecution<TParams, TState>(input: {
1424
+ use: CompiledActionUse<TParams, TState>;
1425
+ actionId: string;
1426
+ ctx: ServerProcessContext<TParams, TState>;
1427
+ inputValue: Record<string, unknown>;
1428
+ }): MaybePromise<{
1429
+ route: NormalizedActionRoute;
1430
+ selectedBranchId?: string;
1431
+ }> {
1432
+ if (input.use.routing.kind === "static") {
1433
+ return { route: input.use.routing.route };
1434
+ }
1435
+ const actionExecution: Omit<ProcessActionExecution<TParams, TState>, "selectedBranchId"> = {
1436
+ ctx: makeProcessServerRuntimeContext(input.ctx),
1437
+ input: input.inputValue,
1438
+ turnId: input.use.turnId,
1439
+ actionId: input.actionId,
1440
+ };
1441
+ const routes = input.use.routing.routes;
1442
+ return Promise.resolve(input.use.routing.choose(actionExecution)).then((selectedBranchId) => {
1443
+ if (!Object.hasOwn(routes, selectedBranchId)) {
1444
+ throw new Error(
1445
+ `Action '${input.actionId}' on turn '${input.use.turnId}' selected unknown branch '${selectedBranchId}'`,
1446
+ );
1447
+ }
1448
+ const route = routes[selectedBranchId];
1449
+ if (!route) {
1450
+ throw new Error(
1451
+ `Action '${input.actionId}' on turn '${input.use.turnId}' selected unknown branch '${selectedBranchId}'`,
1452
+ );
1453
+ }
1454
+ return { route, selectedBranchId };
1455
+ });
1456
+ }
1457
+
1458
+ function buildActionTransitionRequest<TState>(route: NormalizedActionRoute) {
1459
+ if (route.nextTurnId !== undefined) {
1460
+ return {
1461
+ turnId: route.nextTurnId,
1462
+ trigger: route.trigger,
1463
+ } satisfies Omit<ServerTransitionRequest<TState>, "state">;
1464
+ }
1465
+ return {
1466
+ turnId: null,
1467
+ lifecycleStatus: route.lifecycleStatus,
1468
+ trigger: route.trigger,
1469
+ } satisfies Omit<ServerTransitionRequest<TState>, "state">;
1470
+ }
1471
+
1472
+ function validateHappyPathConnectivity<TParams, TState>(input: {
1473
+ processId: string;
1474
+ happyPath: readonly TurnId[] | undefined;
1475
+ turns: ReadonlyMap<TurnId, ProcessTurnBinding<TurnDefinition<TParams, TState>>>;
1476
+ turnDefinitionsById: ReadonlyMap<TurnId, TurnDefinition<unknown, unknown>>;
1477
+ }): void {
1478
+ const happyPath = input.happyPath;
1479
+ if (!happyPath || happyPath.length < 2) {
1480
+ return;
1481
+ }
1482
+ const happyPathTurns = new Set<TurnId>(happyPath);
1483
+ for (let index = 0; index < happyPath.length - 1; index += 1) {
1484
+ const source = happyPath[index];
1485
+ const target = happyPath[index + 1];
1486
+ let connected = false;
1487
+ const visited = new Set<TurnId>([source]);
1488
+ const queue: TurnId[] = [source];
1489
+ while (queue.length > 0 && !connected) {
1490
+ const current = queue.shift() as TurnId;
1491
+ for (const transition of getProcessTurnTransitions(input.turns.get(current))) {
1492
+ const next = transition.nextTurnId;
1493
+ if (next === undefined || !input.turnDefinitionsById.has(next)) {
1494
+ continue;
1495
+ }
1496
+ if (next === target) {
1497
+ connected = true;
1498
+ break;
1499
+ }
1500
+ if (visited.has(next) || happyPathTurns.has(next)) {
1501
+ continue;
1502
+ }
1503
+ const definition = input.turnDefinitionsById.get(next);
1504
+ if (definition?.kind !== "human") {
1505
+ continue;
1506
+ }
1507
+ visited.add(next);
1508
+ queue.push(next);
1509
+ }
1510
+ }
1511
+ if (!connected) {
1512
+ throw new Error(
1513
+ `Process '${input.processId}' happy path segment '${source}' -> '${target}' is not connected by declared transitions`,
1514
+ );
1515
+ }
1516
+ }
1517
+ }
1518
+
1519
+ function buildDefinedProcess<TParams, TState>(
1520
+ input: DefinedProcessInput<TParams, TState>,
1521
+ ): Pick<ExtensionProcessDefinition<TParams, TState>, "turns" | "worker" | "server"> {
1522
+ const turnEntries = getTurnEntries(input.turns);
1523
+ if (turnEntries.length === 0) {
1524
+ throw new Error(`Process '${input.id}' must declare at least one turn`);
1525
+ }
1526
+ const knownTurnIds = new Set(turnEntries.map(([turnId]) => turnId));
1527
+ const turnDefinitionsById = new Map<TurnId, TurnDefinition<unknown, unknown>>(
1528
+ turnEntries.map(([turnId, turnSpec]) => [turnId, turnSpec as TurnDefinition<unknown, unknown>]),
1529
+ );
1530
+ if (!knownTurnIds.has(input.entry)) {
1531
+ throw new Error(`Process '${input.id}' entry turn '${input.entry}' is not declared`);
1532
+ }
1533
+ const seenEntries = new Set<TurnId>();
1534
+ for (const turnId of [input.entry, ...(input.alternateEntries ?? [])]) {
1535
+ if (seenEntries.has(turnId)) {
1536
+ throw new Error(`Process '${input.id}' declares duplicate entry turn '${turnId}'`);
1537
+ }
1538
+ if (!knownTurnIds.has(turnId)) {
1539
+ throw new Error(`Process '${input.id}' entry turn '${turnId}' is not declared`);
1540
+ }
1541
+ seenEntries.add(turnId);
1542
+ }
1543
+
1544
+ if (input.happyPath) {
1545
+ if (input.happyPath.length === 0) {
1546
+ throw new Error(`Process '${input.id}' declares an empty happy path`);
1547
+ }
1548
+ const seen = new Set<TurnId>();
1549
+ for (const turnId of input.happyPath) {
1550
+ if (!knownTurnIds.has(turnId)) {
1551
+ throw new Error(`Process '${input.id}' happy path references undeclared turn '${turnId}'`);
1552
+ }
1553
+ if (seen.has(turnId)) {
1554
+ throw new Error(`Process '${input.id}' happy path repeats turn '${turnId}'`);
1555
+ }
1556
+ seen.add(turnId);
1557
+ }
1558
+ if (input.happyPath[0] !== input.entry) {
1559
+ throw new Error(
1560
+ `Process '${input.id}' happy path must start at the entry turn '${input.entry}'`,
1561
+ );
1562
+ }
1563
+ }
1564
+
1565
+ const turns = new Map<TurnId, ProcessTurnBinding<TurnDefinition<TParams, TState>>>();
1566
+ const actionUses = new Map<string, CompiledActionUse<TParams, TState>[]>();
1567
+ const outcomeEffects = new Map<
1568
+ TurnId,
1569
+ ReadonlyMap<string, ProcessOutcomeEffect<TParams, TState> | undefined>
1570
+ >();
1571
+ const executableTurns = new Map<TurnId, CompiledExecutableTurn<TParams, TState>>();
1572
+
1573
+ for (const [turnId, turnSpec] of turnEntries) {
1574
+ if (turnSpec.kind === "llm") {
1575
+ const compiledOutcomes = compileTurnOutcomeDefinitions({
1576
+ turnId,
1577
+ outcomes: turnSpec.outcomes,
1578
+ turnEnd: turnSpec.turnEnd,
1579
+ knownTurnIds,
1580
+ turnDefinitionsById,
1581
+ });
1582
+ turns.set(turnId, createProcessTurnBinding(turnSpec, compiledOutcomes.transitions));
1583
+ outcomeEffects.set(turnId, compiledOutcomes.effects);
1584
+ executableTurns.set(turnId, {
1585
+ kind: "llm",
1586
+ id: turnId,
1587
+ spec: turnSpec,
1588
+ });
1589
+ continue;
1590
+ }
1591
+
1592
+ if (turnSpec.kind === "automatic" || turnSpec.kind === "server_automatic") {
1593
+ const compiledOutcomes = compileTurnOutcomeDefinitions({
1594
+ turnId,
1595
+ outcomes: turnSpec.outcomes,
1596
+ turnEnd: turnSpec.turnEnd,
1597
+ knownTurnIds,
1598
+ turnDefinitionsById,
1599
+ });
1600
+ turns.set(turnId, createProcessTurnBinding(turnSpec, compiledOutcomes.transitions));
1601
+ outcomeEffects.set(turnId, compiledOutcomes.effects);
1602
+ if (turnSpec.kind === "automatic") {
1603
+ executableTurns.set(turnId, {
1604
+ kind: "automatic",
1605
+ id: turnId,
1606
+ spec: turnSpec,
1607
+ });
1608
+ }
1609
+ continue;
1610
+ }
1611
+
1612
+ if (turnSpec.kind === "human") {
1613
+ const compiled = compileHumanTurn({
1614
+ turnId,
1615
+ spec: turnSpec,
1616
+ knownTurnIds,
1617
+ turnDefinitionsById,
1618
+ actionUses,
1619
+ });
1620
+ turns.set(turnId, compiled.binding);
1621
+ continue;
1622
+ }
1623
+
1624
+ const compiled = compileExternalTurn({
1625
+ turnId,
1626
+ spec: turnSpec,
1627
+ knownTurnIds,
1628
+ });
1629
+ turns.set(turnId, compiled.binding);
1630
+ }
1631
+
1632
+ validateHappyPathConnectivity({
1633
+ processId: input.id,
1634
+ happyPath: input.happyPath,
1635
+ turns,
1636
+ turnDefinitionsById,
1637
+ });
1638
+
1639
+ const worker: ExtensionProcessDefinition<TParams, TState>["worker"] = (api) => {
1640
+ api.start(input.entry);
1641
+ const manuallyRegisteredTurns = new Set<TurnId>();
1642
+ input.worker?.({
1643
+ start(turnId) {
1644
+ api.start(turnId);
1645
+ },
1646
+ turn(turnId, handler) {
1647
+ manuallyRegisteredTurns.add(turnId);
1648
+ api.turn(turnId, handler);
1649
+ },
1650
+ });
1651
+ for (const executable of executableTurns.values()) {
1652
+ if (manuallyRegisteredTurns.has(executable.id)) {
1653
+ continue;
1654
+ }
1655
+ if (executable.kind === "llm") {
1656
+ api.turn(executable.id, async (run) => {
1657
+ await run.turn(executable.spec);
1658
+ });
1659
+ continue;
1660
+ }
1661
+ api.turn(executable.id, async (run) => {
1662
+ await run.complete(await executable.spec.run(run.ctx));
1663
+ });
1664
+ }
1665
+ };
1666
+
1667
+ const server: ExtensionProcessDefinition<TParams, TState>["server"] = (api) => {
1668
+ for (const [actionId, uses] of actionUses) {
1669
+ const [firstUse] = uses;
1670
+ const form = firstUse?.form;
1671
+ for (const use of uses) {
1672
+ if (!areFormsEquivalent(form, use.form)) {
1673
+ throw new Error(
1674
+ `Action '${actionId}' must use the same form on every turn that references it`,
1675
+ );
1676
+ }
1677
+ }
1678
+ api.action({
1679
+ id: actionId,
1680
+ label: firstUse?.label ?? actionId,
1681
+ ...(form ? { form } : {}),
1682
+ async plan(inputValue, ctx) {
1683
+ const turnId = ctx.process.selectedTurnId;
1684
+ const use = uses.find((candidate) => candidate.turnId === turnId);
1685
+ if (!use || !turnId) {
1686
+ throw new Error(
1687
+ `Action '${actionId}' is not available for selected turn '${String(turnId)}'`,
1688
+ );
1689
+ }
1690
+ const resolvedRoute = await resolveActionRouteForExecution({
1691
+ use,
1692
+ actionId,
1693
+ ctx,
1694
+ inputValue,
1695
+ });
1696
+ const effectResult = use.effect
1697
+ ? await use.effect({
1698
+ ctx: makeProcessServerRuntimeContext(ctx),
1699
+ input: inputValue,
1700
+ turnId,
1701
+ actionId,
1702
+ ...(resolvedRoute.selectedBranchId
1703
+ ? { selectedBranchId: resolvedRoute.selectedBranchId }
1704
+ : {}),
1705
+ })
1706
+ : undefined;
1707
+ const formState = applyFormStateFields({
1708
+ form: use.form,
1709
+ inputValue,
1710
+ state: effectResult?.state ?? ctx.state,
1711
+ });
1712
+ const result = formState
1713
+ ? mergeProcessEffectPlans(effectResult, { state: formState })
1714
+ : effectResult;
1715
+ await applyProcessEffectPlan({
1716
+ ctx,
1717
+ result,
1718
+ transition: buildActionTransitionRequest(resolvedRoute.route),
1719
+ });
1720
+ },
1721
+ });
1722
+ }
1723
+
1724
+ for (const [turnId, effects] of outcomeEffects) {
1725
+ api.onTurnOutcome(turnId, async (event, ctx) => {
1726
+ const effect = effects.get(event.outcome);
1727
+ if (!effect) {
1728
+ return;
1729
+ }
1730
+ const result = await effect({
1731
+ ctx: makeProcessServerRuntimeContext(ctx),
1732
+ event,
1733
+ turnId,
1734
+ outcome: event.outcome,
1735
+ });
1736
+ await applyProcessEffectPlan({ ctx, result });
1737
+ });
1738
+ }
1739
+
1740
+ input.server?.(api);
1741
+ };
1742
+
1743
+ return {
1744
+ turns,
1745
+ worker,
1746
+ server,
1747
+ };
1748
+ }
1749
+
1750
+ export function defineProcess<TParams = unknown, TState = unknown>(
1751
+ input: DefinedProcessInput<TParams, TState>,
1752
+ ): ProcessDefinition<TParams, TState> {
1753
+ const compiled = buildDefinedProcess(input);
1754
+ const process = {
1755
+ id: input.id,
1756
+ displayName: input.displayName,
1757
+ entryTurnId: input.entry,
1758
+ alternateEntryTurnIds: [...(input.alternateEntries ?? [])],
1759
+ ...(input.happyPath ? { happyPath: [...input.happyPath] } : {}),
1760
+ turns: compiled.turns,
1761
+ paramsCodec: input.paramsCodec,
1762
+ stateCodec: input.stateCodec,
1763
+ initialState: input.initialState,
1764
+ ...(input.repositoryCredentials ? { repositoryCredentials: input.repositoryCredentials } : {}),
1765
+ ...(input.piConfig ? { piConfig: input.piConfig } : {}),
1766
+ server: compiled.server,
1767
+ worker: compiled.worker,
1768
+ ui: input.ui,
1769
+ launchers: input.launchers,
1770
+ watchers: input.watchers,
1771
+ };
1772
+ markDefinedProcess(process);
1773
+ return process;
1774
+ }
1775
+
1776
+ type RoutableTurnDefinition<TOutcome extends string, TParams, TState> =
1777
+ | LlmTurnDefinition<TOutcome, TParams, TState>
1778
+ | AutomaticTurnDefinition<TOutcome, TParams, TState>
1779
+ | ServerAutomaticTurnDefinition<TOutcome, TParams, TState>;
1780
+
1781
+ // biome-ignore-start lint/suspicious/noExplicitAny: conditional helper types must match and preserve any routable turn instantiation
1782
+ type RoutableOutcome<TTurn> =
1783
+ TTurn extends RoutableTurnDefinition<infer TOutcome, any, any> ? TOutcome : never;
1784
+ type RoutableParams<TTurn> =
1785
+ TTurn extends RoutableTurnDefinition<any, infer TParams, any> ? TParams : never;
1786
+ type RoutableState<TTurn> =
1787
+ TTurn extends RoutableTurnDefinition<any, any, infer TState> ? TState : never;
1788
+
1789
+ export function routeTurnOutcomes<TTurn extends RoutableTurnDefinition<string, any, any>>(
1790
+ baseTurn: TTurn,
1791
+ routes: Partial<
1792
+ Record<RoutableOutcome<TTurn>, OutcomeRouteSpec<RoutableParams<TTurn>, RoutableState<TTurn>>>
1793
+ >,
1794
+ options: OutcomeRouteOptions = {},
1795
+ ): TTurn {
1796
+ type TOutcome = RoutableOutcome<TTurn>;
1797
+ type TParams = RoutableParams<TTurn>;
1798
+ type TState = RoutableState<TTurn>;
1799
+ const baseOutcomes = (baseTurn.outcomes ?? {}) as Partial<
1800
+ Record<TOutcome, ProcessToolOutcomeSpec<TParams, TState>>
1801
+ >;
1802
+ for (const outcomeId of Object.keys(routes) as TOutcome[]) {
1803
+ if (!baseOutcomes[outcomeId]) {
1804
+ throw new Error(`Cannot route unknown outcome '${outcomeId}' on reusable turn`);
1805
+ }
1806
+ }
1807
+ if (options.strict) {
1808
+ for (const outcomeId of Object.keys(baseOutcomes) as TOutcome[]) {
1809
+ if (!routes[outcomeId]) {
1810
+ throw new Error(`Strict routing omitted outcome '${outcomeId}' on reusable turn`);
1811
+ }
1812
+ }
1813
+ }
1814
+ return {
1815
+ ...baseTurn,
1816
+ outcomes: Object.fromEntries(
1817
+ (
1818
+ Object.entries(baseOutcomes) as Array<[TOutcome, ProcessToolOutcomeSpec<TParams, TState>]>
1819
+ ).map(([outcomeId, baseOutcome]) => [
1820
+ outcomeId,
1821
+ { ...baseOutcome, ...(routes[outcomeId] ?? {}) },
1822
+ ]),
1823
+ ) as Partial<Record<TOutcome, ProcessToolOutcomeSpec<TParams, TState>>>,
1824
+ };
1825
+ }
1826
+ // biome-ignore-end lint/suspicious/noExplicitAny: end routable turn instantiation helper suppression
1827
+
1828
+ export function llmTurn<TParams = unknown, TState = unknown, TOutcome extends string = string>(
1829
+ input: Omit<LlmTurnDefinition<TOutcome, TParams, TState>, "kind">,
1830
+ ): LlmTurnDefinition<TOutcome, TParams, TState> {
1831
+ return {
1832
+ ...input,
1833
+ kind: "llm",
1834
+ };
1835
+ }
1836
+
1837
+ export function automaticTurn<
1838
+ TParams = unknown,
1839
+ TState = unknown,
1840
+ TOutcome extends string = string,
1841
+ >(
1842
+ input: Omit<AutomaticTurnDefinition<TOutcome, TParams, TState>, "kind">,
1843
+ ): AutomaticTurnDefinition<TOutcome, TParams, TState> {
1844
+ return {
1845
+ ...input,
1846
+ kind: "automatic",
1847
+ };
1848
+ }
1849
+
1850
+ export function serverAutomaticTurn<
1851
+ TParams = unknown,
1852
+ TState = unknown,
1853
+ TOutcome extends string = string,
1854
+ >(
1855
+ input: Omit<ServerAutomaticTurnDefinition<TOutcome, TParams, TState>, "kind">,
1856
+ ): ServerAutomaticTurnDefinition<TOutcome, TParams, TState> {
1857
+ return {
1858
+ ...input,
1859
+ kind: "server_automatic",
1860
+ };
1861
+ }
1862
+
1863
+ export function humanTurn<TParams = unknown, TState = unknown>(
1864
+ input: Omit<HumanTurnDefinition<TParams, TState>, "kind">,
1865
+ ): HumanTurnDefinition<TParams, TState> {
1866
+ return {
1867
+ ...input,
1868
+ kind: "human",
1869
+ };
1870
+ }
1871
+
1872
+ export function externalTurn<TParams = unknown, TState = unknown>(
1873
+ input: Omit<ExternalTurnDefinition<TParams, TState>, "kind">,
1874
+ ): ExternalTurnDefinition<TParams, TState> {
1875
+ return {
1876
+ ...input,
1877
+ kind: "external",
1878
+ };
1879
+ }