@leitwerk-dev/process-sdk 0.1.8 → 0.1.9

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 (39) hide show
  1. package/dist/core-capabilities.d.ts +6 -0
  2. package/dist/core-capabilities.d.ts.map +1 -1
  3. package/dist/core-capabilities.js.map +1 -1
  4. package/dist/define-process.d.ts +23 -10
  5. package/dist/define-process.d.ts.map +1 -1
  6. package/dist/define-process.js +182 -144
  7. package/dist/define-process.js.map +1 -1
  8. package/dist/{extension-api-CqPGRqc9.d.ts → extension-api-BBcwktmc.d.ts} +30 -10
  9. package/dist/extension-api.d.ts +8 -1
  10. package/dist/extension-api.d.ts.map +1 -1
  11. package/dist/extension-api.js.map +1 -1
  12. package/dist/flow.d.ts +14 -8
  13. package/dist/flow.d.ts.map +1 -1
  14. package/dist/flow.js +115 -35
  15. package/dist/flow.js.map +1 -1
  16. package/dist/index.d.ts +1 -1
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js.map +1 -1
  19. package/dist/process-graph.d.ts +1 -2
  20. package/dist/process-graph.d.ts.map +1 -1
  21. package/dist/process-graph.js +0 -1
  22. package/dist/process-graph.js.map +1 -1
  23. package/dist/process-watcher-source.d.ts +3 -1
  24. package/dist/process-watcher-source.d.ts.map +1 -1
  25. package/dist/process-watcher-source.js +8 -1
  26. package/dist/process-watcher-source.js.map +1 -1
  27. package/dist/state-helpers.d.ts +1 -2
  28. package/dist/state-helpers.d.ts.map +1 -1
  29. package/dist/state-helpers.js +1 -3
  30. package/dist/state-helpers.js.map +1 -1
  31. package/package.json +4 -4
  32. package/src/core-capabilities.ts +9 -0
  33. package/src/define-process.ts +266 -189
  34. package/src/extension-api.ts +8 -0
  35. package/src/flow.ts +172 -59
  36. package/src/index.ts +2 -0
  37. package/src/process-graph.ts +0 -3
  38. package/src/process-watcher-source.ts +10 -2
  39. package/src/state-helpers.ts +0 -5
@@ -8,14 +8,15 @@ import {
8
8
  type ProcessTurnStartSelection,
9
9
  type ProcessTurnTerminalLifecycleStatus,
10
10
  type ProcessTurnTransition,
11
- type ReviewSubject,
12
11
  type TurnId,
12
+ type TurnProgressReport,
13
13
  } from "@leitwerk-dev/domain";
14
14
  import type {
15
15
  Codec,
16
16
  ExtensionProcessDefinition,
17
17
  ExternalActionSource,
18
18
  ExternalSourceEffect,
19
+ ExternalSourceResolveContext,
19
20
  FormDefinition,
20
21
  ProcessLauncherAPI,
21
22
  ProcessTurnBinding,
@@ -95,6 +96,7 @@ export interface ProcessServerRuntimeContext<TParams = unknown, TState = unknown
95
96
  readonly state: TState;
96
97
  readSemanticTurnResultMarkdown(ref: ProcessSemanticEntryRefKey): string | null;
97
98
  readProductTurnResultMarkdown(productName: string): string | null;
99
+ reportProgress?(report: TurnProgressReport): void;
98
100
  }
99
101
 
