@leitwerk-dev/process-sdk 0.1.8 → 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 (171) 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 +76 -34
  6. package/dist/core-capabilities.d.ts.map +1 -1
  7. package/dist/define-process.d.ts +36 -55
  8. package/dist/define-process.d.ts.map +1 -1
  9. package/dist/{extension-api-CqPGRqc9.d.ts → extension-api-CcqZCYJx.d.ts} +160 -74
  10. package/dist/extension-api.d.ts +120 -5
  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 +92 -110
  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 +1 -2
  40. package/dist/process-graph.d.ts.map +1 -1
  41. package/dist/process-watcher-source.d.ts +3 -1
  42. package/dist/process-watcher-source.d.ts.map +1 -1
  43. package/dist/project-binding.d.ts +9 -0
  44. package/dist/project-binding.d.ts.map +1 -0
  45. package/dist/registry-utils.d.ts.map +1 -1
  46. package/dist/repository-feedback.d.ts +29 -0
  47. package/dist/repository-feedback.d.ts.map +1 -0
  48. package/dist/repository-git-env.d.ts +2 -0
  49. package/dist/repository-git-env.d.ts.map +1 -1
  50. package/dist/repository-http.d.ts +19 -0
  51. package/dist/repository-http.d.ts.map +1 -0
  52. package/dist/repository-https.d.ts +3 -0
  53. package/dist/repository-https.d.ts.map +1 -0
  54. package/dist/repository-issue-watcher.d.ts +31 -0
  55. package/dist/repository-issue-watcher.d.ts.map +1 -0
  56. package/dist/repository-source-config.d.ts +32 -0
  57. package/dist/repository-source-config.d.ts.map +1 -0
  58. package/dist/repository-types.d.ts +36 -0
  59. package/dist/repository-types.d.ts.map +1 -0
  60. package/dist/review-flow.js +12 -43
  61. package/dist/review-flow.js.map +1 -1
  62. package/dist/runtime-internals.js +18 -2
  63. package/dist/runtime-internals.js.map +1 -1
  64. package/dist/state-helpers.d.ts +3 -2
  65. package/dist/state-helpers.d.ts.map +1 -1
  66. package/dist/subprocess-env.d.ts +1 -0
  67. package/dist/subprocess-env.d.ts.map +1 -1
  68. package/dist/tool-arguments.d.ts +7 -0
  69. package/dist/tool-arguments.d.ts.map +1 -0
  70. package/dist/turn-semantics.d.ts +5 -6
  71. package/dist/turn-semantics.d.ts.map +1 -1
  72. package/dist/types.d.ts +5 -15
  73. package/dist/types.d.ts.map +1 -1
  74. package/package.json +6 -5
  75. package/src/core-capabilities.ts +90 -37
  76. package/src/define-process.ts +231 -277
  77. package/src/extension-api.ts +148 -4
  78. package/src/external-action-source.ts +12 -0
  79. package/src/external-source-poll.ts +49 -0
  80. package/src/flow.ts +427 -646
  81. package/src/fs-utils.ts +17 -2
  82. package/src/index.ts +56 -13
  83. package/src/integration-http.ts +58 -0
  84. package/src/json-data.ts +25 -0
  85. package/src/leaf-outcomes.ts +1 -9
  86. package/src/model-provider.ts +10 -23
  87. package/src/pi-config.ts +1 -6
  88. package/src/process-flow-view.ts +32 -88
  89. package/src/process-graph.ts +25 -54
  90. package/src/process-watcher-source.ts +13 -8
  91. package/src/project-binding.ts +36 -0
  92. package/src/registry-utils.ts +1 -5
  93. package/src/repository-feedback.ts +59 -0
  94. package/src/repository-git-env.ts +34 -0
  95. package/src/repository-http.ts +71 -0
  96. package/src/repository-https.ts +22 -0
  97. package/src/repository-issue-watcher.ts +92 -0
  98. package/src/repository-source-config.ts +60 -0
  99. package/src/repository-types.ts +25 -0
  100. package/src/state-helpers.ts +8 -9
  101. package/src/subprocess-env.ts +6 -0
  102. package/src/tool-arguments.ts +37 -0
  103. package/src/turn-semantics.ts +31 -75
  104. package/src/types.ts +5 -15
  105. package/dist/browser-ui-extension.js +0 -2
  106. package/dist/browser-ui-extension.js.map +0 -1
  107. package/dist/capabilities.js +0 -7
  108. package/dist/capabilities.js.map +0 -1
  109. package/dist/chunk-TRQJ5PRM.js.map +0 -1
  110. package/dist/codecs.js +0 -9
  111. package/dist/codecs.js.map +0 -1
  112. package/dist/commit-message.js +0 -3
  113. package/dist/commit-message.js.map +0 -1
  114. package/dist/core-capabilities.js +0 -6
  115. package/dist/core-capabilities.js.map +0 -1
  116. package/dist/define-process.js +0 -1040
  117. package/dist/define-process.js.map +0 -1
  118. package/dist/event-bus.js +0 -31
  119. package/dist/event-bus.js.map +0 -1
  120. package/dist/extension-api.js +0 -5
  121. package/dist/extension-api.js.map +0 -1
  122. package/dist/flow.js +0 -1565
  123. package/dist/flow.js.map +0 -1
  124. package/dist/form-contract.js +0 -2
  125. package/dist/form-contract.js.map +0 -1
  126. package/dist/fs-utils.js +0 -23
  127. package/dist/fs-utils.js.map +0 -1
  128. package/dist/graph-fragments.js +0 -57
  129. package/dist/graph-fragments.js.map +0 -1
  130. package/dist/host-capabilities.js +0 -42
  131. package/dist/host-capabilities.js.map +0 -1
  132. package/dist/launcher-contract.js +0 -2
  133. package/dist/launcher-contract.js.map +0 -1
  134. package/dist/leaf-outcomes.js +0 -52
  135. package/dist/leaf-outcomes.js.map +0 -1
  136. package/dist/model-provider.js +0 -171
  137. package/dist/model-provider.js.map +0 -1
  138. package/dist/process-definition-internals.js +0 -25
  139. package/dist/process-definition-internals.js.map +0 -1
  140. package/dist/process-flow-view.js +0 -418
  141. package/dist/process-flow-view.js.map +0 -1
  142. package/dist/process-graph.js +0 -213
  143. package/dist/process-graph.js.map +0 -1
  144. package/dist/process-launcher-builder.js +0 -43
  145. package/dist/process-launcher-builder.js.map +0 -1
  146. package/dist/process-watcher-builder.js +0 -40
  147. package/dist/process-watcher-builder.js.map +0 -1
  148. package/dist/process-watcher-source.js +0 -45
  149. package/dist/process-watcher-source.js.map +0 -1
  150. package/dist/registry-utils.js +0 -18
  151. package/dist/registry-utils.js.map +0 -1
  152. package/dist/repository-git-env.js +0 -26
  153. package/dist/repository-git-env.js.map +0 -1
  154. package/dist/server-events.js +0 -2
  155. package/dist/server-events.js.map +0 -1
  156. package/dist/server-process-builder.js +0 -52
  157. package/dist/server-process-builder.js.map +0 -1
  158. package/dist/state-helpers.js +0 -20
  159. package/dist/state-helpers.js.map +0 -1
  160. package/dist/subprocess-env.js +0 -34
  161. package/dist/subprocess-env.js.map +0 -1
  162. package/dist/tool-renderers.js +0 -63
  163. package/dist/tool-renderers.js.map +0 -1
  164. package/dist/turn-semantics.js +0 -365
  165. package/dist/turn-semantics.js.map +0 -1
  166. package/dist/types.js +0 -23
  167. package/dist/types.js.map +0 -1
  168. package/dist/ui-process-builder.js +0 -30
  169. package/dist/ui-process-builder.js.map +0 -1
  170. package/dist/worker-process-builder.js +0 -22
  171. package/dist/worker-process-builder.js.map +0 -1
package/src/flow.ts CHANGED
@@ -1,15 +1,14 @@
1
1
  import path from "node:path";
2
2
  import {
3
3
  assertValidProcessProductName,
4
- createReviewSubject,
5
4
  humanizeProcessLabel,
6
5
  type ProcessInstance,
7
6
  type ProcessProject,
8
7
  type ProcessSemanticEntryRefKey,
9
8
  type ProcessTurnStartSelection,
10
9
  type ProcessTurnTerminalLifecycleStatus,
11
- type ReviewSubject,
12
10
  type TurnId,
11
+ type TurnProgressReport,
13
12
  } from "@leitwerk-dev/domain";
14
13
  import type {
15
14
  AutomaticTurnDefinition,
@@ -28,8 +27,6 @@ import type {
28
27
  ProcessRuntimeTurnContext,
29
28
  ProcessToolOutcomeSpec,
30
29
  ProcessTurnEndSpec,
31
- ServerAutomaticTurnDefinition,
32
- ServerAutomaticTurnRestartBehavior,
33
30
  TurnDefinition,
34
31
  TurnDefinitionRecord,
35
32
  } from "./define-process.js";
@@ -45,12 +42,16 @@ import type {
45
42
  ProcessLauncherDefinition,
46
43
  ProcessWatcherAPI,
47
44
  ProcessWatcherDefinition,
48
- RepositoryCredentialProject,
49
- RepositoryCredentialRequirement,
50
45
  ServerProcessAPI,
51
46
  UiProcessAPI,
52
47
  WorkerCompleteInput,
53
48
  } from "./extension-api.js";
49
+ import { isPathInside } from "./fs-utils.js";
50
+ import {
51
+ type ProcessGraphSource,
52
+ toProcessGraphView,
53
+ validateProcessGraphProducts,
54
+ } from "./process-graph.js";
54
55
  import type { OutcomeToolParameterSpec, PiBuiltInToolName, ProcessPiConfig } from "./types.js";
55
56
 
56
57
  type MaybePromise<T> = T | Promise<T>;
@@ -83,15 +84,6 @@ export interface FlowAutomaticTurn<
83
84
  definition: AutomaticTurnDefinition<TOutcome, TParams, TState>;
84
85
  }
85
86
 