100
102
  export interface ProcessBroadcastEffect {
@@ -105,6 +107,7 @@ export interface ProcessBroadcastEffect {
105
107
  export type ProcessPatchEffect = Partial<
106
108
  Pick<
107
109
  ProcessInstance,
110
+ | "lifecycleStatus"
108
111
  | "planRevision"
109
112
  | "title"
110
113
  | "externalId"
@@ -168,6 +171,14 @@ export type ProcessOutcomeEffect<TParams = unknown, TState = unknown> = (
168
171
  input: ProcessOutcomeExecution<TParams, TState>,
169
172
  ) => MaybePromise<ProcessEffectPlan<TState> | undefined>;
170
173
 
174
+ export type ProcessOutcomeBranchSelector<TParams = unknown, TState = unknown> = (
175
+ input: ProcessOutcomeExecution<TParams, TState>,
176
+ ) => MaybePromise<string>;
177
+
178
+ export interface ProcessOutcomeBranchSpec extends StaticRouteTarget {
179
+ trigger?: string;
180
+ }
181
+
171
182
  export interface ProcessActionExternalTrigger {
172
183
  id: string;
173
184
  label: string;
@@ -187,9 +198,12 @@ export interface ProcessHumanTurnExternalActionSpec<
187
198
  > extends StaticRouteTarget {
188
199
  id: string;
189
200
  source: ExternalActionSource<TParams, TState, TEvent, TInput>;
201
+ /** Arms and exposes this action only when the current process snapshot matches. */
202
+ when?: (ctx: ExternalSourceResolveContext<TParams, TState>) => boolean;
190
203
  label?: string;
191
204
  description?: string;
192
205
  publishInput?: ExternalActionInputPublication;
206
+ effect?: ExternalSourceEffect<TParams, TState, TEvent, TInput>;
193
207
  }
194
208
 
195
209
  export interface ProcessActionBranchSpec extends StaticRouteTarget {
@@ -222,8 +236,7 @@ export type ProcessHumanTurnActionSpec<TParams = unknown, TState = unknown> = Ba
222
236
  externalTriggers?: readonly ProcessActionExternalTrigger[];
223
237
  } & (StaticActionRouting | BranchingActionRouting<TParams, TState>);
224
238
 
225
- export interface ProcessToolOutcomeSpec<TParams = unknown, TState = unknown>
226
- extends StaticRouteTarget {
239
+ interface ProcessToolOutcomeBaseSpec<TParams = unknown, TState = unknown> {
227
240
  description: string;
228
241
  parameters: Record<string, OutcomeToolParameterSpec>;
229
242
  /** Product published from this outcome's turn-result markdown, when this outcome is selected. */
@@ -231,15 +244,28 @@ export interface ProcessToolOutcomeSpec<TParams = unknown, TState = unknown>
231
244
  /** Outcome parameter whose markdown value is captured as the turn result. */
232
245
  turnResultMarkdownParameter?: string;
233
246
  effect?: ProcessOutcomeEffect<TParams, TState>;
247
+ /** Parks the process on this turn after recording the outcome. */
248
+ wait?: true;
234
249
  lifecycleIntent?: ProcessOutcomeLifecycleIntent<TParams, TState>;
235
250
  }
251
+
252
+ export type ProcessToolOutcomeSpec<
253
+ TParams = unknown,
254
+ TState = unknown,
255
+ > = ProcessToolOutcomeBaseSpec<TParams, TState> &
256
+ (
257
+ | StaticRouteTarget
258
+ | {
259
+ branches: Record<string, ProcessOutcomeBranchSpec>;
260
+ choose: ProcessOutcomeBranchSelector<TParams, TState>;
261
+ }
262
+ );
236
263
  export type HumanTurnOperatorAttention = "required" | "passive";
237
264
 
238
265
  export interface HumanTurnDefinition<TParams = unknown, TState = unknown> {
239
266
  kind: "human";
240
267
  description: string;
241
- /** Optional for generic operator-waiting turns; review turns should set it. */
242
- reviewSubject?: ReviewSubject;
268
+ /** Named product rendered as the subject of this human review turn. */
243
269
  reviewProduct?: string;
244
270
  reviewSemanticRef?: ProcessSemanticEntryRefKey;
245
271
  /** Controls whether entering this turn should raise an action-required toast. */
@@ -293,7 +319,6 @@ export interface LlmTurnDefinition<
293
319
  outcomes?: Partial<Record<TOutcome, ProcessToolOutcomeSpec<TParams, TState>>>;
294
320
  turnEnd?: ProcessTurnEndSpec<TParams, TState, TOutcome>;
295
321
  turnResultMarkdown?: TurnResultMarkdownBehavior;
296
- reviewSubject?: ReviewSubject;
297
322
  reviewSemanticRef?: ProcessSemanticEntryRefKey;
298
323
  resultSemanticRef?: ProcessSemanticEntryRefKey;
299
324
  publishedProduct?: string;
@@ -310,9 +335,12 @@ export interface AutomaticTurnDefinition<
310
335
  > {
311
336
  kind: "automatic";
312
337
  description: string;
338
+ /** Server-owned integration tools callable by this deterministic worker turn. */
339
+ integrationTools?: readonly string[];
340
+ /** External events armed while this automatic turn is selected and waiting. */
341
+ externalActions?: Record<string, ProcessHumanTurnExternalActionSpec<TParams, TState>>;
313
342
  outcomes?: Partial<Record<TOutcome, ProcessToolOutcomeSpec<TParams, TState>>>;
314
343
  turnEnd?: ProcessTurnEndSpec<TParams, TState, TOutcome>;
315
- reviewSubject?: ReviewSubject;
316
344
  reviewSemanticRef?: ProcessSemanticEntryRefKey;
317
345
  run(
318
346
  ctx: ProcessRuntimeTurnContext<TParams, TState>,
@@ -335,7 +363,6 @@ export interface ServerAutomaticTurnDefinition<
335
363
  description: string;
336
364
  outcomes?: Partial<Record<TOutcome, ProcessToolOutcomeSpec<TParams, TState>>>;
337
365
  turnEnd?: ProcessTurnEndSpec<TParams, TState, TOutcome>;
338
- reviewSubject?: ReviewSubject;
339
366
  reviewSemanticRef?: ProcessSemanticEntryRefKey;
340
367
  /**
341
368
  * Controls startup/drainer behavior when a durable running turn record already exists.
@@ -364,7 +391,6 @@ export interface ExternalTurnDefinition<TParams = unknown, TState = unknown> {
364
391
  kind: "external";
365
392
  description: string;
366
393
  transitions: readonly ExternalSourceTransition<TParams, TState>[];
367
- reviewSubject?: ReviewSubject;
368
394
  reviewSemanticRef?: ProcessSemanticEntryRefKey;
369
395
  }
370
396
 
@@ -488,12 +514,79 @@ function buildOutcomeTransition<TParams, TState>(
488
514
  target: ProcessToolOutcomeSpec<TParams, TState> | ProcessTurnEndSpec<TParams, TState>,
489
515
  knownTurnIds?: ReadonlySet<TurnId>,
490
516
  ): NormalizedRouteTarget {
517
+ if ("branches" in target) {
518
+ throw new Error(
519
+ `Turn '${turnId}' outcome '${outcome}' must compile state routing before a static transition`,
520
+ );
521
+ }
522
+ if ("wait" in target && target.wait && hasDeclaredStaticRouteTarget(target)) {
523
+ throw new Error(`Turn '${turnId}' outcome '${outcome}' cannot wait and declare another route`);
524
+ }
491
525
  if (!hasDeclaredStaticRouteTarget(target)) {
492
526
  return { nextTurnId: turnId };
493
527
  }
494
528
  return normalizeStaticRouteTarget(`Turn '${turnId}' outcome '${outcome}'`, target, knownTurnIds);
495
529
  }
496
530
 
531
+ type CompiledOutcomeRouting<TParams, TState> = {
532
+ routes: Readonly<Record<string, NormalizedActionRoute>>;
533
+ choose: ProcessOutcomeBranchSelector<TParams, TState>;
534
+ };
535
+
536
+ type CompiledOutcome<TParams, TState> = {
537
+ effect?: ProcessOutcomeEffect<TParams, TState>;
538
+ routing?: CompiledOutcomeRouting<TParams, TState>;
539
+ };
540
+
541
+ function normalizeBranchRoutes(input: {
542
+ subject: string;
543
+ branches: Record<string, ProcessActionBranchSpec>;
544
+ knownTurnIds?: ReadonlySet<TurnId>;
545
+ }): {
546
+ routes: Readonly<Record<string, NormalizedActionRoute>>;
547
+ transitions: readonly NormalizedActionRoute[];
548
+ } {
549
+ const entries = Object.entries(input.branches);
550
+ if (entries.length === 0) throw new Error(`${input.subject} must declare at least one branch`);
551
+ const routes: Record<string, NormalizedActionRoute> = {};
552
+ const transitions: NormalizedActionRoute[] = [];
553
+ const usedTriggers = new Set<string>();
554
+ for (const [branchId, branchSpec] of entries) {
555
+ if (branchId.trim() === "") throw new Error(`${input.subject} contains an empty branch id`);
556
+ const target = normalizeStaticRouteTarget(
557
+ `${input.subject} branch '${branchId}'`,
558
+ branchSpec,
559
+ input.knownTurnIds,
560
+ );
561
+ const trigger = branchSpec.trigger ?? branchId;
562
+ if (usedTriggers.has(trigger)) {
563
+ throw new Error(`${input.subject} contains duplicate branch trigger '${trigger}'`);
564
+ }
565
+ usedTriggers.add(trigger);
566
+ const route = { ...target, trigger };
567
+ routes[branchId] = route;
568
+ transitions.push(route);
569
+ }
570
+ return { routes, transitions };
571
+ }
572
+
573
+ function resolveOutcomeRouting<TParams, TState>(input: {
574
+ turnId: TurnId;
575
+ outcome: string;
576
+ spec: ProcessToolOutcomeSpec<TParams, TState>;
577
+ knownTurnIds: ReadonlySet<TurnId>;
578
+ }): CompiledOutcomeRouting<TParams, TState> | null {
579
+ if (!("branches" in input.spec)) {
580
+ return null;
581
+ }
582
+ const { routes } = normalizeBranchRoutes({
583
+ subject: `Turn '${input.turnId}' outcome '${input.outcome}'`,
584
+ branches: input.spec.branches,
585
+ knownTurnIds: input.knownTurnIds,
586
+ });
587
+ return { routes, choose: input.spec.choose };
588
+ }
589
+
497
590
  function resolveActionRouting<TParams, TState>(input: {
498
591
  turnId: TurnId;
499
592
  actionId: string;
@@ -504,48 +597,14 @@ function resolveActionRouting<TParams, TState>(input: {
504
597
  transitions: readonly NormalizedActionRoute[];
505
598
  } {
506
599
  if ("branches" in input.spec) {
507
- const entries = Object.entries(input.spec.branches) as Array<[string, ProcessActionBranchSpec]>;
508
- if (entries.length === 0) {
509
- throw new Error(
510
- `Action '${input.actionId}' on turn '${input.turnId}' must declare at least one branch`,
511
- );
512
- }
513
- const routes: Record<string, NormalizedActionRoute> = {};
514
- const resolvedTransitions: NormalizedActionRoute[] = [];
515
- const usedTriggers = new Set<string>();
516
- for (const [branchId, branchSpec] of entries) {
517
- if (branchId.trim() === "") {
518
- throw new Error(
519
- `Action '${input.actionId}' on turn '${input.turnId}' contains an empty branch id`,
520
- );
521
- }
522
- const target = normalizeStaticRouteTarget(
523
- `Action '${input.actionId}' branch '${branchId}' on turn '${input.turnId}'`,
524
- branchSpec,
525
- input.knownTurnIds,
526
- );
527
- const trigger = branchSpec.trigger ?? branchId;
528
- if (usedTriggers.has(trigger)) {
529
- throw new Error(
530
- `Action '${input.actionId}' on turn '${input.turnId}' contains duplicate branch trigger '${trigger}'`,
531
- );
532
- }
533
- usedTriggers.add(trigger);
534
- const normalized = {
535
- ...(target.nextTurnId ? { nextTurnId: target.nextTurnId } : {}),
536
- ...(target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {}),
537
- trigger,
538
- };
539
- routes[branchId] = normalized;
540
- resolvedTransitions.push(normalized);
541
- }
600
+ const { routes, transitions } = normalizeBranchRoutes({
601
+ subject: `Action '${input.actionId}' on turn '${input.turnId}'`,
602
+ branches: input.spec.branches,
603
+ knownTurnIds: input.knownTurnIds,
604
+ });
542
605
  return {
543
- routing: {
544
- kind: "branches",
545
- routes,
546
- choose: input.spec.choose,
547
- },
548
- transitions: resolvedTransitions,
606
+ routing: { kind: "branches", routes, choose: input.spec.choose },
607
+ transitions,
549
608
  };
550
609
  }
551
610
  const target = normalizeStaticRouteTarget(
@@ -768,34 +827,11 @@ function normalizeEffectStringArray(value: unknown): string[] {
768
827
  : [];
769
828
  }
770
829
 
771
- function getTurnReviewSubject(turnDef: TurnDefinition<unknown, unknown> | undefined) {
772
- if (!turnDef || !("reviewSubject" in turnDef)) {
773
- return null;
774
- }
775
- return turnDef.reviewSubject ?? null;
776
- }
777
-
778
- function patchReviewSubjectIntoState<TState>(
779
- state: TState,
780
- reviewSubject: ReviewSubject | null,
781
- ): TState {
782
- if (typeof state !== "object" || state === null || Array.isArray(state)) {
783
- return state;
784
- }
785
- return {
786
- ...(state as Record<string, unknown>),
787
- reviewSubject,
788
- } as TState;
789
- }
790
-
791
830
  async function buildSavePlanResultEffect<TParams, TState>(input: {
792
831
  intent: SavePlanResultLifecycleIntent<TParams, TState>;
793
832
  execution: ProcessOutcomeExecution<TParams, TState>;
794
- targetTurn: TurnDefinition<unknown, unknown> | undefined;
795
833
  }): Promise<ProcessEffectPlan<TState>> {
796
834
  const statePlan = input.intent.state ? await input.intent.state(input.execution) : undefined;
797
- const targetReviewSubject = getTurnReviewSubject(input.targetTurn);
798
- const baseState = statePlan?.state ?? input.execution.ctx.state;
799
835
  const planRevision = input.execution.ctx.process.planRevision + 1;
800
836
  const summary = normalizeEffectString(input.execution.event.params[input.intent.summaryParam]);
801
837
  const acceptanceCriteria = normalizeEffectStringArray(
@@ -807,7 +843,6 @@ async function buildSavePlanResultEffect<TParams, TState>(input: {
807
843
  : normalizeEffectString(input.execution.event.params[input.intent.planMarkdownParam]);
808
844
 
809
845
  return mergeProcessEffectPlans(statePlan, {
810
- state: patchReviewSubjectIntoState(baseState, targetReviewSubject),
811
846
  processPatch: { planRevision },
812
847
  broadcasts: [
813
848
  {
@@ -836,25 +871,27 @@ async function buildSavePlanResultEffect<TParams, TState>(input: {
836
871
 
837
872
  function resolveOutcomeEffect<TParams, TState>(input: {
838
873
  spec: ProcessToolOutcomeSpec<TParams, TState> | ProcessTurnEndSpec<TParams, TState, string>;
839
- targetTurn: TurnDefinition<unknown, unknown> | undefined;
840
874
  }): ProcessOutcomeEffect<TParams, TState> | undefined {
841
875
  const lifecycleIntent = "lifecycleIntent" in input.spec ? input.spec.lifecycleIntent : undefined;
842
- if (!lifecycleIntent) {
843
- return input.spec.effect;
844
- }
876
+ const waits = "wait" in input.spec && input.spec.wait === true;
877
+ if (!lifecycleIntent && !waits) return input.spec.effect;
845
878
  return async (execution) => {
846
879
  const explicitPlan = input.spec.effect ? await input.spec.effect(execution) : undefined;
847
880
  let lifecyclePlan: ProcessEffectPlan<TState> | undefined;
848
- switch (lifecycleIntent.kind) {
849
- case "save_plan_result":
850
- lifecyclePlan = await buildSavePlanResultEffect({
851
- intent: lifecycleIntent,
852
- execution,
853
- targetTurn: input.targetTurn,
854
- });
855
- break;
881
+ if (lifecycleIntent) {
882
+ switch (lifecycleIntent.kind) {
883
+ case "save_plan_result":
884
+ lifecyclePlan = await buildSavePlanResultEffect({
885
+ intent: lifecycleIntent,
886
+ execution,
887
+ });
888
+ break;
889
+ }
856
890
  }
857
- return mergeProcessEffectPlans(explicitPlan, lifecyclePlan);
891
+ const result = mergeProcessEffectPlans(explicitPlan, lifecyclePlan);
892
+ return waits
893
+ ? mergeProcessEffectPlans(result, { processPatch: { lifecycleStatus: "waiting" } })
894
+ : result;
858
895
  };
859
896
  }
860
897
 
@@ -993,10 +1030,9 @@ function compileTurnOutcomeDefinitions<TParams, TState>(input: {
993
1030
  outcomes?: Partial<Record<string, ProcessToolOutcomeSpec<TParams, TState>>>;
994
1031
  turnEnd?: ProcessTurnEndSpec<TParams, TState, string>;
995
1032
  knownTurnIds: ReadonlySet<TurnId>;
996
- turnDefinitionsById: ReadonlyMap<TurnId, TurnDefinition<unknown, unknown>>;
997
1033
  }): {
998
1034
  transitions: readonly ProcessTurnTransition[];
999
- effects: ReadonlyMap<string, ProcessOutcomeEffect<TParams, TState> | undefined>;
1035
+ outcomes: ReadonlyMap<string, CompiledOutcome<TParams, TState>>;
1000
1036
  } {
1001
1037
  const outcomeEntries = Object.entries(input.outcomes ?? {}) as Array<
1002
1038
  [string, ProcessToolOutcomeSpec<TParams, TState>]
@@ -1013,26 +1049,40 @@ function compileTurnOutcomeDefinitions<TParams, TState>(input: {
1013
1049
  }
1014
1050
 
1015
1051
  const transitions: ProcessTurnTransition[] = [];
1016
- const effects = new Map<string, ProcessOutcomeEffect<TParams, TState> | undefined>();
1052
+ const outcomes = new Map<string, CompiledOutcome<TParams, TState>>();
1017
1053
  for (const [outcome, spec] of outcomeEntries) {
1018
1054
  if (outcome.trim() === "") {
1019
1055
  throw new Error(`Turn '${input.turnId}' declares an empty outcome id`);
1020
1056
  }
1021
- const target = buildOutcomeTransition(input.turnId, outcome, spec, input.knownTurnIds);
1022
- transitions.push({
1023
- ...(target.nextTurnId ? { nextTurnId: target.nextTurnId } : {}),
1024
- ...(target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {}),
1057
+ const routing = resolveOutcomeRouting({
1058
+ turnId: input.turnId,
1025
1059
  outcome,
1060
+ spec,
1061
+ knownTurnIds: input.knownTurnIds,
1062
+ });
1063
+ const target = routing
1064
+ ? null
1065
+ : buildOutcomeTransition(input.turnId, outcome, spec, input.knownTurnIds);
1066
+ if (routing) {
1067
+ for (const route of Object.values(routing.routes)) {
1068
+ transitions.push({
1069
+ ...(route.nextTurnId ? { nextTurnId: route.nextTurnId } : {}),
1070
+ ...(route.lifecycleStatus ? { lifecycleStatus: route.lifecycleStatus } : {}),
1071
+ trigger: route.trigger,
1072
+ outcome,
1073
+ });
1074
+ }
1075
+ } else if (target) {
1076
+ transitions.push({
1077
+ ...(target.nextTurnId ? { nextTurnId: target.nextTurnId } : {}),
1078
+ ...(target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {}),
1079
+ outcome,
1080
+ });
1081
+ }
1082
+ outcomes.set(outcome, {
1083
+ effect: resolveOutcomeEffect({ spec }),
1084
+ ...(routing ? { routing } : {}),
1026
1085
  });
1027
- effects.set(
1028
- outcome,
1029
- resolveOutcomeEffect({
1030
- spec,
1031
- targetTurn: target.nextTurnId
1032
- ? input.turnDefinitionsById.get(target.nextTurnId)
1033
- : undefined,
1034
- }),
1035
- );
1036
1086
  }
1037
1087
 
1038
1088
  if (input.turnEnd) {
@@ -1050,21 +1100,12 @@ function compileTurnOutcomeDefinitions<TParams, TState>(input: {
1050
1100
  ...(target.lifecycleStatus ? { lifecycleStatus: target.lifecycleStatus } : {}),
1051
1101
  outcome: input.turnEnd.outcome,
1052
1102
  });
1053
- effects.set(
1054
- input.turnEnd.outcome,
1055
- resolveOutcomeEffect({
1056
- spec: input.turnEnd,
1057
- targetTurn: target.nextTurnId
1058
- ? input.turnDefinitionsById.get(target.nextTurnId)
1059
- : undefined,
1060
- }),
1061
- );
1103
+ outcomes.set(input.turnEnd.outcome, {
1104
+ effect: resolveOutcomeEffect({ spec: input.turnEnd }),
1105
+ });
1062
1106
  }
1063
1107
 
1064
- return {
1065
- transitions,
1066
- effects,
1067
- };
1108
+ return { transitions, outcomes };
1068
1109
  }
1069
1110
 
1070
1111
  function addActionUse<TParams, TState>(input: {
@@ -1194,6 +1235,68 @@ function validateActionPrimaryPrompt(
1194
1235
  }
1195
1236
  }
1196
1237
 
1238
+ function deriveExternalActions<TParams, TState>(input: {
1239
+ turnId: TurnId;
1240
+ externalActions?: Record<string, ProcessHumanTurnExternalActionSpec<TParams, TState>>;
1241
+ knownTurnIds?: ReadonlySet<TurnId>;
1242
+ turnDefinitionsById?: ReadonlyMap<TurnId, TurnDefinition<unknown, unknown>>;
1243
+ reservedTriggers?: ReadonlyMap<string, string>;
1244
+ }): {
1245
+ externalActions: readonly DerivedHumanTurnExternalAction<TParams, TState>[];
1246
+ transitions: readonly ProcessTurnTransition[];
1247
+ } {
1248
+ const externalActions: DerivedHumanTurnExternalAction<TParams, TState>[] = [];
1249
+ const transitions: ProcessTurnTransition[] = [];
1250
+ const usedTriggers = new Map(input.reservedTriggers);
1251
+ for (const [externalActionId, actionSpec] of Object.entries(input.externalActions ?? {})) {
1252
+ if (actionSpec.publishInput) {
1253
+ assertValidProcessProductName(actionSpec.publishInput.productName);
1254
+ if (actionSpec.publishInput.inputField.trim() === "") {
1255
+ throw new Error(
1256
+ `Turn '${input.turnId}' external action '${externalActionId}' publishInput must declare a non-empty inputField`,
1257
+ );
1258
+ }
1259
+ }
1260
+ validateExternalActionPublishedInputTarget({
1261
+ turnId: input.turnId,
1262
+ externalActionId,
1263
+ spec: actionSpec,
1264
+ turnDefinitionsById: input.turnDefinitionsById,
1265
+ });
1266
+ const transition = resolveExternalActionRoute({
1267
+ turnId: input.turnId,
1268
+ externalActionId,
1269
+ spec: actionSpec,
1270
+ knownTurnIds: input.knownTurnIds,
1271
+ });
1272
+ const existingActionId = usedTriggers.get(transition.trigger);
1273
+ if (existingActionId) {
1274
+ throw new Error(
1275
+ `Turn '${input.turnId}' contains duplicate trigger '${transition.trigger}' across action '${existingActionId}' and external action '${externalActionId}'`,
1276
+ );
1277
+ }
1278
+ usedTriggers.set(transition.trigger, externalActionId);
1279
+ transitions.push({
1280
+ ...(transition.nextTurnId ? { nextTurnId: transition.nextTurnId } : {}),
1281
+ ...(transition.lifecycleStatus ? { lifecycleStatus: transition.lifecycleStatus } : {}),
1282
+ trigger: transition.trigger,
1283
+ });
1284
+ externalActions.push({
1285
+ externalActionId,
1286
+ actionSpec,
1287
+ transition,
1288
+ view: {
1289
+ id: externalActionArmingId({ turnId: input.turnId, externalActionId }),
1290
+ externalActionId,
1291
+ sourceKind: actionSpec.source.kind,
1292
+ label: actionSpec.label ?? actionSpec.source.label ?? null,
1293
+ description: actionSpec.description ?? actionSpec.source.description ?? null,
1294
+ },
1295
+ });
1296
+ }
1297
+ return { externalActions, transitions };
1298
+ }
1299
+
1197
1300
  function deriveHumanTurnActions<TParams, TState>(input: {
1198
1301
  turnId: TurnId;
1199
1302
  spec: HumanTurnDefinition<TParams, TState>;
@@ -1281,68 +1384,17 @@ function deriveHumanTurnActions<TParams, TState>(input: {
1281
1384
  });
1282
1385
  }
1283
1386
 
1284
- const externalActionEntries = Object.entries(input.spec.externalActions ?? {}) as Array<
1285
- [string, ProcessHumanTurnExternalActionSpec<TParams, TState>]
1286
- >;
1287
- const derivedExternalActions: DerivedHumanTurnExternalAction<TParams, TState>[] = [];
1288
- const externalActionIds = new Set<string>();
1289
- for (const [externalActionId, actionSpec] of externalActionEntries) {
1290
- if (externalActionIds.has(externalActionId)) {
1291
- throw new Error(
1292
- `Human turn '${input.turnId}' declares duplicate external action '${externalActionId}'`,
1293
- );
1294
- }
1295
- externalActionIds.add(externalActionId);
1296
- if (actionSpec.publishInput) {
1297
- assertValidProcessProductName(actionSpec.publishInput.productName);
1298
- if (actionSpec.publishInput.inputField.trim() === "") {
1299
- throw new Error(
1300
- `Human turn '${input.turnId}' external action '${externalActionId}' publishInput must declare a non-empty inputField`,
1301
- );
1302
- }
1303
- }
1304
- validateExternalActionPublishedInputTarget({
1305
- turnId: input.turnId,
1306
- externalActionId,
1307
- spec: actionSpec,
1308
- turnDefinitionsById: input.turnDefinitionsById,
1309
- });
1310
- const transition = resolveExternalActionRoute({
1311
- turnId: input.turnId,
1312
- externalActionId,
1313
- spec: actionSpec,
1314
- knownTurnIds: input.knownTurnIds,
1315
- });
1316
- const existingActionId = actionIdByTrigger.get(transition.trigger);
1317
- if (existingActionId) {
1318
- throw new Error(
1319
- `Human turn '${input.turnId}' contains duplicate trigger '${transition.trigger}' across action '${existingActionId}' and external action '${externalActionId}'`,
1320
- );
1321
- }
1322
- actionIdByTrigger.set(transition.trigger, externalActionId);
1323
- transitions.push({
1324
- ...(transition.nextTurnId ? { nextTurnId: transition.nextTurnId } : {}),
1325
- ...(transition.lifecycleStatus ? { lifecycleStatus: transition.lifecycleStatus } : {}),
1326
- trigger: transition.trigger,
1327
- });
1328
- derivedExternalActions.push({
1329
- externalActionId,
1330
- actionSpec,
1331
- transition,
1332
- view: {
1333
- id: externalActionArmingId({ turnId: input.turnId, externalActionId }),
1334
- externalActionId,
1335
- sourceKind: actionSpec.source.kind,
1336
- label: actionSpec.label ?? actionSpec.source.label ?? null,
1337
- description: actionSpec.description ?? actionSpec.source.description ?? null,
1338
- },
1339
- });
1340
- }
1341
-
1387
+ const derivedExternal = deriveExternalActions({
1388
+ turnId: input.turnId,
1389
+ externalActions: input.spec.externalActions,
1390
+ knownTurnIds: input.knownTurnIds,
1391
+ turnDefinitionsById: input.turnDefinitionsById,
1392
+ reservedTriggers: actionIdByTrigger,
1393
+ });
1342
1394
  return {
1343
1395
  actions: derivedActions,
1344
- externalActions: derivedExternalActions,
1345
- transitions,
1396
+ externalActions: derivedExternal.externalActions,
1397
+ transitions: [...transitions, ...derivedExternal.transitions],
1346
1398
  };
1347
1399
  }
1348
1400
 
@@ -1566,9 +1618,9 @@ function buildDefinedProcess<TParams, TState>(
1566
1618
 
1567
1619
  const turns = new Map<TurnId, ProcessTurnBinding<TurnDefinition<TParams, TState>>>();
1568
1620
  const actionUses = new Map<string, CompiledActionUse<TParams, TState>[]>();
1569
- const outcomeEffects = new Map<
1621
+ const compiledOutcomesByTurn = new Map<
1570
1622
  TurnId,
1571
- ReadonlyMap<string, ProcessOutcomeEffect<TParams, TState> | undefined>
1623
+ ReadonlyMap<string, CompiledOutcome<TParams, TState>>
1572
1624
  >();
1573
1625
  const executableTurns = new Map<TurnId, CompiledExecutableTurn<TParams, TState>>();
1574
1626
 
@@ -1579,10 +1631,9 @@ function buildDefinedProcess<TParams, TState>(
1579
1631
  outcomes: turnSpec.outcomes,
1580
1632
  turnEnd: turnSpec.turnEnd,
1581
1633
  knownTurnIds,
1582
- turnDefinitionsById,
1583
1634
  });
1584
1635
  turns.set(turnId, createProcessTurnBinding(turnSpec, compiledOutcomes.transitions));
1585
- outcomeEffects.set(turnId, compiledOutcomes.effects);
1636
+ compiledOutcomesByTurn.set(turnId, compiledOutcomes.outcomes);
1586
1637
  executableTurns.set(turnId, {
1587
1638
  kind: "llm",
1588
1639
  id: turnId,
@@ -1597,10 +1648,24 @@ function buildDefinedProcess<TParams, TState>(
1597
1648
  outcomes: turnSpec.outcomes,
1598
1649
  turnEnd: turnSpec.turnEnd,
1599
1650
  knownTurnIds,
1600
- turnDefinitionsById,
1601
1651
  });
1602
- turns.set(turnId, createProcessTurnBinding(turnSpec, compiledOutcomes.transitions));
1603
- outcomeEffects.set(turnId, compiledOutcomes.effects);
1652
+ const externalTransitions =
1653
+ turnSpec.kind === "automatic"
1654
+ ? deriveExternalActions({
1655
+ turnId,
1656
+ externalActions: turnSpec.externalActions,
1657
+ knownTurnIds,
1658
+ turnDefinitionsById,
1659
+ }).transitions
1660
+ : [];
1661
+ turns.set(
1662
+ turnId,
1663
+ createProcessTurnBinding(turnSpec, [
1664
+ ...compiledOutcomes.transitions,
1665
+ ...externalTransitions,
1666
+ ]),
1667
+ );
1668
+ compiledOutcomesByTurn.set(turnId, compiledOutcomes.outcomes);
1604
1669
  if (turnSpec.kind === "automatic") {
1605
1670
  executableTurns.set(turnId, {
1606
1671
  kind: "automatic",
@@ -1723,19 +1788,31 @@ function buildDefinedProcess<TParams, TState>(
1723
1788
  });
1724
1789
  }
1725
1790
 
1726
- for (const [turnId, effects] of outcomeEffects) {
1791
+ for (const [turnId, outcomes] of compiledOutcomesByTurn) {
1727
1792
  api.onTurnOutcome(turnId, async (event, ctx) => {
1728
- const effect = effects.get(event.outcome);
1729
- if (!effect) {
1793
+ const { effect, routing } = outcomes.get(event.outcome) ?? {};
1794
+ if (!effect && !routing) {
1730
1795
  return;
1731
1796
  }
1732
- const result = await effect({
1797
+ const execution = {
1733
1798
  ctx: makeProcessServerRuntimeContext(ctx),
1734
1799
  event,
1735
1800
  turnId,
1736
1801
  outcome: event.outcome,
1737
- });
1738
- await applyProcessEffectPlan({ ctx, result });
1802
+ };
1803
+ const result = effect ? await effect(execution) : undefined;
1804
+ let transition: Omit<ServerTransitionRequest<TState>, "state"> | undefined;
1805
+ if (routing) {
1806
+ const branchId = await routing.choose(execution);
1807
+ const route = routing.routes[branchId];
1808
+ if (!route) {
1809
+ throw new Error(
1810
+ `Turn '${turnId}' outcome '${event.outcome}' selected unknown branch '${branchId}'`,
1811
+ );
1812
+ }
1813
+ transition = buildActionTransitionRequest(route);
1814
+ }
1815
+ await applyProcessEffectPlan({ ctx, result, transition });
1739
1816
  });
1740
1817
  }
1741
1818