86
- export interface FlowServerAutomaticTurn<
87
- TParams = unknown,
88
- TState = unknown,
89
- TOutcome extends string = string,
90
- > {
91
- id: TurnId;
92
- definition: ServerAutomaticTurnDefinition<TOutcome, TParams, TState>;
93
- }
94
-
95
87
  export interface FlowHumanTurn<TParams = unknown, TState = unknown> {
96
88
  id: TurnId;
97
89
  definition: HumanTurnDefinition<TParams, TState>;
@@ -105,7 +97,6 @@ export interface FlowExternalTurn<TParams = unknown, TState = unknown> {
105
97
  export type FlowTurn<TParams = unknown, TState = unknown> =
106
98
  | FlowLlmTurn<TParams, TState, string>
107
99
  | FlowAutomaticTurn<TParams, TState, string>
108
- | FlowServerAutomaticTurn<TParams, TState, string>
109
100
  | FlowHumanTurn<TParams, TState>
110
101
  | FlowExternalTurn<TParams, TState>
111
102
  | { id: TurnId; definition: TurnDefinition<TParams, TState> };
@@ -139,11 +130,12 @@ export interface FlowRepoLookup {
139
130
  all(): FlowRepoContext[];
140
131
  }
141
132
 
142
- export interface FlowPromptContext<
133
+ export type FlowPromptContext<
143
134
  TParams = unknown,
144
135
  TState = unknown,
145
136
  TConsumedProducts extends string = string,
146
- > {
137
+ TPrepared = undefined,
138
+ > = {
147
139
  process: ProcessInstance;
148
140
  projects: readonly ProcessProject[];
149
141
  params: TParams;
@@ -154,7 +146,7 @@ export interface FlowPromptContext<
154
146
  };
155
147
  input: Readonly<Partial<Record<TConsumedProducts, string>>>;
156
148
  repo: FlowRepoLookup;
157
- }
149
+ } & ([TPrepared] extends [undefined] ? { prepared?: undefined } : { prepared: TPrepared });
158
150
 
159
151
  export interface FlowAutomaticRunContext<TParams = unknown, TState = unknown> {
160
152
  process: ProcessInstance;
@@ -163,17 +155,16 @@ export interface FlowAutomaticRunContext<TParams = unknown, TState = unknown> {
163
155
  state: TState;
164
156
  workspaceRoot?: string;
165
157
  repo: FlowRepoLookup;
158
+ callIntegrationTool(name: string, args: Record<string, unknown>): Promise<unknown>;
159
+ reportProgress(report: TurnProgressReport): void;
166
160
  }
167
161
 
168
- export interface FlowLlmOutcomeEffectContext<TParams = unknown, TState = unknown> {
169
- process: ProcessInstance;
170
- projects: readonly ProcessProject[];
171
- params: TParams;
172
- state: TState;
173
- output: { content: string | null } | null;
174
- }
162
+ export type FlowLlmPreparationContext<
163
+ TParams = unknown,
164
+ TState = unknown,
165
+ > = FlowAutomaticRunContext<TParams, TState>;
175
166
 
176
- export interface FlowAutomaticOutcomeEffectContext<TParams = unknown, TState = unknown> {
167
+ interface FlowOutcomeEffectContext<TParams = unknown, TState = unknown> {
177
168
  process: ProcessInstance;
178
169
  projects: readonly ProcessProject[];
179
170
  params: TParams;
@@ -181,6 +172,12 @@ export interface FlowAutomaticOutcomeEffectContext<TParams = unknown, TState = u
181
172
  output: { content: string | null } | null;
182
173
  }
183
174
 
175
+ export interface FlowLlmOutcomeEffectContext<TParams = unknown, TState = unknown>
176
+ extends FlowOutcomeEffectContext<TParams, TState> {}
177
+
178
+ export interface FlowAutomaticOutcomeEffectContext<TParams = unknown, TState = unknown>
179
+ extends FlowOutcomeEffectContext<TParams, TState> {}
180
+
184
181
  export interface FlowExternalSourceContext<
185
182
  TParams = unknown,
186
183
  TState = unknown,
@@ -203,13 +200,6 @@ type FlowOutcomeStateEffect<TParams, TState, TContext> = (
203
200
  input: FlowOutcomeEffectInput<TParams, TState, TContext>,
204
201
  ) => MaybePromise<TState>;
205
202
 
206
- type SnapshotContext<TParams, TState> = {
207
- process: ProcessInstance;
208
- projects: readonly ProcessProject[];
209
- params: TParams;
210
- state: TState;
211
- };
212
-
213
203
  function textField(input: {
214
204
  description: string;
215
205
  requiredErrorCode: string;
@@ -263,16 +253,6 @@ function readInitialPrompt<TParams>(params: TParams): string {
263
253
  return "";
264
254
  }
265
255
 
266
- function isPathInside(parent: string, child: string): boolean {
267
- const relative = path.relative(parent, child);
268
- return (
269
- relative !== "" &&
270
- relative !== ".." &&
271
- !relative.startsWith(`..${path.sep}`) &&
272
- !path.isAbsolute(relative)
273
- );
274
- }
275
-
276
256
  function safeJoinInside(parent: string, childPath: string, context: string): string {
277
257
  const parentPath = path.resolve(parent);
278
258
  const targetPath = path.resolve(parentPath, childPath);
@@ -382,37 +362,37 @@ function createFlowRepoLookup(input: {
382
362
  workspaceRoot?: string;
383
363
  }): FlowRepoLookup {
384
364
  return {
385
- get: (key) =>
386
- resolveRepoByKey({
387
- projects: input.projects,
388
- workspaceRoot: input.workspaceRoot,
389
- key,
390
- required: true,
391
- }),
392
- optional: (key) =>
393
- resolveRepoByKey({
394
- projects: input.projects,
395
- workspaceRoot: input.workspaceRoot,
396
- key,
397
- required: false,
398
- }),
365
+ get: (key) => resolveRepoByKey({ ...input, key, required: true }),
366
+ optional: (key) => resolveRepoByKey({ ...input, key, required: false }),
399
367
  all: () =>
400
368
  input.projects.map((project) =>
401
- resolveRepoByKey({
402
- projects: input.projects,
403
- workspaceRoot: input.workspaceRoot,
404
- key: project.key,
405
- required: true,
406
- }),
369
+ resolveRepoByKey({ ...input, key: project.key, required: true }),
407
370
  ),
408
371
  };
409
372
  }
410
373
 
411
- export function createFlowPromptContext<TParams, TState, TConsumedProducts extends string = string>(
374
+ function createFlowContextBase<TParams, TState>(ctx: ProcessRuntimeTurnContext<TParams, TState>) {
375
+ const { process, projects, params, state, workspaceRoot } = ctx;
376
+ return {
377
+ process,
378
+ projects,
379
+ params,
380
+ state,
381
+ ...(workspaceRoot ? { workspaceRoot } : {}),
382
+ repo: createFlowRepoLookup({ projects, workspaceRoot }),
383
+ };
384
+ }
385
+
386
+ export function createFlowPromptContext<
387
+ TParams,
388
+ TState,
389
+ TConsumedProducts extends string = string,
390
+ TPrepared = undefined,
391
+ >(
412
392
  ctx: ProcessRuntimeTurnContext<TParams, TState>,
413
393
  consumedProducts: readonly TConsumedProducts[],
414
394
  optionalConsumedProducts: readonly string[] = [],
415
- ): FlowPromptContext<TParams, TState, TConsumedProducts> {
395
+ ): FlowPromptContext<TParams, TState, TConsumedProducts, TPrepared> {
416
396
  const productInput: Record<string, string> = {};
417
397
  for (const productName of consumedProducts) {
418
398
  const markdown = ctx.turnResultMarkdownByProduct?.[productName];
@@ -433,88 +413,49 @@ export function createFlowPromptContext<TParams, TState, TConsumedProducts exten
433
413
  }
434
414
  }
435
415
  return {
436
- process: ctx.process,
437
- projects: ctx.projects,
438
- params: ctx.params,
439
- state: ctx.state,
440
- ...(ctx.workspaceRoot ? { workspaceRoot: ctx.workspaceRoot } : {}),
416
+ ...createFlowContextBase(ctx),
441
417
  prompts: {
442
418
  initial: readInitialPrompt(ctx.params),
443
419
  },
444
420
  input: productInput as Partial<Record<TConsumedProducts, string>>,
445
- repo: createFlowRepoLookup({
446
- projects: ctx.projects,
447
- workspaceRoot: ctx.workspaceRoot,
448
- }),
449
- };
421
+ prepared: ctx.prepared as TPrepared,
422
+ } as FlowPromptContext<TParams, TState, TConsumedProducts, TPrepared>;
450
423
  }
451
424
 
452
425
  export function createFlowAutomaticRunContext<TParams, TState>(
453
426
  ctx: ProcessRuntimeTurnContext<TParams, TState>,
454
427
  ): FlowAutomaticRunContext<TParams, TState> {
455
428
  return {
456
- process: ctx.process,
457
- projects: ctx.projects,
458
- params: ctx.params,
459
- state: ctx.state,
460
- ...(ctx.workspaceRoot ? { workspaceRoot: ctx.workspaceRoot } : {}),
461
- repo: createFlowRepoLookup({
462
- projects: ctx.projects,
463
- workspaceRoot: ctx.workspaceRoot,
464
- }),
465
- };
466
- }
467
-
468
- function createFlowLlmOutcomeEffectContext<TParams, TState>(input: {
469
- ctx: SnapshotContext<TParams, TState>;
470
- event: ProcessOutcomeExecution<TParams, TState>["event"];
471
- }): FlowLlmOutcomeEffectContext<TParams, TState> {
472
- return {
473
- process: input.ctx.process,
474
- projects: input.ctx.projects,
475
- params: input.ctx.params,
476
- state: input.ctx.state,
477
- output:
478
- typeof input.event.turnResultMarkdown === "string"
479
- ? { content: input.event.turnResultMarkdown }
480
- : null,
481
- };
482
- }
483
-
484
- function createFlowAutomaticOutcomeEffectContext<TParams, TState>(input: {
485
- ctx: SnapshotContext<TParams, TState>;
486
- event: ProcessOutcomeExecution<TParams, TState>["event"];
487
- }): FlowAutomaticOutcomeEffectContext<TParams, TState> {
488
- return {
489
- process: input.ctx.process,
490
- projects: input.ctx.projects,
491
- params: input.ctx.params,
492
- state: input.ctx.state,
493
- output:
494
- typeof input.event.turnResultMarkdown === "string"
495
- ? { content: input.event.turnResultMarkdown }
496
- : null,
429
+ ...createFlowContextBase(ctx),
430
+ callIntegrationTool(name, args) {
431
+ if (!ctx.callIntegrationTool) {
432
+ throw new Error(`Automatic integration tool '${name}' is unavailable`);
433
+ }
434
+ return ctx.callIntegrationTool(name, args);
435
+ },
436
+ reportProgress(report) {
437
+ ctx.reportProgress?.(report);
438
+ },
497
439
  };
498
440
  }
499
441
 
500
- function wrapLlmOutcomeEffect<TParams, TState>(
501
- effect: FlowOutcomeEffect<TParams, TState, FlowLlmOutcomeEffectContext<TParams, TState>>,
502
- ): ProcessOutcomeEffect<TParams, TState> {
503
- return (execution) =>
504
- effect({
505
- ctx: createFlowLlmOutcomeEffectContext({ ctx: execution.ctx, event: execution.event }),
506
- event: execution.event,
507
- turnId: execution.turnId,
508
- outcome: execution.outcome,
509
- });
510
- }
511
-
512
- function wrapAutomaticOutcomeEffect<TParams, TState>(
513
- effect: FlowOutcomeEffect<TParams, TState, FlowAutomaticOutcomeEffectContext<TParams, TState>>,
514
- ): ProcessOutcomeEffect<TParams, TState> {
442
+ function wrapOutcomeCallback<TParams, TState, TResult>(
443
+ callback: (
444
+ input: FlowOutcomeEffectInput<TParams, TState, FlowOutcomeEffectContext<TParams, TState>>,
445
+ ) => TResult,
446
+ ): (execution: ProcessOutcomeExecution<TParams, TState>) => TResult {
515
447
  return (execution) =>
516
- effect({
517
- ctx: createFlowAutomaticOutcomeEffectContext({ ctx: execution.ctx, event: execution.event }),
448
+ callback({
449
+ ctx: {
450
+ process: execution.ctx.process,
451
+ projects: execution.ctx.projects,
452
+ params: execution.ctx.params,
453
+ state: execution.ctx.state,
454
+ output:
455
+ typeof execution.event.turnResultMarkdown === "string"
456
+ ? { content: execution.event.turnResultMarkdown }
457
+ : null,
458
+ },
518
459
  event: execution.event,
519
460
  turnId: execution.turnId,
520
461
  outcome: execution.outcome,
@@ -522,20 +463,10 @@ function wrapAutomaticOutcomeEffect<TParams, TState>(
522
463
  }
523
464
 
524
465
  class RouteAndEffectBuilder<TParams, TState, TContext> {
525
- protected target:
526
- | { kind: "to"; turnId: TurnId }
527
- | { kind: "complete" }
528
- | { kind: "lifecycleStatus"; status: ProcessTurnTerminalLifecycleStatus }
529
- | null = null;
466
+ protected target: FlowTargetSpec = null;
530
467
  protected flowEffect: FlowOutcomeEffect<TParams, TState, TContext> | undefined;
531
468
 
532
- protected setTarget(
533
- next:
534
- | { kind: "to"; turnId: TurnId }
535
- | { kind: "complete" }
536
- | { kind: "lifecycleStatus"; status: ProcessTurnTerminalLifecycleStatus }
537
- | null,
538
- ): this {
469
+ protected setTarget(next: FlowTargetSpec): this {
539
470
  if (this.target && next) {
540
471
  throw new Error("Flow route already declares a target");
541
472
  }
@@ -635,6 +566,25 @@ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEff
635
566
  protected outcomeDescription: string | null = null;
636
567
  protected parameters: Record<string, OutcomeToolParameterSpec> = {};
637
568
  protected publishedMarkdownParameter: string | null = null;
569
+ protected summaryParameter: string | null = null;
570
+
571
+ /** Optional concise result publication, separate from the full Markdown. */
572
+ resultSummary(name = "resultSummary"): this {
573
+ this.summaryParameter = name;
574
+ return this.parameter(name, {
575
+ type: "string",
576
+ description: "Concise summary of this attempt’s outcome.",
577
+ });
578
+ }
579
+
580
+ protected publishedMarkdownFields() {
581
+ return this.publishedMarkdownParameter
582
+ ? {
583
+ publishedProduct: this.publishedMarkdownParameter,
584
+ turnResultMarkdownParameter: this.publishedMarkdownParameter,
585
+ }
586
+ : {};
587
+ }
638
588
 
639
589
  description(text: string): this {
640
590
  this.outcomeDescription = text;
@@ -664,15 +614,24 @@ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEff
664
614
  };
665
615
  }
666
616
 
667
- string(name: string, options: string | ParameterOptions = {}): this {
617
+ private typedParameter(
618
+ name: string,
619
+ type: OutcomeToolParameterSpec["type"],
620
+ options: string | ArrayParameterOptions = {},
621
+ ): this {
668
622
  const resolved = typeof options === "string" ? { description: options } : options;
669
623
  return this.parameter(name, {
670
624
  ...resolved,
671
- type: "string",
625
+ type,
672
626
  description: resolved.description ?? "",
627
+ ...(type === "array" ? { items: resolved.items ?? { type: "string" } } : {}),
673
628
  });
674
629
  }
675
630
 
631
+ string(name: string, options: string | ParameterOptions = {}): this {
632
+ return this.typedParameter(name, "string", options);
633
+ }
634
+
676
635
  markdown(name: string, options: string | MarkdownParameterOptions = {}): this {
677
636
  const resolved = typeof options === "string" ? { description: options } : options;
678
637
  const { publish, ...parameterOptions } = resolved;
@@ -683,78 +642,39 @@ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEff
683
642
  normalizeProductName(name);
684
643
  this.publishedMarkdownParameter = name;
685
644
  }
686
- return this.parameter(name, {
645
+ return this.typedParameter(name, "string", {
687
646
  ...parameterOptions,
688
647
  required: publish ? true : resolved.required,
689
648
  requiredErrorCode: resolved.requiredErrorCode ?? (publish ? `${name}_required` : undefined),
690
- type: "string",
691
- description: resolved.description ?? "",
692
649
  });
693
650
  }
694
651
 
695
652
  requiredString(name: string, options: string | ParameterOptions = {}): this {
696
- const resolved = this.withRequired(name, options);
697
- return this.parameter(name, {
698
- ...resolved,
699
- type: "string",
700
- description: resolved.description ?? "",
701
- });
653
+ return this.typedParameter(name, "string", this.withRequired(name, options));
702
654
  }
703
655
 
704
656
  number(name: string, options: string | ParameterOptions = {}): this {
705
- const resolved = typeof options === "string" ? { description: options } : options;
706
- return this.parameter(name, {
707
- ...resolved,
708
- type: "number",
709
- description: resolved.description ?? "",
710
- });
657
+ return this.typedParameter(name, "number", options);
711
658
  }
712
659
 
713
660
  requiredNumber(name: string, options: string | ParameterOptions = {}): this {
714
- const resolved = this.withRequired(name, options);
715
- return this.parameter(name, {
716
- ...resolved,
717
- type: "number",
718
- description: resolved.description ?? "",
719
- });
661
+ return this.typedParameter(name, "number", this.withRequired(name, options));
720
662
  }
721
663
 
722
664
  boolean(name: string, options: string | ParameterOptions = {}): this {
723
- const resolved = typeof options === "string" ? { description: options } : options;
724
- return this.parameter(name, {
725
- ...resolved,
726
- type: "boolean",
727
- description: resolved.description ?? "",
728
- });
665
+ return this.typedParameter(name, "boolean", options);
729
666
  }
730
667
 
731
668
  requiredBoolean(name: string, options: string | ParameterOptions = {}): this {
732
- const resolved = this.withRequired(name, options);
733
- return this.parameter(name, {
734
- ...resolved,
735
- type: "boolean",
736
- description: resolved.description ?? "",
737
- });
669
+ return this.typedParameter(name, "boolean", this.withRequired(name, options));
738
670
  }
739
671
 
740
672
  stringArray(name: string, options: string | ArrayParameterOptions = {}): this {
741
- const resolved = typeof options === "string" ? { description: options } : options;
742
- return this.parameter(name, {
743
- ...resolved,
744
- type: "array",
745
- description: resolved.description ?? "",
746
- items: resolved.items ?? { type: "string" },
747
- });
673
+ return this.typedParameter(name, "array", options);
748
674
  }
749
675
 
750
676
  requiredStringArray(name: string, options: string | ArrayParameterOptions = {}): this {
751
- const resolved = this.withRequired(name, options);
752
- return this.parameter(name, {
753
- ...resolved,
754
- type: "array",
755
- description: resolved.description ?? "",
756
- items: (resolved as ArrayParameterOptions).items ?? { type: "string" },
757
- });
677
+ return this.typedParameter(name, "array", this.withRequired(name, options));
758
678
  }
759
679
 
760
680
  enum(name: string, valuesOrOptions: readonly string[] | EnumParameterOptions): this {
@@ -771,22 +691,11 @@ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEff
771
691
  }
772
692
 
773
693
  object(name: string, options: string | ParameterOptions = {}): this {
774
- const resolved = typeof options === "string" ? { description: options } : options;
775
- return this.parameter(name, {
776
- ...resolved,
777
- type: "object",
778
- description: resolved.description ?? "",
779
- });
694
+ return this.typedParameter(name, "object", options);
780
695
  }
781
696
 
782
697
  array(name: string, options: string | ArrayParameterOptions = {}): this {
783
- const resolved = typeof options === "string" ? { description: options } : options;
784
- return this.parameter(name, {
785
- ...resolved,
786
- type: "array",
787
- description: resolved.description ?? "",
788
- items: resolved.items ?? { type: "string" },
789
- });
698
+ return this.typedParameter(name, "array", options);
790
699
  }
791
700
  }
792
701
 
@@ -798,21 +707,60 @@ export class OutcomeToolBuilder<
798
707
  TState,
799
708
  FlowLlmOutcomeEffectContext<TParams, TState>
800
709
  > {
710
+ private stateRouting:
711
+ | {
712
+ branches: Record<string, TurnId>;
713
+ choose: (
714
+ input: FlowOutcomeEffectInput<
715
+ TParams,
716
+ TState,
717
+ FlowLlmOutcomeEffectContext<TParams, TState>
718
+ >,
719
+ ) => MaybePromise<string>;
720
+ }
721
+ | undefined;
722
+
723
+ routeByState(
724
+ branches: Record<string, TurnId>,
725
+ choose: (
726
+ input: FlowOutcomeEffectInput<TParams, TState, FlowLlmOutcomeEffectContext<TParams, TState>>,
727
+ ) => MaybePromise<string>,
728
+ ): this {
729
+ if (this.hasRoute() || this.stateRouting) {
730
+ throw new Error("State-routed outcome cannot declare another route");
731
+ }
732
+ if (Object.keys(branches).length === 0) {
733
+ throw new Error("State-routed outcome must declare at least one branch");
734
+ }
735
+ this.stateRouting = { branches, choose };
736
+ return this;
737
+ }
738
+
801
739
  build(): ProcessToolOutcomeSpec<TParams, TState> {
802
740
  if (!this.outcomeDescription) {
803
741
  throw new Error("LLM outcome tool must declare .description(...)");
804
742
  }
743
+ if (this.stateRouting && this.hasRoute()) {
744
+ throw new Error("State-routed outcome cannot declare another route");
745
+ }
746
+ const stateRouting = this.stateRouting;
805
747
  return {
806
748
  description: this.outcomeDescription,
807
749
  parameters: this.parameters,
808
- ...(this.publishedMarkdownParameter
750
+ ...(this.summaryParameter ? { resultSummaryParameter: this.summaryParameter } : {}),
751
+ ...this.publishedMarkdownFields(),
752
+ ...(stateRouting
809
753
  ? {
810
- publishedProduct: this.publishedMarkdownParameter,
811
- turnResultMarkdownParameter: this.publishedMarkdownParameter,
754
+ branches: Object.fromEntries(
755
+ Object.entries(stateRouting.branches).map(([branchId, turnId]) => [
756
+ branchId,
757
+ { to: turnId },
758
+ ]),
759
+ ),
760
+ choose: wrapOutcomeCallback((input) => stateRouting.choose(input)),
812
761
  }
813
- : {}),
814
- ...this.buildRouteTarget(),
815
- ...(this.flowEffect ? { effect: wrapLlmOutcomeEffect(this.flowEffect) } : {}),
762
+ : this.buildRouteTarget()),
763
+ ...(this.flowEffect ? { effect: wrapOutcomeCallback(this.flowEffect) } : {}),
816
764
  };
817
765
  }
818
766
  }
@@ -825,21 +773,37 @@ export class AutomaticOutcomeBuilder<
825
773
  TState,
826
774
  FlowAutomaticOutcomeEffectContext<TParams, TState>
827
775
  > {
776
+ private waits = false;
777
+
778
+ wait(): this {
779
+ if (this.hasRoute()) throw new Error("Waiting outcome cannot declare another route");
780
+ this.waits = true;
781
+ return this;
782
+ }
783
+
828
784
  build(): ProcessToolOutcomeSpec<TParams, TState> {
829
785
  if (!this.outcomeDescription) {
830
786
  throw new Error("Automatic outcome must declare .description(...)");
831
787
  }
788
+ const configuredEffect = this.flowEffect ? wrapOutcomeCallback(this.flowEffect) : undefined;
789
+ const effect = this.waits
790
+ ? async (
791
+ execution: Parameters<NonNullable<ProcessToolOutcomeSpec<TParams, TState>["effect"]>>[0],
792
+ ) => {
793
+ const result = configuredEffect ? await configuredEffect(execution) : undefined;
794
+ return {
795
+ ...result,
796
+ processPatch: { ...(result?.processPatch ?? {}), lifecycleStatus: "waiting" as const },
797
+ };
798
+ }
799
+ : configuredEffect;
832
800
  return {
833
801
  description: this.outcomeDescription,
834
802
  parameters: this.parameters,
835
- ...(this.publishedMarkdownParameter
836
- ? {
837
- publishedProduct: this.publishedMarkdownParameter,
838
- turnResultMarkdownParameter: this.publishedMarkdownParameter,
839
- }
840
- : {}),
803
+ ...(this.summaryParameter ? { resultSummaryParameter: this.summaryParameter } : {}),
804
+ ...this.publishedMarkdownFields(),
841
805
  ...this.buildRouteTarget(),
842
- ...(this.flowEffect ? { effect: wrapAutomaticOutcomeEffect(this.flowEffect) } : {}),
806
+ ...(effect ? { effect } : {}),
843
807
  };
844
808
  }
845
809
  }
@@ -894,7 +858,7 @@ export class PlanResultBuilder<TParams = unknown, TState = unknown> extends Rout
894
858
  if (!this.reviewTurnId) {
895
859
  throw new Error("plan result must declare .review(turnId)");
896
860
  }
897
- const stateEffect = this.flowEffect ? wrapLlmOutcomeEffect(this.flowEffect) : undefined;
861
+ const stateEffect = this.flowEffect ? wrapOutcomeCallback(this.flowEffect) : undefined;
898
862
  return {
899
863
  description: this.resultDescription,
900
864
  parameters: {
@@ -915,106 +879,116 @@ export class PlanResultBuilder<TParams = unknown, TState = unknown> extends Rout
915
879
  }
916
880
  }
917
881
 
918
- export class PublishedResultBuilder<TParams = unknown, TState = unknown>
882
+ abstract class TurnEndBuilder<TParams, TState>
919
883
  extends RouteAndEffectBuilder<TParams, TState, FlowLlmOutcomeEffectContext<TParams, TState>>
920
884
  implements FlowLlmTurn<TParams, TState, string>
921
885
  {
886
+ protected abstract readonly builderName: string;
887
+
922
888
  constructor(
923
- private readonly productName: string,
889
+ private readonly outcomeId: string,
924
890
  private readonly parent?: FlowLlmTurn<TParams, TState, string>,
925
891
  ) {
926
892
  super();
927
893
  }
928
894
 
895
+ private get turn(): FlowLlmTurn<TParams, TState, string> {
896
+ if (!this.parent) throw new Error(`${this.builderName} builder is not attached to a turn`);
897
+ return this.parent;
898
+ }
899
+
929
900
  get id(): TurnId {
930
- if (!this.parent) {
931
- throw new Error("Published result builder is not attached to a turn");
932
- }
933
- return this.parent.id;
901
+ return this.turn.id;
934
902
  }
935
903
 
936
904
  get definition(): LlmTurnDefinition<string, TParams, TState> {
937
- if (!this.parent) {
938
- throw new Error("Published result builder is not attached to a turn");
939
- }
940
- return this.parent.definition;
905
+ return this.turn.definition;
941
906
  }
942
907
 
943
- buildTurnEnd(): ProcessTurnEndSpec<TParams, TState, string> {
944
- const effect = this.flowEffect ? wrapLlmOutcomeEffect(this.flowEffect) : undefined;
908
+ protected buildResult(): ProcessTurnEndSpec<TParams, TState, string> {
909
+ const effect = this.flowEffect ? wrapOutcomeCallback(this.flowEffect) : undefined;
945
910
  return {
946
- outcome: this.productName,
911
+ outcome: this.outcomeId,
947
912
  ...this.buildRouteTarget(),
948
913
  ...(effect ? { effect } : {}),
949
914
  };
950
915
  }
951
916
  }
952
917
 
953
- export class LlmTurnEndBuilder<TParams = unknown, TState = unknown>
954
- extends RouteAndEffectBuilder<TParams, TState, FlowLlmOutcomeEffectContext<TParams, TState>>
955
- implements FlowLlmTurn<TParams, TState, string>
956
- {
957
- constructor(
958
- private readonly outcomeId: string,
959
- private readonly parent?: FlowLlmTurn<TParams, TState, string>,
960
- ) {
961
- super();
962
- if (outcomeId.trim() === "") {
963
- throw new Error("LLM turn end outcome must be non-empty");
964
- }
965
- }
918
+ export class PublishedResultBuilder<TParams = unknown, TState = unknown> extends TurnEndBuilder<
919
+ TParams,
920
+ TState
921
+ > {
922
+ protected readonly builderName = "Published result";
966
923
 
967
- get id(): TurnId {
968
- if (!this.parent) {
969
- throw new Error("LLM turn end builder is not attached to a turn");
970
- }
971
- return this.parent.id;
924
+ buildTurnEnd(): ProcessTurnEndSpec<TParams, TState, string> {
925
+ return this.buildResult();
972
926
  }
927
+ }
973
928
 
974
- get definition(): LlmTurnDefinition<string, TParams, TState> {
975
- if (!this.parent) {
976
- throw new Error("LLM turn end builder is not attached to a turn");
977
- }
978
- return this.parent.definition;
929
+ export class LlmTurnEndBuilder<TParams = unknown, TState = unknown> extends TurnEndBuilder<
930
+ TParams,
931
+ TState
932
+ > {
933
+ protected readonly builderName = "LLM turn end";
934
+
935
+ constructor(outcomeId: string, parent?: FlowLlmTurn<TParams, TState, string>) {
936
+ super(outcomeId, parent);
937
+ if (outcomeId.trim() === "") throw new Error("LLM turn end outcome must be non-empty");
979
938
  }
980
939
 
981
940
  build(): ProcessTurnEndSpec<TParams, TState, string> {
982
- const effect = this.flowEffect ? wrapLlmOutcomeEffect(this.flowEffect) : undefined;
983
- return {
984
- outcome: this.outcomeId,
985
- ...this.buildRouteTarget(),
986
- ...(effect ? { effect } : {}),
987
- };
941
+ return this.buildResult();
988
942
  }
989
943
  }
990
944
 
991
- type LlmPromptBuilder<TParams, TState, TConsumedProducts extends string> = (
992
- ctx: FlowPromptContext<TParams, TState, TConsumedProducts>,
945
+ type LlmPromptBuilder<TParams, TState, TConsumedProducts extends string, TPrepared> = (
946
+ ctx: FlowPromptContext<TParams, TState, TConsumedProducts, TPrepared>,
993
947
  ) => MaybePromise<string>;
994
948
 
949
+ abstract class DescribedTurnBuilder {
950
+ protected turnDescription: string | null = null;
951
+
952
+ constructor(protected readonly turnId: TurnId) {}
953
+
954
+ get id(): TurnId {
955
+ return this.turnId;
956
+ }
957
+
958
+ description(description: string): this {
959
+ this.turnDescription = description;
960
+ return this;
961
+ }
962
+ }
963
+
995
964
  export class LlmFlowBuilder<
996
- TParams = unknown,
997
- TState = unknown,
998
- TConsumedProducts extends string = never,
999
- > implements FlowLlmTurn<TParams, TState, string>
965
+ TParams = unknown,
966
+ TState = unknown,
967
+ TConsumedProducts extends string = never,
968
+ TPrepared = undefined,
969
+ >
970
+ extends DescribedTurnBuilder
971
+ implements FlowLlmTurn<TParams, TState, string>
1000
972
  {
1001
- private readonly turnId: TurnId;
1002
- private turnDescription: string | null = null;
1003
973
  private modelPurposeValue: LlmModelPurpose | undefined;
1004
974
  private availableTools: readonly PiBuiltInToolName[] = [];
1005
975
  private availableIntegrationTools: readonly string[] = [];
976
+ private integrationToolResolver:
977
+ | ((params: TParams, state: TState) => readonly string[])
978
+ | undefined;
979
+ private preparation:
980
+ | ((ctx: FlowLlmPreparationContext<TParams, TState>) => MaybePromise<unknown>)
981
+ | null = null;
1006
982
  private promptBuilder:
1007
983
  | ((ctx: ProcessRuntimeTurnContext<TParams, TState>) => MaybePromise<string>)
1008
984
  | null = null;
1009
985
  private branchType: LlmTurnDefinition<string, TParams, TState>["branchType"] = "primary";
1010
986
  private context: LlmTurnDefinition<string, TParams, TState>["context"] = "fresh";
1011
- private completionMode: LlmTurnDefinition<string, TParams, TState>["completionMode"] = "turn_end";
1012
987
  private questionsEnabled = false;
1013
988
  private startFrom: LlmTurnDefinition<string, TParams, TState>["startFrom"] | undefined;
1014
989
  private restorePrimaryLeafAfterTurn: boolean | undefined;
1015
- private reviewSubject: ReviewSubject | undefined;
1016
- private consumedProductNames: string[] = [];
1017
- private optionalConsumedProductNames: string[] = [];
990
+ private readonly consumedProductNames = new Set<string>();
991
+ private readonly optionalConsumedProductNames = new Set<string>();
1018
992
  private publishedResult: {
1019
993
  productName: string;
1020
994
  builder: PublishedResultBuilder<TParams, TState>;
@@ -1022,23 +996,10 @@ export class LlmFlowBuilder<
1022
996
  private endResult: LlmTurnEndBuilder<TParams, TState> | null = null;
1023
997
  private outcomeToolBuilders = new Map<string, OutcomeToolBuilder<TParams, TState>>();
1024
998
 
1025
- constructor(turnId: TurnId) {
1026
- this.turnId = turnId;
1027
- }
1028
-
1029
- get id(): TurnId {
1030
- return this.turnId;
1031
- }
1032
-
1033
999
  get definition(): LlmTurnDefinition<string, TParams, TState> {
1034
1000
  return this.buildDefinition();
1035
1001
  }
1036
1002
 
1037
- description(description: string): this {
1038
- this.turnDescription = description;
1039
- return this;
1040
- }
1041
-
1042
1003
  modelPurpose(purpose: LlmModelPurpose): this {
1043
1004
  this.modelPurposeValue = purpose;
1044
1005
  return this;
@@ -1054,6 +1015,18 @@ export class LlmFlowBuilder<
1054
1015
  return this;
1055
1016
  }
1056
1017
 
1018
+ resolveIntegrationTools(resolver: (params: TParams, state: TState) => readonly string[]): this {
1019
+ this.integrationToolResolver = resolver;
1020
+ return this;
1021
+ }
1022
+
1023
+ prepare<TNextPrepared>(
1024
+ fn: (ctx: FlowLlmPreparationContext<TParams, TState>) => MaybePromise<TNextPrepared>,
1025
+ ): LlmFlowBuilder<TParams, TState, TConsumedProducts, TNextPrepared> {
1026
+ this.preparation = fn;
1027
+ return this as unknown as LlmFlowBuilder<TParams, TState, TConsumedProducts, TNextPrepared>;
1028
+ }
1029
+
1057
1030
  /** Enable durable operator questions for this LLM turn. */
1058
1031
  askQuestions(): this {
1059
1032
  this.questionsEnabled = true;
@@ -1063,7 +1036,6 @@ export class LlmFlowBuilder<
1063
1036
  freshPrimary(): this {
1064
1037
  this.branchType = "primary";
1065
1038
  this.context = "fresh";
1066
- this.completionMode = "turn_end";
1067
1039
  this.startFrom = undefined;
1068
1040
  this.restorePrimaryLeafAfterTurn = undefined;
1069
1041
  return this;
@@ -1072,7 +1044,6 @@ export class LlmFlowBuilder<
1072
1044
  freshSeededPrimary(): this {
1073
1045
  this.branchType = "primary";
1074
1046
  this.context = "fresh_seeded";
1075
- this.completionMode = "turn_end";
1076
1047
  this.startFrom = undefined;
1077
1048
  this.restorePrimaryLeafAfterTurn = undefined;
1078
1049
  return this;
@@ -1081,14 +1052,12 @@ export class LlmFlowBuilder<
1081
1052
  fullPrimary(): this {
1082
1053
  this.branchType = "primary";
1083
1054
  this.context = "full";
1084
- this.completionMode = "turn_end";
1085
1055
  return this;
1086
1056
  }
1087
1057
 
1088
1058
  rootBranchReview(): this {
1089
1059
  this.branchType = "root_branch";
1090
1060
  this.context = "full";
1091
- this.completionMode = "turn_end";
1092
1061
  this.restorePrimaryLeafAfterTurn = true;
1093
1062
  return this;
1094
1063
  }
@@ -1115,12 +1084,7 @@ export class LlmFlowBuilder<
1115
1084
  productName: string,
1116
1085
  fallback: ProcessTurnStartSelection = { kind: "current_leaf" },
1117
1086
  ): this {
1118
- this.startFrom = {
1119
- kind: "product_ref",
1120
- productName: normalizeProductName(productName),
1121
- fallback,
1122
- };
1123
- return this;
1087
+ return this.startFromProductBranch(productName, fallback);
1124
1088
  }
1125
1089
 
1126
1090
  startFromReviewBranch(): this {
@@ -1149,29 +1113,28 @@ export class LlmFlowBuilder<
1149
1113
  return this;
1150
1114
  }
1151
1115
 
1152
- reviews(subject: ReviewSubject): this {
1153
- this.reviewSubject = subject;
1154
- return this;
1155
- }
1156
-
1157
1116
  consume<TProductName extends string>(
1158
1117
  productName: TProductName,
1159
- ): LlmFlowBuilder<TParams, TState, TConsumedProducts | TProductName> {
1160
- const normalized = normalizeProductName(productName);
1161
- if (!this.consumedProductNames.includes(normalized)) {
1162
- this.consumedProductNames.push(normalized);
1163
- }
1164
- return this as unknown as LlmFlowBuilder<TParams, TState, TConsumedProducts | TProductName>;
1118
+ ): LlmFlowBuilder<TParams, TState, TConsumedProducts | TProductName, TPrepared> {
1119
+ this.consumedProductNames.add(normalizeProductName(productName));
1120
+ return this as unknown as LlmFlowBuilder<
1121
+ TParams,
1122
+ TState,
1123
+ TConsumedProducts | TProductName,
1124
+ TPrepared
1125
+ >;
1165
1126
  }
1166
1127
 
1167
1128
  optionalConsume<TProductName extends string>(
1168
1129
  productName: TProductName,
1169
- ): LlmFlowBuilder<TParams, TState, TConsumedProducts | TProductName> {
1170
- const normalized = normalizeProductName(productName);
1171
- if (!this.optionalConsumedProductNames.includes(normalized)) {
1172
- this.optionalConsumedProductNames.push(normalized);
1173
- }
1174
- return this as unknown as LlmFlowBuilder<TParams, TState, TConsumedProducts | TProductName>;
1130
+ ): LlmFlowBuilder<TParams, TState, TConsumedProducts | TProductName, TPrepared> {
1131
+ this.optionalConsumedProductNames.add(normalizeProductName(productName));
1132
+ return this as unknown as LlmFlowBuilder<
1133
+ TParams,
1134
+ TState,
1135
+ TConsumedProducts | TProductName,
1136
+ TPrepared
1137
+ >;
1175
1138
  }
1176
1139
 
1177
1140
  publish(productName: string): PublishedResultBuilder<TParams, TState> {
@@ -1201,14 +1164,12 @@ export class LlmFlowBuilder<
1201
1164
  return this.endResult;
1202
1165
  }
1203
1166
 
1204
- buildPrompt(fn: LlmPromptBuilder<TParams, TState, TConsumedProducts>): this {
1167
+ buildPrompt(fn: LlmPromptBuilder<TParams, TState, TConsumedProducts, TPrepared>): this {
1205
1168
  this.promptBuilder = (ctx) =>
1206
1169
  fn(
1207
- createFlowPromptContext(
1208
- ctx,
1209
- this.consumedProductNames as TConsumedProducts[],
1210
- this.optionalConsumedProductNames,
1211
- ),
1170
+ createFlowPromptContext(ctx, [...this.consumedProductNames] as TConsumedProducts[], [
1171
+ ...this.optionalConsumedProductNames,
1172
+ ]),
1212
1173
  );
1213
1174
  return this;
1214
1175
  }
@@ -1250,6 +1211,7 @@ export class LlmFlowBuilder<
1250
1211
  if (!prompt) {
1251
1212
  throw new Error(`LLM turn '${this.turnId}' must declare .buildPrompt(...)`);
1252
1213
  }
1214
+ const preparation = this.preparation;
1253
1215
  return {
1254
1216
  kind: "llm" as const,
1255
1217
  description: this.turnDescription,
@@ -1258,8 +1220,17 @@ export class LlmFlowBuilder<
1258
1220
  ...(this.availableIntegrationTools.length > 0
1259
1221
  ? { integrationTools: this.availableIntegrationTools }
1260
1222
  : {}),
1223
+ ...(this.integrationToolResolver
1224
+ ? { resolveIntegrationTools: this.integrationToolResolver }
1225
+ : {}),
1261
1226
  ...(this.questionsEnabled ? { askQuestions: true as const } : {}),
1262
- completionMode: this.completionMode,
1227
+ ...(preparation
1228
+ ? {
1229
+ prepare: (ctx: ProcessRuntimeTurnContext<TParams, TState>) =>
1230
+ preparation(createFlowAutomaticRunContext(ctx)),
1231
+ }
1232
+ : {}),
1233
+ completionMode: "turn_end" as const,
1263
1234
  branchType: this.branchType,
1264
1235
  context: this.context,
1265
1236
  ...(this.startFrom ? { startFrom: this.startFrom } : {}),
@@ -1299,13 +1270,18 @@ export class LlmFlowBuilder<
1299
1270
  for (const [outcomeId, builder] of this.outcomeToolBuilders) {
1300
1271
  outcomes[outcomeId] = builder.build();
1301
1272
  }
1302
- const hasOutcomePublishedProduct = Object.values(outcomes).some(
1303
- (outcome) => outcome.publishedProduct,
1273
+ const outcomePublishedProducts = new Set(
1274
+ Object.values(outcomes)
1275
+ .map((outcome) => outcome.publishedProduct)
1276
+ .filter((productName): productName is string => typeof productName === "string"),
1304
1277
  );
1278
+ const hasOutcomePublishedProduct = outcomePublishedProducts.size > 0;
1305
1279
  let turnEnd: ProcessTurnEndSpec<TParams, TState, string> | undefined;
1306
- let resultSemanticRef: "plan" | "review" | undefined = this.reviewSubject
1280
+ let resultSemanticRef: "plan" | "review" | undefined = outcomePublishedProducts.has("review")
1307
1281
  ? "review"
1308
- : undefined;
1282
+ : outcomePublishedProducts.has("plan")
1283
+ ? "plan"
1284
+ : undefined;
1309
1285
  let turnResultMarkdown: LlmTurnDefinition<string, TParams, TState>["turnResultMarkdown"];
1310
1286
  let publishedProduct: string | undefined;
1311
1287
 
@@ -1363,139 +1339,93 @@ export class LlmFlowBuilder<
1363
1339
 
1364
1340
  return {
1365
1341
  ...definition,
1366
- ...(this.reviewSubject ? { reviewSubject: this.reviewSubject } : {}),
1367
1342
  ...(Object.keys(outcomes).length > 0 ? { outcomes } : {}),
1368
1343
  ...(turnEnd ? { turnEnd } : {}),
1369
1344
  ...(turnResultMarkdown ? { turnResultMarkdown } : {}),
1370
1345
  ...(resultSemanticRef ? { resultSemanticRef } : {}),
1371
1346
  ...(publishedProduct ? { publishedProduct } : {}),
1372
- ...(this.consumedProductNames.length > 0
1347
+ ...(this.consumedProductNames.size > 0
1373
1348
  ? { consumedProducts: [...this.consumedProductNames] }
1374
1349
  : {}),
1375
- ...(this.optionalConsumedProductNames.length > 0
1350
+ ...(this.optionalConsumedProductNames.size > 0
1376
1351
  ? { optionalConsumedProducts: [...this.optionalConsumedProductNames] }
1377
1352
  : {}),
1378
1353
  };
1379
1354
  }
1380
1355
  }
1381
1356
 
1382
- export class AutomaticFlowBuilder<TParams = unknown, TState = unknown>
1383
- implements FlowAutomaticTurn<TParams, TState, string>
1384
- {
1385
- private readonly turnId: TurnId;
1386
- private turnDescription: string | null = null;
1387
- private runFn:
1388
- | ((ctx: FlowAutomaticRunContext<TParams, TState>) => MaybePromise<WorkerCompleteInput<string>>)
1389
- | null = null;
1390
- private outcomeBuilders = new Map<string, AutomaticOutcomeBuilder<TParams, TState>>();
1391
-
1392
- constructor(turnId: TurnId) {
1393
- this.turnId = turnId;
1394
- }
1395
-
1396
- get id(): TurnId {
1397
- return this.turnId;
1398
- }
1399
-
1400
- get definition(): AutomaticTurnDefinition<string, TParams, TState> {
1401
- return this.buildDefinition();
1402
- }
1403
-
1404
- description(description: string): this {
1405
- this.turnDescription = description;
1406
- return this;
1407
- }
1357
+ type StoredExternalActionBuilder<TParams, TState> = ExternalActionBuilder<
1358
+ TParams,
1359
+ TState,
1360
+ unknown,
1361
+ Record<string, unknown>
1362
+ >;
1408
1363
 
1409
- run(
1410
- fn: (
1411
- ctx: FlowAutomaticRunContext<TParams, TState>,
1412
- ) => MaybePromise<WorkerCompleteInput<string>>,
1413
- ): this {
1414
- this.runFn = fn;
1415
- return this;
1416
- }
1364
+ abstract class ExternalActionTurnBuilder<TParams, TState> extends DescribedTurnBuilder {
1365
+ protected abstract readonly turnKind: "Automatic" | "Human";
1366
+ private externalActionBuilders = new Map<string, StoredExternalActionBuilder<TParams, TState>>();
1417
1367
 
1418
- outcome(
1419
- id: string,
1368
+ externalAction<
1369
+ TEvent = unknown,
1370
+ TInput extends Record<string, unknown> = Record<string, unknown>,
1371
+ >(
1372
+ externalActionId: string,
1373
+ source: ExternalActionSource<TParams, TState, TEvent, TInput>,
1420
1374
  configure: (
1421
- outcome: AutomaticOutcomeBuilder<TParams, TState>,
1422
- ) => AutomaticOutcomeBuilder<TParams, TState> | undefined,
1375
+ external: ExternalActionBuilder<TParams, TState, TEvent, TInput>,
1376
+ ) => ExternalActionBuilder<TParams, TState, TEvent, TInput> | undefined,
1423
1377
  ): this {
1424
- if (id.trim() === "") {
1425
- throw new Error(`Automatic turn '${this.turnId}' declares an empty outcome id`);
1426
- }
1427
- if (this.outcomeBuilders.has(id)) {
1428
- throw new Error(`Automatic turn '${this.turnId}' declares duplicate outcome '${id}'`);
1378
+ if (this.externalActionBuilders.has(externalActionId)) {
1379
+ throw new Error(
1380
+ `${this.turnKind} turn '${this.turnId}' declares duplicate external action '${externalActionId}'`,
1381
+ );
1429
1382
  }
1430
- const builder = new AutomaticOutcomeBuilder<TParams, TState>();
1383
+ const builder = new ExternalActionBuilder(externalActionId, source);
1431
1384
  configure(builder);
1432
- this.outcomeBuilders.set(id, builder);
1385
+ this.externalActionBuilders.set(
1386
+ externalActionId,
1387
+ builder as unknown as StoredExternalActionBuilder<TParams, TState>,
1388
+ );
1433
1389
  return this;
1434
1390
  }
1435
1391
 
1436
- private buildDefinition(): AutomaticTurnDefinition<string, TParams, TState> {
1437
- if (!this.turnDescription) {
1438
- throw new Error(`Automatic turn '${this.turnId}' must declare .description(...)`);
1439
- }
1440
- if (!this.runFn) {
1441
- throw new Error(`Automatic turn '${this.turnId}' must declare .run(...)`);
1442
- }
1443
- if (this.outcomeBuilders.size === 0) {
1444
- throw new Error(`Automatic turn '${this.turnId}' must declare at least one outcome`);
1445
- }
1446
- const outcomes: Record<string, ProcessToolOutcomeSpec<TParams, TState>> = {};
1447
- for (const [outcomeId, builder] of this.outcomeBuilders) {
1448
- outcomes[outcomeId] = builder.build();
1449
- }
1450
- const runFn = this.runFn;
1451
- return {
1452
- kind: "automatic",
1453
- description: this.turnDescription,
1454
- outcomes,
1455
- run: (ctx) => runFn(createFlowAutomaticRunContext(ctx)),
1456
- };
1392
+ protected buildExternalActions():
1393
+ | Record<string, ProcessHumanTurnExternalActionSpec<TParams, TState>>
1394
+ | undefined {
1395
+ return this.externalActionBuilders.size > 0
1396
+ ? Object.fromEntries(
1397
+ [...this.externalActionBuilders].map(([id, builder]) => [id, builder.build()]),
1398
+ )
1399
+ : undefined;
1457
1400
  }
1458
1401
  }
1459
1402
 
1460
- export class ServerAutomaticFlowBuilder<TParams = unknown, TState = unknown>
1461
- implements FlowServerAutomaticTurn<TParams, TState, string>
1403
+ export class AutomaticFlowBuilder<TParams = unknown, TState = unknown>
1404
+ extends ExternalActionTurnBuilder<TParams, TState>
1405
+ implements FlowAutomaticTurn<TParams, TState, string>
1462
1406
  {
1463
- private readonly turnId: TurnId;
1464
- private turnDescription: string | null = null;
1465
- private restartBehaviorValue: ServerAutomaticTurnRestartBehavior | undefined;
1407
+ protected readonly turnKind = "Automatic";
1466
1408
  private runFn:
1467
1409
  | ((ctx: FlowAutomaticRunContext<TParams, TState>) => MaybePromise<WorkerCompleteInput<string>>)
1468
1410
  | null = null;
1469
1411
  private outcomeBuilders = new Map<string, AutomaticOutcomeBuilder<TParams, TState>>();
1412
+ private availableIntegrationTools: readonly string[] = [];
1470
1413
 
1471
- constructor(turnId: TurnId) {
1472
- this.turnId = turnId;
1473
- }
1474
-
1475
- get id(): TurnId {
1476
- return this.turnId;
1477
- }
1478
-
1479
- get definition(): ServerAutomaticTurnDefinition<string, TParams, TState> {
1414
+ get definition(): AutomaticTurnDefinition<string, TParams, TState> {
1480
1415
  return this.buildDefinition();
1481
1416
  }
1482
1417
 
1483
- description(description: string): this {
1484
- this.turnDescription = description;
1485
- return this;
1486
- }
1487
-
1488
1418
  run(
1489
1419
  fn: (
1490
1420
  ctx: FlowAutomaticRunContext<TParams, TState>,
1491
- ) => MaybePromise<WorkerCompleteInput<string> & { state?: TState }>,
1421
+ ) => MaybePromise<WorkerCompleteInput<string>>,
1492
1422
  ): this {
1493
1423
  this.runFn = fn;
1494
1424
  return this;
1495
1425
  }
1496
1426
 
1497
- restartBehavior(behavior: ServerAutomaticTurnRestartBehavior): this {
1498
- this.restartBehaviorValue = behavior;
1427
+ integrationTools(...tools: readonly string[]): this {
1428
+ this.availableIntegrationTools = tools.map((tool) => tool.trim());
1499
1429
  return this;
1500
1430
  }
1501
1431
 
@@ -1506,10 +1436,10 @@ export class ServerAutomaticFlowBuilder<TParams = unknown, TState = unknown>
1506
1436
  ) => AutomaticOutcomeBuilder<TParams, TState> | undefined,
1507
1437
  ): this {
1508
1438
  if (id.trim() === "") {
1509
- throw new Error(`Server automatic turn '${this.turnId}' declares an empty outcome id`);
1439
+ throw new Error(`Automatic turn '${this.turnId}' declares an empty outcome id`);
1510
1440
  }
1511
1441
  if (this.outcomeBuilders.has(id)) {
1512
- throw new Error(`Server automatic turn '${this.turnId}' declares duplicate outcome '${id}'`);
1442
+ throw new Error(`Automatic turn '${this.turnId}' declares duplicate outcome '${id}'`);
1513
1443
  }
1514
1444
  const builder = new AutomaticOutcomeBuilder<TParams, TState>();
1515
1445
  configure(builder);
@@ -1517,45 +1447,35 @@ export class ServerAutomaticFlowBuilder<TParams = unknown, TState = unknown>
1517
1447
  return this;
1518
1448
  }
1519
1449
 
1520
- private buildDefinition(): ServerAutomaticTurnDefinition<string, TParams, TState> {
1450
+ private buildDefinition(): AutomaticTurnDefinition<string, TParams, TState> {
1521
1451
  if (!this.turnDescription) {
1522
- throw new Error(`Server automatic turn '${this.turnId}' must declare .description(...)`);
1452
+ throw new Error(`Automatic turn '${this.turnId}' must declare .description(...)`);
1523
1453
  }
1524
1454
  if (!this.runFn) {
1525
- throw new Error(`Server automatic turn '${this.turnId}' must declare .run(...)`);
1455
+ throw new Error(`Automatic turn '${this.turnId}' must declare .run(...)`);
1526
1456
  }
1527
1457
  if (this.outcomeBuilders.size === 0) {
1528
- throw new Error(`Server automatic turn '${this.turnId}' must declare at least one outcome`);
1458
+ throw new Error(`Automatic turn '${this.turnId}' must declare at least one outcome`);
1529
1459
  }
1530
1460
  const outcomes: Record<string, ProcessToolOutcomeSpec<TParams, TState>> = {};
1531
1461
  for (const [outcomeId, builder] of this.outcomeBuilders) {
1532
1462
  outcomes[outcomeId] = builder.build();
1533
1463
  }
1534
1464
  const runFn = this.runFn;
1465
+ const externalActions = this.buildExternalActions();
1535
1466
  return {
1536
- kind: "server_automatic",
1467
+ kind: "automatic",
1537
1468
  description: this.turnDescription,
1469
+ ...(this.availableIntegrationTools.length > 0
1470
+ ? { integrationTools: this.availableIntegrationTools }
1471
+ : {}),
1472
+ ...(externalActions ? { externalActions } : {}),
1538
1473
  outcomes,
1539
- ...(this.restartBehaviorValue ? { restartBehavior: this.restartBehaviorValue } : {}),
1540
- run: (ctx) =>
1541
- runFn(createFlowAutomaticRunContext(ctx as ProcessRuntimeTurnContext<TParams, TState>)),
1474
+ run: (ctx) => runFn(createFlowAutomaticRunContext(ctx)),
1542
1475
  };
1543
1476
  }
1544
1477
  }
1545
1478
 
1546
- function formFieldPublishedProductName(field: FormDefinition["fields"][number]): string | null {
1547
- if (!field.publish) {
1548
- return null;
1549
- }
1550
- return normalizeProductName(
1551
- typeof field.publish === "object" && field.publish.product ? field.publish.product : field.id,
1552
- );
1553
- }
1554
-
1555
- function inferActionLabel(actionId: string): string {
1556
- return humanizeProcessLabel(actionId);
1557
- }
1558
-
1559
1479
  function inferAcceptanceState(actionId: string): ProcessHumanTurnActionSpec["acceptanceState"] {
1560
1480
  const normalized = actionId.toLowerCase();
1561
1481
  if (/approve|accept|complete|merged/.test(normalized)) {
@@ -1625,7 +1545,7 @@ export class HumanActionBuilder<TParams = unknown, TState = unknown> {
1625
1545
  build(): ProcessHumanTurnActionSpec<TParams, TState> {
1626
1546
  return {
1627
1547
  label:
1628
- typeof this.spec.label === "string" ? this.spec.label : inferActionLabel(this.actionId),
1548
+ typeof this.spec.label === "string" ? this.spec.label : humanizeProcessLabel(this.actionId),
1629
1549
  acceptanceState:
1630
1550
  (this.spec.acceptanceState as
1631
1551
  | ProcessHumanTurnActionSpec<TParams, TState>["acceptanceState"]
@@ -1657,6 +1577,11 @@ export class ExternalActionBuilder<
1657
1577
  return this;
1658
1578
  }
1659
1579
 
1580
+ when(condition: NonNullable<ProcessHumanTurnExternalActionSpec<TParams, TState>["when"]>): this {
1581
+ this.spec.when = condition;
1582
+ return this;
1583
+ }
1584
+
1660
1585
  to(turnId: TurnId): this {
1661
1586
  this.spec.to = turnId;
1662
1587
  return this;
@@ -1680,41 +1605,36 @@ export class ExternalActionBuilder<
1680
1605
  return this;
1681
1606
  }
1682
1607
 
1608
+ effect(effect: ExternalSourceEffect<TParams, TState, TEvent, TInput>): this {
1609
+ this.spec.effect = effect;
1610
+ return this;
1611
+ }
1612
+
1683
1613
  build(): ProcessHumanTurnExternalActionSpec<TParams, TState, TEvent, TInput> {
1684
1614
  return this.spec as ProcessHumanTurnExternalActionSpec<TParams, TState, TEvent, TInput>;
1685
1615
  }
1686
1616
  }
1687
1617
 
1688
1618
  export class HumanFlowBuilder<TParams = unknown, TState = unknown>
1619
+ extends ExternalActionTurnBuilder<TParams, TState>
1689
1620
  implements FlowHumanTurn<TParams, TState>
1690
1621
  {
1691
- private turnDescription: string | null = null;
1692
- private reviewSubject: ReviewSubject | null = null;
1622
+ protected readonly turnKind = "Human";
1693
1623
  private reviewProductName: string | undefined;
1694
1624
  private reviewSemanticRef: ProcessSemanticEntryRefKey | undefined;
1695
1625
  private operatorAttentionValue: HumanTurnOperatorAttention | undefined;
1696
1626
  private turnCommentary: string | undefined;
1697
1627
  private notes: HumanTurnDefinition<TParams, TState>["notesFields"] | undefined;
1698
1628
  private actions = new Map<string, HumanActionBuilder<TParams, TState>>();
1699
- private externalActionBuilders = new Map<
1700
- string,
1701
- ExternalActionBuilder<TParams, TState, unknown, Record<string, unknown>>
1702
- >();
1703
-
1704
- constructor(private readonly turnId: TurnId) {}
1705
-
1706
- get id(): TurnId {
1707
- return this.turnId;
1708
- }
1709
1629
 
1710
1630
  get definition(): HumanTurnDefinition<TParams, TState> {
1711
1631
  if (!this.turnDescription) {
1712
1632
  throw new Error(`Human turn '${this.turnId}' must declare .description(...)`);
1713
1633
  }
1634
+ const externalActions = this.buildExternalActions();
1714
1635
  return {
1715
1636
  kind: "human",
1716
1637
  description: this.turnDescription,
1717
- ...(this.reviewSubject ? { reviewSubject: this.reviewSubject } : {}),
1718
1638
  ...(this.reviewProductName ? { reviewProduct: this.reviewProductName } : {}),
1719
1639
  ...(this.reviewSemanticRef ? { reviewSemanticRef: this.reviewSemanticRef } : {}),
1720
1640
  ...(this.operatorAttentionValue ? { operatorAttention: this.operatorAttentionValue } : {}),
@@ -1723,39 +1643,13 @@ export class HumanFlowBuilder<TParams = unknown, TState = unknown>
1723
1643
  actions: Object.fromEntries(
1724
1644
  [...this.actions.entries()].map(([actionId, builder]) => [actionId, builder.build()]),
1725
1645
  ),
1726
- ...(this.externalActionBuilders.size > 0
1727
- ? {
1728
- externalActions: Object.fromEntries(
1729
- [...this.externalActionBuilders.entries()].map(([actionId, builder]) => [
1730
- actionId,
1731
- builder.build(),
1732
- ]),
1733
- ),
1734
- }
1735
- : {}),
1646
+ ...(externalActions ? { externalActions } : {}),
1736
1647
  };
1737
1648
  }
1738
1649
 
1739
- description(description: string): this {
1740
- this.turnDescription = description;
1741
- return this;
1742
- }
1743
-
1744
- review(subject: ReviewSubject | "plan" | "implementation"): this {
1745
- this.reviewSubject = typeof subject === "string" ? createReviewSubject(subject) : subject;
1746
- this.reviewProductName = undefined;
1747
- this.reviewSemanticRef = typeof subject === "string" && subject === "plan" ? "plan" : undefined;
1748
- return this;
1749
- }
1750
-
1751
- reviewProduct(
1752
- productName: string,
1753
- options: { subject: ReviewSubject | "plan" | "implementation" },
1754
- ): this {
1650
+ reviewProduct(productName: string): this {
1755
1651
  const normalized = normalizeProductName(productName);
1756
1652
  this.reviewProductName = normalized;
1757
- this.reviewSubject =
1758
- typeof options.subject === "string" ? createReviewSubject(options.subject) : options.subject;
1759
1653
  this.reviewSemanticRef =
1760
1654
  normalized === "plan" ? "plan" : normalized === "review" ? "review" : undefined;
1761
1655
  return this;
@@ -1790,38 +1684,6 @@ export class HumanFlowBuilder<TParams = unknown, TState = unknown>
1790
1684
  this.actions.set(actionId, builder);
1791
1685
  return this;
1792
1686
  }
1793
-
1794
- externalAction<
1795
- TEvent = unknown,
1796
- TInput extends Record<string, unknown> = Record<string, unknown>,
1797
- >(
1798
- externalActionId: string,
1799
- source: ExternalActionSource<TParams, TState, TEvent, TInput>,
1800
- configure: (
1801
- external: ExternalActionBuilder<TParams, TState, TEvent, TInput>,
1802
- ) => ExternalActionBuilder<TParams, TState, TEvent, TInput> | undefined,
1803
- ): this {
1804
- if (this.externalActionBuilders.has(externalActionId)) {
1805
- throw new Error(
1806
- `Human turn '${this.turnId}' declares duplicate external action '${externalActionId}'`,
1807
- );
1808
- }
1809
- const builder = new ExternalActionBuilder<TParams, TState, TEvent, TInput>(
1810
- externalActionId,
1811
- source,
1812
- );
1813
- configure(builder);
1814
- this.externalActionBuilders.set(
1815
- externalActionId,
1816
- builder as unknown as ExternalActionBuilder<
1817
- TParams,
1818
- TState,
1819
- unknown,
1820
- Record<string, unknown>
1821
- >,
1822
- );
1823
- return this;
1824
- }
1825
1687
  }
1826
1688
 
1827
1689
  export class ExternalRouteBuilder<
@@ -1832,11 +1694,7 @@ export class ExternalRouteBuilder<
1832
1694
  > implements FlowExternalTurn<TParams, TState>
1833
1695
  {
1834
1696
  private externalEffect: ExternalSourceEffect<TParams, TState, TEvent, TInput> | undefined;
1835
- private target:
1836
- | { kind: "to"; turnId: TurnId }
1837
- | { kind: "complete" }
1838
- | { kind: "lifecycleStatus"; status: ProcessTurnTerminalLifecycleStatus }
1839
- | null = null;
1697
+ private target: FlowTargetSpec = null;
1840
1698
  constructor(
1841
1699
  private readonly parent: ExternalFlowBuilder<TParams, TState>,
1842
1700
  private readonly source: ExternalActionSource<TParams, TState, TEvent, TInput>,
@@ -1850,12 +1708,7 @@ export class ExternalRouteBuilder<
1850
1708
  return this.parent.definition;
1851
1709
  }
1852
1710
 
1853
- private setTarget(
1854
- next:
1855
- | { kind: "to"; turnId: TurnId }
1856
- | { kind: "complete" }
1857
- | { kind: "lifecycleStatus"; status: ProcessTurnTerminalLifecycleStatus },
1858
- ): this {
1711
+ private setTarget(next: Exclude<FlowTargetSpec, null>): this {
1859
1712
  if (this.target) {
1860
1713
  throw new Error("External source route already declares a target");
1861
1714
  }
@@ -1899,36 +1752,22 @@ export class ExternalRouteBuilder<
1899
1752
  return this;
1900
1753
  }
1901
1754
 
1902
- private buildRouteTarget(): {
1903
- to?: TurnId;
1904
- complete?: boolean;
1905
- lifecycleStatus?: ProcessTurnTerminalLifecycleStatus;
1906
- } {
1907
- return buildRouteTargetSpec(this.target);
1908
- }
1909
-
1910
1755
  build() {
1911
1756
  return {
1912
1757
  source: this.source,
1913
- ...this.buildRouteTarget(),
1758
+ ...buildRouteTargetSpec(this.target),
1914
1759
  ...(this.externalEffect ? { effect: this.externalEffect } : {}),
1915
1760
  };
1916
1761
  }
1917
1762
  }
1918
1763
 
1919
1764
  export class ExternalFlowBuilder<TParams = unknown, TState = unknown>
1765
+ extends DescribedTurnBuilder
1920
1766
  implements FlowExternalTurn<TParams, TState>
1921
1767
  {
1922
- private turnDescription: string | null = null;
1923
1768
  private routeBuilders: ExternalRouteBuilder<TParams, TState, unknown, Record<string, unknown>>[] =
1924
1769
  [];
1925
1770
 
1926
- constructor(private readonly turnId: TurnId) {}
1927
-
1928
- get id(): TurnId {
1929
- return this.turnId;
1930
- }
1931
-
1932
1771
  get definition(): ExternalTurnDefinition<TParams, TState> {
1933
1772
  if (!this.turnDescription) {
1934
1773
  this.turnDescription =
@@ -1944,11 +1783,6 @@ export class ExternalFlowBuilder<TParams = unknown, TState = unknown>
1944
1783
  };
1945
1784
  }
1946
1785
 
1947
- description(description: string): this {
1948
- this.turnDescription = description;
1949
- return this;
1950
- }
1951
-
1952
1786
  from<TEvent = unknown, TInput extends Record<string, unknown> = Record<string, unknown>>(
1953
1787
  source: ExternalActionSource<TParams, TState, TEvent, TInput>,
1954
1788
  ): ExternalRouteBuilder<TParams, TState, TEvent, TInput> {
@@ -1962,6 +1796,12 @@ export class ExternalFlowBuilder<TParams = unknown, TState = unknown>
1962
1796
 
1963
1797
  type Hook<TApi> = (api: TApi) => void;
1964
1798
 
1799
+ function chainHooks<TApi>(hooks: readonly Hook<TApi>[]): Hook<TApi> {
1800
+ return (api) => {
1801
+ for (const hook of hooks) hook(api);
1802
+ };
1803
+ }
1804
+
1965
1805
  export abstract class FlowComponentBuilder<TParams = unknown, TState = unknown> {
1966
1806
  readonly turns: FlowTurn<TParams, TState>[] = [];
1967
1807
  readonly serverHooks: Hook<ServerProcessAPI<TParams, TState>>[] = [];
@@ -2041,13 +1881,11 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2041
1881
  private paramsCodec: Codec<TParams> | null = null;
2042
1882
  private stateCodec: Codec<TState> | null = null;
2043
1883
  private initialStateFn: ((params: TParams) => TState) | null = null;
2044
- private repositoryCredentialsFn:
2045
- | ((input: {
2046
- params: TParams;
2047
- projects: readonly RepositoryCredentialProject[];
2048
- }) => readonly RepositoryCredentialRequirement[])
2049
- | undefined;
1884
+ private repositoryCredentialsFn: ProcessDefinition<TParams, TState>["repositoryCredentials"];
1885
+ private storageSizeResolver: ProcessDefinition<TParams, TState>["resolveStorageSize"];
2050
1886
  private processPiConfig: ProcessPiConfig | undefined;
1887
+ private developmentTools = false;
1888
+ private docker = false;
2051
1889
 
2052
1890
  constructor(processId: string) {
2053
1891
  super();
@@ -2095,20 +1933,32 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2095
1933
  }
2096
1934
 
2097
1935
  repositoryCredentials(
2098
- fn: (input: {
2099
- params: TParams;
2100
- projects: readonly RepositoryCredentialProject[];
2101
- }) => readonly RepositoryCredentialRequirement[],
1936
+ fn: NonNullable<ProcessDefinition<TParams, TState>["repositoryCredentials"]>,
2102
1937
  ): this {
2103
1938
  this.repositoryCredentialsFn = fn;
2104
1939
  return this;
2105
1940
  }
2106
1941
 
1942
+ /** Resolve new process-volume capacity on the server; operator configuration wins. */
1943
+ resolveStorageSize(
1944
+ fn: NonNullable<ProcessDefinition<TParams, TState>["resolveStorageSize"]>,
1945
+ ): this {
1946
+ this.storageSizeResolver = fn;
1947
+ return this;
1948
+ }
1949
+
2107
1950
  piConfig(config: ProcessPiConfig): this {
2108
1951
  this.processPiConfig = config;
2109
1952
  return this;
2110
1953
  }
2111
1954
 
1955
+ /** Declare runner-provided process runtime capabilities. */
1956
+ runtime(capabilities: { developmentTools?: boolean; docker?: boolean }): this {
1957
+ this.developmentTools = capabilities.developmentTools === true;
1958
+ this.docker = capabilities.docker === true;
1959
+ return this;
1960
+ }
1961
+
2112
1962
  use(fragment: FlowFragmentBuilder<TParams, TState>): this {
2113
1963
  this.turns.push(...fragment.turns);
2114
1964
  this.serverHooks.push(...fragment.serverHooks);
@@ -2140,53 +1990,6 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2140
1990
  turns[turn.id] = turn.definition;
2141
1991
  }
2142
1992
 
2143
- const publishedProducts = new Set<string>();
2144
- for (const turnDef of Object.values(turns)) {
2145
- if (turnDef.kind === "llm") {
2146
- if (turnDef.publishedProduct) {
2147
- normalizeProductName(turnDef.publishedProduct);
2148
- publishedProducts.add(turnDef.publishedProduct);
2149
- }
2150
- for (const outcome of Object.values(turnDef.outcomes ?? {})) {
2151
- if (outcome?.publishedProduct) {
2152
- normalizeProductName(outcome.publishedProduct);
2153
- publishedProducts.add(outcome.publishedProduct);
2154
- }
2155
- }
2156
- }
2157
- if (turnDef.kind === "human") {
2158
- for (const action of Object.values(turnDef.actions)) {
2159
- for (const field of action.form?.fields ?? []) {
2160
- const productName = formFieldPublishedProductName(field);
2161
- if (productName) {
2162
- publishedProducts.add(productName);
2163
- }
2164
- }
2165
- }
2166
- for (const externalAction of Object.values(turnDef.externalActions ?? {})) {
2167
- if (externalAction.publishInput) {
2168
- publishedProducts.add(normalizeProductName(externalAction.publishInput.productName));
2169
- }
2170
- }
2171
- }
2172
- }
2173
- for (const [turnId, turnDef] of Object.entries(turns)) {
2174
- if (turnDef.kind !== "llm") {
2175
- continue;
2176
- }
2177
- for (const productName of [
2178
- ...(turnDef.consumedProducts ?? []),
2179
- ...(turnDef.optionalConsumedProducts ?? []),
2180
- ]) {
2181
- normalizeProductName(productName);
2182
- if (!publishedProducts.has(productName)) {
2183
- throw new Error(
2184
- `Flow process '${this.processId}' turn '${turnId}' consumes product '${productName}' that is never published by this process`,
2185
- );
2186
- }
2187
- }
2188
- }
2189
-
2190
1993
  const input: DefinedProcessInput<TParams, TState> = {
2191
1994
  id: this.processId,
2192
1995
  displayName: this.processDisplayName,
@@ -2198,49 +2001,32 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2198
2001
  paramsCodec: this.paramsCodec,
2199
2002
  stateCodec: this.stateCodec,
2200
2003
  initialState: this.initialStateFn,
2201
- ...(this.repositoryCredentialsFn
2202
- ? { repositoryCredentials: this.repositoryCredentialsFn }
2203
- : {}),
2204
- ...(this.processPiConfig ? { piConfig: this.processPiConfig } : {}),
2205
- turns,
2206
- ...(this.serverHooks.length > 0
2207
- ? {
2208
- server: (api) => {
2209
- for (const hook of this.serverHooks) {
2210
- hook(api);
2211
- }
2212
- },
2213
- }
2214
- : {}),
2215
- ...(this.uiHooks.length > 0
2004
+ ...(this.developmentTools || this.docker
2216
2005
  ? {
2217
- ui: (api) => {
2218
- for (const hook of this.uiHooks) {
2219
- hook(api);
2220
- }
2006
+ runtime: {
2007
+ ...(this.developmentTools ? { developmentTools: true } : {}),
2008
+ ...(this.docker ? { docker: true } : {}),
2221
2009
  },
2222
2010
  }
2223
2011
  : {}),
2224
- ...(this.launcherHooks.length > 0
2225
- ? {
2226
- launchers: (api) => {
2227
- for (const hook of this.launcherHooks) {
2228
- hook(api);
2229
- }
2230
- },
2231
- }
2232
- : {}),
2233
- ...(this.watcherHooks.length > 0
2234
- ? {
2235
- watchers: (api) => {
2236
- for (const hook of this.watcherHooks) {
2237
- hook(api);
2238
- }
2239
- },
2240
- }
2012
+ ...(this.repositoryCredentialsFn
2013
+ ? { repositoryCredentials: this.repositoryCredentialsFn }
2241
2014
  : {}),
2015
+ ...(this.storageSizeResolver ? { resolveStorageSize: this.storageSizeResolver } : {}),
2016
+ ...(this.processPiConfig ? { piConfig: this.processPiConfig } : {}),
2017
+ turns,
2018
+ ...(this.serverHooks.length > 0 ? { server: chainHooks(this.serverHooks) } : {}),
2019
+ ...(this.uiHooks.length > 0 ? { ui: chainHooks(this.uiHooks) } : {}),
2020
+ ...(this.launcherHooks.length > 0 ? { launchers: chainHooks(this.launcherHooks) } : {}),
2021
+ ...(this.watcherHooks.length > 0 ? { watchers: chainHooks(this.watcherHooks) } : {}),
2242
2022
  };
2243
- return defineProcess(input);
2023
+ const process = defineProcess(input);
2024
+ const errors = validateProcessGraphProducts(
2025
+ toProcessGraphView(process as unknown as ProcessGraphSource),
2026
+ );
2027
+ if (errors.length > 0)
2028
+ throw new Error(`Flow process '${this.processId}': ${errors.join("; ")}`);
2029
+ return process;
2244
2030
  }
2245
2031
  }
2246
2032
 
@@ -2253,11 +2039,6 @@ export const flow = {
2253
2039
  ): AutomaticFlowBuilder<TParams, TState> {
2254
2040
  return new AutomaticFlowBuilder<TParams, TState>(turnId);
2255
2041
  },
2256
- serverAutomatic<TParams = unknown, TState = unknown>(
2257
- turnId: TurnId,
2258
- ): ServerAutomaticFlowBuilder<TParams, TState> {
2259
- return new ServerAutomaticFlowBuilder<TParams, TState>(turnId);
2260
- },
2261
2042
  human<TParams = unknown, TState = unknown>(turnId: TurnId): HumanFlowBuilder<TParams, TState> {
2262
2043
  return new HumanFlowBuilder<TParams, TState>(turnId);
2263
2044
  },