@leitwerk-dev/process-sdk 0.3.1 → 0.4.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 (63) hide show
  1. package/dist/{chunk-GVBLXKSR.js → chunk-HT2AXXLH.js} +2 -1
  2. package/dist/chunk-HT2AXXLH.js.map +1 -0
  3. package/dist/core-capabilities.d.ts +57 -1
  4. package/dist/core-capabilities.d.ts.map +1 -1
  5. package/dist/define-process.d.ts +40 -26
  6. package/dist/define-process.d.ts.map +1 -1
  7. package/dist/{extension-api-DM-AvWOW.d.ts → extension-api-Ljc4UTZ0.d.ts} +258 -64
  8. package/dist/extension-api.d.ts +52 -0
  9. package/dist/extension-api.d.ts.map +1 -1
  10. package/dist/external-source-poll.d.ts +1 -1
  11. package/dist/external-source-poll.d.ts.map +1 -1
  12. package/dist/file-external-source.d.ts +32 -0
  13. package/dist/file-external-source.d.ts.map +1 -0
  14. package/dist/flow-mapped.typecheck.d.ts +2 -0
  15. package/dist/flow-mapped.typecheck.d.ts.map +1 -0
  16. package/dist/flow.d.ts +188 -177
  17. package/dist/flow.d.ts.map +1 -1
  18. package/dist/index.d.ts +11 -4
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +4424 -4327
  21. package/dist/index.js.map +1 -1
  22. package/dist/mapped-turn.d.ts +6 -22
  23. package/dist/mapped-turn.d.ts.map +1 -1
  24. package/dist/outcome-contract.d.ts +19 -0
  25. package/dist/outcome-contract.d.ts.map +1 -0
  26. package/dist/outcome-schema.d.ts +23 -0
  27. package/dist/outcome-schema.d.ts.map +1 -0
  28. package/dist/pi-config-public.js +1 -1
  29. package/dist/pi-config.js +1 -1
  30. package/dist/process-flow-view.d.ts +3 -14
  31. package/dist/process-flow-view.d.ts.map +1 -1
  32. package/dist/process-graph.d.ts +10 -4
  33. package/dist/process-graph.d.ts.map +1 -1
  34. package/dist/scoped-settings.d.ts +87 -0
  35. package/dist/scoped-settings.d.ts.map +1 -0
  36. package/dist/ticket-creation.d.ts +24 -0
  37. package/dist/ticket-creation.d.ts.map +1 -0
  38. package/dist/turn-semantics.d.ts +3 -3
  39. package/dist/turn-semantics.d.ts.map +1 -1
  40. package/dist/turn-wait.d.ts +53 -0
  41. package/dist/turn-wait.d.ts.map +1 -0
  42. package/dist/types.d.ts +31 -18
  43. package/dist/types.d.ts.map +1 -1
  44. package/package.json +6 -6
  45. package/src/core-capabilities.ts +76 -1
  46. package/src/define-process.ts +420 -596
  47. package/src/extension-api.ts +60 -0
  48. package/src/external-source-poll.ts +6 -24
  49. package/src/file-external-source.ts +135 -0
  50. package/src/flow-mapped.typecheck.ts +136 -0
  51. package/src/flow.ts +744 -805
  52. package/src/index.ts +48 -1
  53. package/src/mapped-turn.ts +74 -23
  54. package/src/outcome-contract.ts +126 -0
  55. package/src/outcome-schema.ts +314 -0
  56. package/src/process-flow-view.ts +84 -346
  57. package/src/process-graph.ts +95 -45
  58. package/src/scoped-settings.ts +113 -0
  59. package/src/ticket-creation.ts +113 -0
  60. package/src/turn-semantics.ts +99 -188
  61. package/src/turn-wait.ts +76 -0
  62. package/src/types.ts +30 -16
  63. package/dist/chunk-GVBLXKSR.js.map +0 -1
package/src/flow.ts CHANGED
@@ -2,13 +2,15 @@ import path from "node:path";
2
2
  import {
3
3
  assertValidProcessProductName,
4
4
  humanizeProcessLabel,
5
+ normalizeStringArray,
5
6
  type ProcessInstance,
6
7
  type ProcessProject,
7
- type ProcessSemanticEntryRefKey,
8
8
  type ProcessTurnStartSelection,
9
9
  type ProcessTurnTerminalLifecycleStatus,
10
+ type ScopedSettingsSnapshot,
10
11
  type TurnId,
11
12
  type TurnProgressReport,
13
+ trimString,
12
14
  } from "@leitwerk-dev/domain";
13
15
  import type {
14
16
  AutomaticTurnDefinition,
@@ -17,10 +19,14 @@ import type {
17
19
  HumanTurnDefinition,
18
20
  HumanTurnOperatorAttention,
19
21
  LlmModelPurpose,
22
+ LlmOutcomeSubmission,
20
23
  LlmTurnDefinition,
24
+ LlmTurnPreparationContext,
25
+ OutcomeParameterContext,
21
26
  ProcessEffectPlan,
22
27
  ProcessHumanTurnActionSpec,
23
28
  ProcessHumanTurnExternalActionSpec,
29
+ ProcessOutcomeBranchSpec,
24
30
  ProcessOutcomeEffect,
25
31
  ProcessOutcomeExecution,
26
32
  ProcessRuntimeTurnContext,
@@ -43,6 +49,7 @@ import type {
43
49
  ProcessWatcherAPI,
44
50
  ProcessWatcherDefinition,
45
51
  ServerProcessAPI,
52
+ TurnDiagnosticReport,
46
53
  UiProcessAPI,
47
54
  WorkerCompleteInput,
48
55
  } from "./extension-api.js";
@@ -55,12 +62,13 @@ import type {
55
62
  MappedTurnItemContext,
56
63
  MappedTurnServerContext,
57
64
  } from "./mapped-turn.js";
58
- import {
59
- type ProcessGraphSource,
60
- toProcessGraphView,
61
- validateProcessGraphProducts,
62
- } from "./process-graph.js";
63
- import type { OutcomeToolParameterSpec, PiBuiltInToolName, ProcessPiConfig } from "./types.js";
65
+ import type { TurnWaitPredicate } from "./turn-wait.js";
66
+ import type {
67
+ OutcomeToolArrayItemSpec,
68
+ OutcomeToolParameterSpec,
69
+ PiBuiltInToolName,
70
+ ProcessPiConfig,
71
+ } from "./types.js";
64
72
 
65
73
  /** @public */
66
74
  type MaybePromise<T> = T | Promise<T>;
@@ -214,6 +222,8 @@ export type FlowPromptContext<
214
222
 
215
223
  /** @public */
216
224
  export interface FlowAutomaticRunContext<TParams = unknown, TState = unknown> {
225
+ /** Immutable non-secret settings captured for this turn. @public */
226
+ readonly scopedSettings?: ScopedSettingsSnapshot;
217
227
  /** @public */
218
228
  process: ProcessInstance;
219
229
  /** @public */
@@ -230,6 +240,15 @@ export interface FlowAutomaticRunContext<TParams = unknown, TState = unknown> {
230
240
  callIntegrationTool(name: string, args: Record<string, unknown>): Promise<unknown>;
231
241
  /** @public */
232
242
  reportProgress(report: TurnProgressReport): void;
243
+ /** Append a non-secret worker diagnostic for this turn attempt. @internal */
244
+ reportDiagnostic(report: TurnDiagnosticReport): void;
245
+ }
246
+
247
+ /** Worker context for correcting a submission before accepting it. @public */
248
+ export interface FlowOutcomeValidationContext<TParams = unknown, TState = unknown>
249
+ extends FlowAutomaticRunContext<TParams, TState> {
250
+ /** Preparation captured before prompting. @public */
251
+ prepared?: unknown;
233
252
  }
234
253
 
235
254
  /** @public */
@@ -293,35 +312,6 @@ type FlowOutcomeStateEffect<TParams, TState, TContext> = (
293
312
  input: FlowOutcomeEffectInput<TParams, TState, TContext>,
294
313
  ) => MaybePromise<TState>;
295
314
 
296
- function textField(input: {
297
- description: string;
298
- requiredErrorCode: string;
299
- }): OutcomeToolParameterSpec {
300
- return {
301
- type: "string",
302
- description: input.description,
303
- required: true,
304
- requiredErrorCode: input.requiredErrorCode,
305
- };
306
- }
307
-
308
- function stringArrayField(input: {
309
- description: string;
310
- requiredErrorCode: string;
311
- minItems: number;
312
- minItemsErrorCode: string;
313
- }): OutcomeToolParameterSpec {
314
- return {
315
- type: "array",
316
- description: input.description,
317
- items: { type: "string" },
318
- required: true,
319
- requiredErrorCode: input.requiredErrorCode,
320
- minItems: input.minItems,
321
- minItemsErrorCode: input.minItemsErrorCode,
322
- };
323
- }
324
-
325
315
  function normalizeProductName(productName: string): string {
326
316
  assertValidProcessProductName(productName);
327
317
  return productName;
@@ -355,10 +345,6 @@ function safeJoinInside(parent: string, childPath: string, context: string): str
355
345
  return targetPath;
356
346
  }
357
347
 
358
- function toWorkspaceClonePath(relativePath: string): string {
359
- return `./${relativePath.split(path.sep).join("/")}`;
360
- }
361
-
362
348
  function resolveSafeProjectWorkspacePath(key: string): {
363
349
  relativePath: string;
364
350
  workspaceClonePath: string;
@@ -375,7 +361,7 @@ function resolveSafeProjectWorkspacePath(key: string): {
375
361
  const relativePath = path.relative(virtualWorkspaceRoot, virtualTarget);
376
362
  return {
377
363
  relativePath,
378
- workspaceClonePath: toWorkspaceClonePath(relativePath),
364
+ workspaceClonePath: `./${relativePath.split(path.sep).join("/")}`,
379
365
  };
380
366
  }
381
367
 
@@ -383,47 +369,17 @@ function resolveRepoByKey(input: {
383
369
  projects: readonly ProcessProject[];
384
370
  workspaceRoot?: string;
385
371
  key: string;
386
- required: true;
387
- }): FlowRepoContext;
388
- function resolveRepoByKey(input: {
389
- projects: readonly ProcessProject[];
390
- workspaceRoot?: string;
391
- key: string;
392
- required: false;
393
- }): FlowRepoContext | undefined;
394
- function resolveRepoByKey(input: {
395
- projects: readonly ProcessProject[];
396
- workspaceRoot?: string;
397
- key: string;
398
- required: boolean;
399
372
  }): FlowRepoContext | undefined {
400
- const requestedKey = input.key.trim();
401
- if (!requestedKey) {
373
+ const key = input.key.trim();
374
+ if (!key) {
402
375
  throw new Error("Flow repo lookup requires a non-empty project key");
403
376
  }
404
- const matches = input.projects.filter((project) => project.key.trim() === requestedKey);
405
- if (matches.length === 0) {
406
- if (!input.required) {
407
- return undefined;
408
- }
409
- const availableKeys = input.projects
410
- .map((project) => project.key.trim())
411
- .filter((key) => key !== "")
412
- .join(", ");
413
- throw new Error(
414
- `Flow context requires project '${requestedKey}', but this process has no project with that key${
415
- availableKeys ? ` (available: ${availableKeys})` : ""
416
- }`,
417
- );
418
- }
377
+ const matches = input.projects.filter((project) => project.key.trim() === key);
378
+ if (matches.length === 0) return undefined;
419
379
  if (matches.length > 1) {
420
- throw new Error(`Flow context found duplicate project key '${requestedKey}'`);
380
+ throw new Error(`Flow context found duplicate project key '${key}'`);
421
381
  }
422
382
  const project = matches[0];
423
- const key = project.key.trim();
424
- if (!key) {
425
- throw new Error("Flow context requires projects to have non-empty keys");
426
- }
427
383
  const baseBranch = project.baseBranch.trim();
428
384
  if (!baseBranch) {
429
385
  throw new Error(`Flow context project '${key}' has no base branch`);
@@ -454,13 +410,23 @@ function createFlowRepoLookup(input: {
454
410
  projects: readonly ProcessProject[];
455
411
  workspaceRoot?: string;
456
412
  }): FlowRepoLookup {
413
+ const get = (key: string): FlowRepoContext => {
414
+ const repo = resolveRepoByKey({ ...input, key });
415
+ if (repo) return repo;
416
+ const availableKeys = input.projects
417
+ .map((project) => project.key.trim())
418
+ .filter((key) => key !== "")
419
+ .join(", ");
420
+ throw new Error(
421
+ `Flow context requires project '${key.trim()}', but this process has no project with that key${
422
+ availableKeys ? ` (available: ${availableKeys})` : ""
423
+ }`,
424
+ );
425
+ };
457
426
  return {
458
- get: (key) => resolveRepoByKey({ ...input, key, required: true }),
459
- optional: (key) => resolveRepoByKey({ ...input, key, required: false }),
460
- all: () =>
461
- input.projects.map((project) =>
462
- resolveRepoByKey({ ...input, key: project.key, required: true }),
463
- ),
427
+ get,
428
+ optional: (key) => resolveRepoByKey({ ...input, key }),
429
+ all: () => input.projects.map((project) => get(project.key)),
464
430
  };
465
431
  }
466
432
 
@@ -488,23 +454,16 @@ export function createFlowPromptContext<
488
454
  optionalConsumedProducts: readonly string[] = [],
489
455
  ): FlowPromptContext<TParams, TState, TConsumedProducts, TPrepared> {
490
456
  const productInput: Record<string, string> = {};
491
- for (const productName of consumedProducts) {
457
+ const required = new Set<string>(consumedProducts);
458
+ for (const productName of new Set([...required, ...optionalConsumedProducts])) {
492
459
  const markdown = ctx.turnResultMarkdownByProduct?.[productName];
493
- if (typeof markdown !== "string" || markdown.trim() === "") {
460
+ if (typeof markdown === "string" && markdown.trim() !== "") {
461
+ productInput[productName] = markdown;
462
+ } else if (required.has(productName)) {
494
463
  throw new Error(
495
464
  `Flow prompt context requires product '${productName}' markdown, but the worker payload did not provide it`,
496
465
  );
497
466
  }
498
- productInput[productName] = markdown;
499
- }
500
- for (const productName of optionalConsumedProducts) {
501
- if (productName in productInput) {
502
- continue;
503
- }
504
- const markdown = ctx.turnResultMarkdownByProduct?.[productName];
505
- if (typeof markdown === "string" && markdown.trim() !== "") {
506
- productInput[productName] = markdown;
507
- }
508
467
  }
509
468
  return {
510
469
  ...createFlowContextBase(ctx),
@@ -522,6 +481,7 @@ export function createFlowAutomaticRunContext<TParams, TState>(
522
481
  ): FlowAutomaticRunContext<TParams, TState> {
523
482
  return {
524
483
  ...createFlowContextBase(ctx),
484
+ scopedSettings: ctx.scopedSettings,
525
485
  callIntegrationTool(name, args) {
526
486
  if (!ctx.callIntegrationTool) {
527
487
  throw new Error(`Automatic integration tool '${name}' is unavailable`);
@@ -531,6 +491,9 @@ export function createFlowAutomaticRunContext<TParams, TState>(
531
491
  reportProgress(report) {
532
492
  ctx.reportProgress?.(report);
533
493
  },
494
+ reportDiagnostic(report) {
495
+ ctx.reportDiagnostic?.(report);
496
+ },
534
497
  };
535
498
  }
536
499
 
@@ -575,17 +538,17 @@ class RouteAndEffectBuilder<TParams, TState, TContext> {
575
538
 
576
539
  /** @public */
577
540
  to(turnId: TurnId): this {
578
- return this.setTarget({ kind: "to", turnId });
541
+ return this.setTarget({ to: turnId });
579
542
  }
580
543
 
581
544
  /** @public */
582
545
  complete(): this {
583
- return this.setTarget({ kind: "complete" });
546
+ return this.setTarget({ complete: true });
584
547
  }
585
548
 
586
549
  /** @public */
587
550
  lifecycleStatus(status: ProcessTurnTerminalLifecycleStatus): this {
588
- return this.setTarget({ kind: "lifecycleStatus", status });
551
+ return this.setTarget({ lifecycleStatus: status });
589
552
  }
590
553
 
591
554
  /** @internal */
@@ -606,21 +569,19 @@ class RouteAndEffectBuilder<TParams, TState, TContext> {
606
569
  return this;
607
570
  }
608
571
 
572
+ /** @internal */
573
+ getEffect(): FlowOutcomeEffect<TParams, TState, TContext> | undefined {
574
+ return this.flowEffect;
575
+ }
576
+
609
577
  /** @internal */
610
578
  hasRoute(): boolean {
611
579
  return this.target !== null;
612
580
  }
613
581
 
614
582
  /** @internal */
615
- protected buildRouteTarget(): {
616
- /** @internal */
617
- to?: TurnId;
618
- /** @internal */
619
- complete?: boolean;
620
- /** @internal */
621
- lifecycleStatus?: ProcessTurnTerminalLifecycleStatus;
622
- } {
623
- return buildRouteTargetSpec(this.target);
583
+ buildRouteTarget(): Pick<ProcessTurnEndSpec, "to" | "complete" | "lifecycleStatus"> {
584
+ return { ...this.target };
624
585
  }
625
586
  }
626
587
 
@@ -628,42 +589,18 @@ class RouteAndEffectBuilder<TParams, TState, TContext> {
628
589
  export type FlowTargetSpec =
629
590
  | {
630
591
  /** @internal */
631
- kind: "to";
632
- /** @internal */
633
- turnId: TurnId;
592
+ to: TurnId;
634
593
  }
635
594
  | {
636
595
  /** @internal */
637
- kind: "complete";
596
+ complete: true;
638
597
  }
639
598
  | {
640
599
  /** @internal */
641
- kind: "lifecycleStatus";
642
- /** @internal */
643
- status: ProcessTurnTerminalLifecycleStatus;
600
+ lifecycleStatus: ProcessTurnTerminalLifecycleStatus;
644
601
  }
645
602
  | null;
646
603
 
647
- export function buildRouteTargetSpec(target: FlowTargetSpec): {
648
- /** @internal */
649
- to?: TurnId;
650
- /** @internal */
651
- complete?: boolean;
652
- /** @internal */
653
- lifecycleStatus?: ProcessTurnTerminalLifecycleStatus;
654
- } {
655
- if (!target) {
656
- return {};
657
- }
658
- if (target.kind === "to") {
659
- return { to: target.turnId };
660
- }
661
- if (target.kind === "complete") {
662
- return { complete: true };
663
- }
664
- return { lifecycleStatus: target.status };
665
- }
666
-
667
604
  /** @public */
668
605
  interface ParameterOptions extends Partial<Omit<OutcomeToolParameterSpec, "type" | "description">> {
669
606
  /** @public */
@@ -695,19 +632,38 @@ function isStringArray(value: unknown): value is readonly string[] {
695
632
  }
696
633
 
697
634
  /** @public */
698
- class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEffectBuilder<
699
- TParams,
700
- TState,
701
- TContext
702
- > {
635
+ class OutcomeParametersBuilder<TParams = unknown, TState = unknown> {
703
636
  /** @internal */
704
637
  protected outcomeDescription: string | null = null;
705
638
  /** @internal */
706
639
  protected parameters: Record<string, OutcomeToolParameterSpec> = {};
707
640
  /** @internal */
708
- protected publishedMarkdownParameter: string | null = null;
709
- /** @internal */
710
641
  protected summaryParameter: string | null = null;
642
+ private enforceSchema = false;
643
+ /** @internal */
644
+ protected parameterResolver?: (
645
+ ctx: OutcomeParameterContext<TParams, TState>,
646
+ ) => Record<string, OutcomeToolParameterSpec>;
647
+
648
+ /** Enforce a closed schema with no optional properties at supported providers. @public */
649
+ strictSchema(): this {
650
+ this.enforceSchema = true;
651
+ return this;
652
+ }
653
+
654
+ /** Declare alternatives for one argument. @public */
655
+ union(
656
+ name: string,
657
+ variants: readonly OutcomeToolArrayItemSpec[],
658
+ options: string | ParameterOptions = {},
659
+ ): this {
660
+ const resolved = typeof options === "string" ? { description: options } : options;
661
+ return this.parameter(name, {
662
+ ...resolved,
663
+ anyOf: variants,
664
+ description: resolved.description ?? "",
665
+ });
666
+ }
711
667
 
712
668
  /** Optional concise result publication, separate from the full Markdown. @public */
713
669
  resultSummary(name = "resultSummary"): this {
@@ -719,18 +675,16 @@ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEff
719
675
  }
720
676
 
721
677
  /** @internal */
722
- protected buildParameterSpec(kind: string): ProcessToolOutcomeSpec<TParams, TState> {
678
+ protected buildParameterSpec(
679
+ kind: string,
680
+ ): Pick<ProcessToolOutcomeSpec, "description" | "parameters" | "resultSummaryParameter"> {
723
681
  if (!this.outcomeDescription) throw new Error(`${kind} must declare .description(...)`);
724
682
  return {
725
683
  description: this.outcomeDescription,
726
684
  parameters: this.parameters,
685
+ ...(this.enforceSchema ? { strictSchema: true } : {}),
686
+ ...(this.parameterResolver ? { resolveParameters: this.parameterResolver } : {}),
727
687
  ...(this.summaryParameter ? { resultSummaryParameter: this.summaryParameter } : {}),
728
- ...(this.publishedMarkdownParameter
729
- ? {
730
- publishedProduct: this.publishedMarkdownParameter,
731
- turnResultMarkdownParameter: this.publishedMarkdownParameter,
732
- }
733
- : {}),
734
688
  };
735
689
  }
736
690
 
@@ -764,7 +718,8 @@ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEff
764
718
  };
765
719
  }
766
720
 
767
- private typedParameter(
721
+ /** @internal */
722
+ protected typedParameter(
768
723
  name: string,
769
724
  type: OutcomeToolParameterSpec["type"],
770
725
  options: string | ArrayParameterOptions = {},
@@ -778,29 +733,11 @@ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEff
778
733
  });
779
734
  }
780
735
 
781
- /** @internal */
736
+ /** @public */
782
737
  string(name: string, options: string | ParameterOptions = {}): this {
783
738
  return this.typedParameter(name, "string", options);
784
739
  }
785
740
 
786
- /** @public */
787
- markdown(name: string, options: string | MarkdownParameterOptions = {}): this {
788
- const resolved = typeof options === "string" ? { description: options } : options;
789
- const { publish, ...parameterOptions } = resolved;
790
- if (publish) {
791
- if (this.publishedMarkdownParameter && this.publishedMarkdownParameter !== name) {
792
- throw new Error("Outcome can publish only one markdown parameter");
793
- }
794
- normalizeProductName(name);
795
- this.publishedMarkdownParameter = name;
796
- }
797
- return this.typedParameter(name, "string", {
798
- ...parameterOptions,
799
- required: publish ? true : resolved.required,
800
- requiredErrorCode: resolved.requiredErrorCode ?? (publish ? `${name}_required` : undefined),
801
- });
802
- }
803
-
804
741
  /** @public */
805
742
  requiredString(name: string, options: string | ParameterOptions = {}): this {
806
743
  return this.typedParameter(name, "string", this.withRequired(name, options));
@@ -811,7 +748,7 @@ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEff
811
748
  return this.typedParameter(name, "number", options);
812
749
  }
813
750
 
814
- /** @internal */
751
+ /** @public */
815
752
  requiredNumber(name: string, options: string | ParameterOptions = {}): this {
816
753
  return this.typedParameter(name, "number", this.withRequired(name, options));
817
754
  }
@@ -821,7 +758,7 @@ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEff
821
758
  return this.typedParameter(name, "boolean", options);
822
759
  }
823
760
 
824
- /** @internal */
761
+ /** @public */
825
762
  requiredBoolean(name: string, options: string | ParameterOptions = {}): this {
826
763
  return this.typedParameter(name, "boolean", this.withRequired(name, options));
827
764
  }
@@ -831,9 +768,9 @@ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEff
831
768
  return this.typedParameter(name, "array", options);
832
769
  }
833
770
 
834
- /** @internal */
771
+ /** @public */
835
772
  requiredStringArray(name: string, options: string | ArrayParameterOptions = {}): this {
836
- return this.typedParameter(name, "array", this.withRequired(name, options));
773
+ return this.typedParameter(name, "array", { minItems: 1, ...this.withRequired(name, options) });
837
774
  }
838
775
 
839
776
  /** @internal */
@@ -862,7 +799,98 @@ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEff
862
799
 
863
800
  /** @public */
864
801
  requiredArray(name: string, options: string | ArrayParameterOptions = {}): this {
865
- return this.typedParameter(name, "array", this.withRequired(name, options));
802
+ return this.typedParameter(name, "array", { minItems: 1, ...this.withRequired(name, options) });
803
+ }
804
+ }
805
+
806
+ /** @public */
807
+ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends OutcomeParametersBuilder<
808
+ TParams,
809
+ TState
810
+ > {
811
+ private readonly route = new RouteAndEffectBuilder<TParams, TState, TContext>();
812
+ private publishedMarkdownParameter: string | null = null;
813
+
814
+ /** @public */
815
+ to(turnId: TurnId): this {
816
+ this.route.to(turnId);
817
+ return this;
818
+ }
819
+
820
+ /** @public */
821
+ complete(): this {
822
+ this.route.complete();
823
+ return this;
824
+ }
825
+
826
+ /** @public */
827
+ lifecycleStatus(status: ProcessTurnTerminalLifecycleStatus): this {
828
+ this.route.lifecycleStatus(status);
829
+ return this;
830
+ }
831
+
832
+ /** @internal */
833
+ stay(): this {
834
+ this.route.stay();
835
+ return this;
836
+ }
837
+
838
+ /** @public */
839
+ state(fn: FlowOutcomeStateEffect<TParams, TState, TContext>): this {
840
+ this.route.state(fn);
841
+ return this;
842
+ }
843
+
844
+ /** @public */
845
+ effect(fn: FlowOutcomeEffect<TParams, TState, TContext>): this {
846
+ this.route.effect(fn);
847
+ return this;
848
+ }
849
+
850
+ /** @internal */
851
+ hasRoute(): boolean {
852
+ return this.route.hasRoute();
853
+ }
854
+
855
+ /** @internal */
856
+ protected get flowEffect(): FlowOutcomeEffect<TParams, TState, TContext> | undefined {
857
+ return this.route.getEffect();
858
+ }
859
+
860
+ /** @internal */
861
+ protected buildRouteTarget() {
862
+ return this.route.buildRouteTarget();
863
+ }
864
+
865
+ /** @internal */
866
+ protected override buildParameterSpec(kind: string): ProcessToolOutcomeSpec<TParams, TState> {
867
+ return {
868
+ ...super.buildParameterSpec(kind),
869
+ ...(this.publishedMarkdownParameter
870
+ ? {
871
+ publishedProduct: this.publishedMarkdownParameter,
872
+ turnResultMarkdownParameter: this.publishedMarkdownParameter,
873
+ }
874
+ : {}),
875
+ };
876
+ }
877
+
878
+ /** @public */
879
+ markdown(name: string, options: string | MarkdownParameterOptions = {}): this {
880
+ const resolved = typeof options === "string" ? { description: options } : options;
881
+ const { publish, ...parameterOptions } = resolved;
882
+ if (publish) {
883
+ if (this.publishedMarkdownParameter && this.publishedMarkdownParameter !== name) {
884
+ throw new Error("Outcome can publish only one markdown parameter");
885
+ }
886
+ normalizeProductName(name);
887
+ this.publishedMarkdownParameter = name;
888
+ }
889
+ return this.typedParameter(name, "string", {
890
+ ...parameterOptions,
891
+ required: publish ? true : resolved.required,
892
+ requiredErrorCode: resolved.requiredErrorCode ?? (publish ? `${name}_required` : undefined),
893
+ });
866
894
  }
867
895
  }
868
896
 
@@ -875,9 +903,17 @@ export class OutcomeToolBuilder<
875
903
  TState,
876
904
  FlowLlmOutcomeEffectContext<TParams, TState>
877
905
  > {
906
+ /** Pure synchronous resolution at turn-start preparation. @public */
907
+ resolveParameters(
908
+ fn: (ctx: OutcomeParameterContext<TParams, TState>) => Record<string, OutcomeToolParameterSpec>,
909
+ ): this {
910
+ this.parameterResolver = fn;
911
+ return this;
912
+ }
913
+
878
914
  private stateRouting:
879
915
  | {
880
- branches: Record<string, TurnId>;
916
+ branches: Record<string, TurnId | ProcessOutcomeBranchSpec>;
881
917
  choose: (
882
918
  input: FlowOutcomeEffectInput<
883
919
  TParams,
@@ -890,7 +926,7 @@ export class OutcomeToolBuilder<
890
926
 
891
927
  /** @public */
892
928
  routeByState(
893
- branches: Record<string, TurnId>,
929
+ branches: Record<string, TurnId | ProcessOutcomeBranchSpec>,
894
930
  choose: (
895
931
  input: FlowOutcomeEffectInput<TParams, TState, FlowLlmOutcomeEffectContext<TParams, TState>>,
896
932
  ) => MaybePromise<string>,
@@ -917,9 +953,9 @@ export class OutcomeToolBuilder<
917
953
  ...(stateRouting
918
954
  ? {
919
955
  branches: Object.fromEntries(
920
- Object.entries(stateRouting.branches).map(([branchId, turnId]) => [
956
+ Object.entries(stateRouting.branches).map(([branchId, branch]) => [
921
957
  branchId,
922
- { to: turnId },
958
+ typeof branch === "string" ? { to: branch } : { ...branch },
923
959
  ]),
924
960
  ),
925
961
  choose: wrapOutcomeCallback((input) => stateRouting.choose(input)),
@@ -991,29 +1027,34 @@ export class PlanResultBuilder<TParams = unknown, TState = unknown> extends Rout
991
1027
  /** @internal */
992
1028
  summary(options: string | PlanFieldOptions = {}): this {
993
1029
  const resolved = typeof options === "string" ? { description: options } : options;
994
- this.summarySpec = textField({
1030
+ this.summarySpec = {
1031
+ type: "string",
995
1032
  description: resolved.description ?? "Short summary of the proposed plan",
1033
+ required: true,
996
1034
  requiredErrorCode: resolved.requiredErrorCode ?? "summary_required",
997
- });
1035
+ };
998
1036
  return this;
999
1037
  }
1000
1038
 
1001
1039
  /** @internal */
1002
1040
  acceptanceCriteria(options: string | PlanAcceptanceCriteriaOptions = {}): this {
1003
1041
  const resolved = typeof options === "string" ? { description: options } : options;
1004
- this.acceptanceCriteriaSpec = stringArrayField({
1042
+ this.acceptanceCriteriaSpec = {
1043
+ type: "array",
1005
1044
  description: resolved.description ?? "Acceptance criteria for the requested change",
1045
+ items: { type: "string" },
1046
+ required: true,
1006
1047
  requiredErrorCode: resolved.requiredErrorCode ?? "acceptance_criteria_required",
1007
1048
  minItems: resolved.minItems ?? 1,
1008
1049
  minItemsErrorCode: resolved.minItemsErrorCode ?? "acceptance_criteria_required",
1009
- });
1050
+ };
1010
1051
  return this;
1011
1052
  }
1012
1053
 
1013
1054
  /** @internal */
1014
1055
  review(turnId: TurnId): this {
1015
1056
  this.reviewTurnId = turnId;
1016
- return this.setTarget({ kind: "to", turnId });
1057
+ return this.setTarget({ to: turnId });
1017
1058
  }
1018
1059
 
1019
1060
  /** @internal */
@@ -1035,26 +1076,45 @@ export class PlanResultBuilder<TParams = unknown, TState = unknown> extends Rout
1035
1076
  acceptanceCriteria: this.acceptanceCriteriaSpec,
1036
1077
  },
1037
1078
  to: this.reviewTurnId,
1038
- lifecycleIntent: {
1039
- kind: "save_plan_result",
1040
- summaryParam: "summary",
1041
- acceptanceCriteriaParam: "acceptanceCriteria",
1042
- planMarkdownParam: "planMarkdown",
1043
- emitEventType: DEFAULT_PLAN_RESULT_OUTCOME_ID,
1044
- broadcastType: "plan.updated",
1045
- ...(stateEffect ? { state: stateEffect } : {}),
1079
+ async effect(execution) {
1080
+ const plan = await stateEffect?.(execution);
1081
+ const planRevision = execution.ctx.process.planRevision + 1;
1082
+ const summary = trimString(execution.event.params.summary);
1083
+ const acceptanceCriteria = normalizeStringArray(execution.event.params.acceptanceCriteria);
1084
+ const planMarkdown =
1085
+ typeof execution.event.turnResultMarkdown === "string"
1086
+ ? execution.event.turnResultMarkdown
1087
+ : trimString(execution.event.params.planMarkdown);
1088
+ return {
1089
+ ...plan,
1090
+ processPatch: { ...plan?.processPatch, planRevision },
1091
+ broadcasts: [
1092
+ ...(plan?.broadcasts ?? []),
1093
+ {
1094
+ type: "plan.updated",
1095
+ payload: { planRevision, reviewState: "awaiting_approval", approved: false, summary },
1096
+ },
1097
+ ],
1098
+ emit: [
1099
+ ...(plan?.emit ?? []),
1100
+ {
1101
+ type: DEFAULT_PLAN_RESULT_OUTCOME_ID,
1102
+ data: { planRevision, summary, planMarkdown, acceptanceCriteria },
1103
+ },
1104
+ ],
1105
+ };
1046
1106
  },
1047
1107
  };
1048
1108
  }
1049
1109
  }
1050
1110
 
1051
1111
  /** @public */
1052
- abstract class TurnEndBuilder<TParams, TState>
1112
+ export class LlmTurnEndBuilder<TParams = unknown, TState = unknown>
1053
1113
  extends RouteAndEffectBuilder<TParams, TState, FlowLlmOutcomeEffectContext<TParams, TState>>
1054
1114
  implements FlowLlmTurn<TParams, TState, string>
1055
1115
  {
1056
1116
  /** @internal */
1057
- protected abstract readonly builderName: string;
1117
+ protected readonly builderName: string = "LLM turn end";
1058
1118
 
1059
1119
  /** @internal */
1060
1120
  constructor(
@@ -1062,6 +1122,7 @@ abstract class TurnEndBuilder<TParams, TState>
1062
1122
  private readonly parent?: FlowLlmTurn<TParams, TState, string>,
1063
1123
  ) {
1064
1124
  super();
1125
+ if (outcomeId.trim() === "") throw new Error("LLM turn end outcome must be non-empty");
1065
1126
  }
1066
1127
 
1067
1128
  private get turn(): FlowLlmTurn<TParams, TState, string> {
@@ -1080,7 +1141,7 @@ abstract class TurnEndBuilder<TParams, TState>
1080
1141
  }
1081
1142
 
1082
1143
  /** @internal */
1083
- protected buildResult(): ProcessTurnEndSpec<TParams, TState, string> {
1144
+ build(): ProcessTurnEndSpec<TParams, TState, string> {
1084
1145
  const effect = this.flowEffect ? wrapOutcomeCallback(this.flowEffect) : undefined;
1085
1146
  return {
1086
1147
  outcome: this.outcomeId,
@@ -1091,44 +1152,19 @@ abstract class TurnEndBuilder<TParams, TState>
1091
1152
  }
1092
1153
 
1093
1154
  /** @public */
1094
- export class PublishedResultBuilder<TParams = unknown, TState = unknown> extends TurnEndBuilder<
1155
+ export class PublishedResultBuilder<TParams = unknown, TState = unknown> extends LlmTurnEndBuilder<
1095
1156
  TParams,
1096
1157
  TState
1097
1158
  > {
1098
1159
  /** @internal */
1099
- protected readonly builderName = "Published result";
1160
+ protected override readonly builderName = "Published result";
1100
1161
 
1101
1162
  /** @internal */
1102
1163
  buildTurnEnd(): ProcessTurnEndSpec<TParams, TState, string> {
1103
- return this.buildResult();
1104
- }
1105
- }
1106
-
1107
- /** @public */
1108
- export class LlmTurnEndBuilder<TParams = unknown, TState = unknown> extends TurnEndBuilder<
1109
- TParams,
1110
- TState
1111
- > {
1112
- /** @internal */
1113
- protected readonly builderName = "LLM turn end";
1114
-
1115
- /** @internal */
1116
- constructor(outcomeId: string, parent?: FlowLlmTurn<TParams, TState, string>) {
1117
- super(outcomeId, parent);
1118
- if (outcomeId.trim() === "") throw new Error("LLM turn end outcome must be non-empty");
1119
- }
1120
-
1121
- /** @internal */
1122
- build(): ProcessTurnEndSpec<TParams, TState, string> {
1123
- return this.buildResult();
1164
+ return this.build();
1124
1165
  }
1125
1166
  }
1126
1167
 
1127
- /** @public */
1128
- type LlmPromptBuilder<TParams, TState, TConsumedProducts extends string, TPrepared> = (
1129
- ctx: FlowPromptContext<TParams, TState, TConsumedProducts, TPrepared>,
1130
- ) => MaybePromise<string>;
1131
-
1132
1168
  /** @public */
1133
1169
  abstract class DescribedTurnBuilder {
1134
1170
  /** @internal */
@@ -1152,220 +1188,258 @@ abstract class DescribedTurnBuilder {
1152
1188
  }
1153
1189
  }
1154
1190
 
1191
+ type StoredExternalActionBuilder<TParams, TState> = ExternalActionBuilder<
1192
+ TParams,
1193
+ TState,
1194
+ unknown,
1195
+ Record<string, unknown>
1196
+ >;
1197
+
1155
1198
  /** @public */
1156
- export class LlmFlowBuilder<
1157
- TParams = unknown,
1158
- TState = unknown,
1159
- TConsumedProducts extends string = never,
1160
- TPrepared = undefined,
1161
- >
1162
- extends DescribedTurnBuilder
1163
- implements FlowLlmTurn<TParams, TState, string>
1164
- {
1165
- private modelPurposeValue: LlmModelPurpose | undefined;
1166
- private availableTools: readonly PiBuiltInToolName[] = [];
1167
- private availableIntegrationTools: readonly string[] = [];
1168
- private integrationToolResolver:
1169
- | ((params: TParams, state: TState) => readonly string[])
1170
- | undefined;
1171
- private preparation:
1172
- | ((ctx: FlowLlmPreparationContext<TParams, TState>) => MaybePromise<unknown>)
1173
- | null = null;
1174
- private promptBuilder:
1175
- | ((ctx: ProcessRuntimeTurnContext<TParams, TState>) => MaybePromise<string>)
1176
- | null = null;
1177
- private branchType: LlmTurnDefinition<string, TParams, TState>["branchType"] = "primary";
1178
- private context: LlmTurnDefinition<string, TParams, TState>["context"] = "fresh";
1179
- private questionsEnabled = false;
1180
- private startFrom: LlmTurnDefinition<string, TParams, TState>["startFrom"] | undefined;
1181
- private restorePrimaryLeafAfterTurn: boolean | undefined;
1182
- private readonly consumedProductNames = new Set<string>();
1183
- private readonly optionalConsumedProductNames = new Set<string>();
1184
- private publishedResult: {
1185
- productName: string;
1186
- builder: PublishedResultBuilder<TParams, TState>;
1187
- } | null = null;
1188
- private endResult: LlmTurnEndBuilder<TParams, TState> | null = null;
1189
- private outcomeToolBuilders = new Map<string, OutcomeToolBuilder<TParams, TState>>();
1190
- private mapped: {
1191
- options: FlowForEachOptions<TParams, TState, unknown, unknown>;
1192
- yields: Map<string, MappedItemYield<TParams, TState, unknown, unknown>>;
1193
- collect?: MappedCollect<TParams, TState, unknown>;
1194
- routing?: MappedCollectRouting<TParams, TState>;
1195
- } | null = null;
1196
-
1199
+ abstract class ExternalActionTurnBuilder<TParams, TState> extends DescribedTurnBuilder {
1197
1200
  /** @internal */
1198
- get definition(): LlmTurnDefinition<string, TParams, TState> {
1199
- return this.buildDefinition();
1200
- }
1201
+ protected abstract readonly turnKind: "LLM" | "Automatic" | "Human";
1202
+ private externalActionBuilders = new Map<string, StoredExternalActionBuilder<TParams, TState>>();
1201
1203
 
1202
- /**
1203
- * Run this turn once per frozen item. Items run sequentially; each item's
1204
- * outcome yields a typed result, and `collect` updates state and routes once.
1205
- * @public
1206
- */
1207
- forEach<TItem, TResult>(
1208
- options: FlowForEachOptions<TParams, TState, TItem, TResult>,
1209
- ): MappedLlmFlowBuilder<TParams, TState, TItem, TResult, TConsumedProducts, TPrepared> {
1210
- if (this.mapped) {
1211
- throw new Error(`LLM turn '${this.turnId}' declares .forEach(...) more than once`);
1212
- }
1213
- if (this.outcomeToolBuilders.size > 0 || this.publishedResult || this.endResult) {
1204
+ /** @public */
1205
+ externalAction<
1206
+ TEvent = unknown,
1207
+ TInput extends Record<string, unknown> = Record<string, unknown>,
1208
+ >(
1209
+ externalActionId: string,
1210
+ source: ExternalActionSource<TParams, TState, TEvent, TInput>,
1211
+ configure: (
1212
+ external: ExternalActionBuilder<TParams, TState, TEvent, TInput>,
1213
+ ) => ExternalActionBuilder<TParams, TState, TEvent, TInput> | undefined,
1214
+ ): this {
1215
+ if (this.externalActionBuilders.has(externalActionId)) {
1214
1216
  throw new Error(
1215
- `LLM turn '${this.turnId}' must declare .forEach(...) before its completion path`,
1217
+ `${this.turnKind} turn '${this.turnId}' declares duplicate external action '${externalActionId}'`,
1216
1218
  );
1217
1219
  }
1218
- this.mapped = {
1219
- options: options as FlowForEachOptions<TParams, TState, unknown, unknown>,
1220
- yields: new Map(),
1221
- };
1222
- return new MappedLlmFlowBuilder<TParams, TState, TItem, TResult, TConsumedProducts, TPrepared>(
1223
- this,
1220
+ const builder = new ExternalActionBuilder(externalActionId, source);
1221
+ configure(builder);
1222
+ this.externalActionBuilders.set(
1223
+ externalActionId,
1224
+ builder as unknown as StoredExternalActionBuilder<TParams, TState>,
1224
1225
  );
1226
+ return this;
1225
1227
  }
1226
1228
 
1227
1229
  /** @internal */
1228
- addMappedOutcome(
1229
- id: string,
1230
- builder: OutcomeToolBuilder<TParams, TState>,
1231
- yieldResult: MappedItemYield<TParams, TState, unknown, unknown>,
1232
- ): void {
1233
- if (!this.mapped) throw new Error(`LLM turn '${this.turnId}' is not mapped`);
1234
- if (id.trim() === "") {
1235
- throw new Error(`LLM turn '${this.turnId}' declares an empty outcome tool id`);
1236
- }
1237
- if (this.outcomeToolBuilders.has(id)) {
1238
- throw new Error(`LLM turn '${this.turnId}' declares duplicate outcome tool '${id}'`);
1239
- }
1240
- this.outcomeToolBuilders.set(id, builder);
1241
- this.mapped.yields.set(id, yieldResult);
1230
+ protected buildExternalActions():
1231
+ | Record<string, ProcessHumanTurnExternalActionSpec<TParams, TState>>
1232
+ | undefined {
1233
+ return this.externalActionBuilders.size > 0
1234
+ ? buildSpecs(this.externalActionBuilders)
1235
+ : undefined;
1242
1236
  }
1237
+ }
1243
1238
 
1244
- /** @internal */
1245
- setMappedCollect(collect: MappedCollect<TParams, TState, unknown>): void {
1246
- if (!this.mapped) throw new Error(`LLM turn '${this.turnId}' is not mapped`);
1247
- if (this.mapped.collect) {
1248
- throw new Error(`Mapped turn '${this.turnId}' declares .collect(...) more than once`);
1239
+ function buildSpecs<T>(builders: ReadonlyMap<string, { build(): T }>): Record<string, T> {
1240
+ return Object.fromEntries([...builders].map(([id, builder]) => [id, builder.build()]));
1241
+ }
1242
+
1243
+ function assertLlmOutcomeParameters<TParams, TState>(
1244
+ turnId: TurnId,
1245
+ outcomes: Record<string, ProcessToolOutcomeSpec<TParams, TState>>,
1246
+ ): void {
1247
+ for (const [outcomeId, outcome] of Object.entries(outcomes)) {
1248
+ if (OUTCOME_TOOL_MARKDOWN_PARAMETER_NAME in outcome.parameters) {
1249
+ throw new Error(
1250
+ `LLM turn '${turnId}' outcome tool '${outcomeId}' cannot declare reserved markdown parameter '${OUTCOME_TOOL_MARKDOWN_PARAMETER_NAME}'`,
1251
+ );
1249
1252
  }
1250
- this.mapped.collect = collect;
1251
1253
  }
1254
+ }
1255
+
1256
+ /** LLM authoring families used to preserve fluent context and completion types. @public */
1257
+ type LlmBuilderFamily =
1258
+ | {
1259
+ /** @public */
1260
+ kind: "ordinary";
1261
+ }
1262
+ | {
1263
+ /** @public */
1264
+ kind: "mapped";
1265
+ /** @public */
1266
+ item: unknown;
1267
+ /** @public */
1268
+ result: unknown;
1269
+ };
1270
+
1271
+ /** Active-item context supplied by an LLM authoring family. @public */
1272
+ type LlmItemContext<TFamily extends LlmBuilderFamily> = TFamily extends {
1273
+ kind: "mapped";
1274
+ item: infer TItem;
1275
+ }
1276
+ ? MappedTurnItemContext<TItem>
1277
+ : Record<never, never>;
1252
1278
 
1279
+ /** Preserve the concrete completion API when preparation or products refine its types. @public */
1280
+ type ConfiguredLlmBuilder<
1281
+ TFamily extends LlmBuilderFamily,
1282
+ TParams,
1283
+ TState,
1284
+ TConsumedProducts extends string,
1285
+ TPrepared,
1286
+ > = TFamily extends { kind: "mapped"; item: infer TItem; result: infer TResult }
1287
+ ? MappedLlmFlowBuilder<TParams, TState, TItem, TResult, TConsumedProducts, TPrepared>
1288
+ : LlmFlowBuilder<TParams, TState, TConsumedProducts, TPrepared>;
1289
+
1290
+ /** @public */
1291
+ abstract class LlmConfigurationBuilder<
1292
+ TParams,
1293
+ TState,
1294
+ TConsumedProducts extends string,
1295
+ TPrepared,
1296
+ TFamily extends LlmBuilderFamily,
1297
+ > extends ExternalActionTurnBuilder<TParams, TState> {
1253
1298
  /** @internal */
1254
- setMappedRouting(routing: MappedCollectRouting<TParams, TState>): void {
1255
- if (!this.mapped) throw new Error(`LLM turn '${this.turnId}' is not mapped`);
1256
- if (this.mapped.routing) {
1257
- throw new Error(`Mapped turn '${this.turnId}' collection already declares a route`);
1258
- }
1259
- this.mapped.routing = routing;
1299
+ protected readonly turnKind = "LLM";
1300
+ private readonly configuration: Omit<
1301
+ LlmTurnDefinition<string, TParams, TState>,
1302
+ "kind" | "description" | "prompt" | "outcomes" | "turnEnd" | "forEach"
1303
+ > = { availableTools: [], branchType: "primary", context: "fresh", completionMode: "turn_end" };
1304
+
1305
+ /** Wait on the server before this turn may allocate a worker. @public */
1306
+ waitFor(predicate: TurnWaitPredicate<TParams, TState>): this {
1307
+ if (this.configuration.waitFor)
1308
+ throw new Error(`Turn '${this.turnId}' already declares .waitFor(...)`);
1309
+ this.configuration.waitFor = predicate;
1310
+ return this;
1260
1311
  }
1312
+ private promptBuilder:
1313
+ | ((ctx: ProcessRuntimeTurnContext<TParams, TState>) => MaybePromise<string>)
1314
+ | null = null;
1315
+ private readonly consumedProductNames = new Set<string>();
1316
+ private readonly optionalConsumedProductNames = new Set<string>();
1261
1317
 
1262
- private mappedItemContext(
1318
+ /** @internal */
1319
+ protected abstract itemContext(
1263
1320
  ctx: ProcessRuntimeTurnContext<TParams, TState>,
1264
- ): Partial<MappedTurnItemContext<unknown>> {
1265
- if (!this.mapped) return {};
1266
- const iteration = ctx.iteration;
1267
- if (!iteration) {
1268
- throw new Error(`Mapped turn '${this.turnId}' requires an active item`);
1269
- }
1270
- return {
1271
- item: this.mapped.options.itemCodec.parse(iteration.item),
1272
- itemKey: iteration.itemKey,
1273
- itemLabel: iteration.itemLabel,
1274
- itemIndex: iteration.itemIndex,
1275
- itemCount: iteration.itemCount,
1276
- };
1277
- }
1321
+ ): LlmItemContext<TFamily>;
1278
1322
 
1279
- private buildMappedSpec(): MappedLlmTurnSpec<TParams, TState> | undefined {
1280
- if (!this.mapped) return undefined;
1281
- if (!this.mapped.collect) {
1282
- throw new Error(`Mapped turn '${this.turnId}' must declare .collect(...)`);
1283
- }
1284
- if (!this.mapped.routing) {
1285
- throw new Error(`Mapped turn '${this.turnId}' must declare a collection route`);
1286
- }
1287
- return {
1288
- ...this.mapped.options,
1289
- yields: Object.fromEntries(this.mapped.yields),
1290
- collect: this.mapped.collect,
1291
- routing: this.mapped.routing,
1292
- };
1323
+ /** @public */
1324
+ executionPurpose(purpose: string): this {
1325
+ if (purpose) this.configuration.executionPurpose = purpose;
1326
+ else delete this.configuration.executionPurpose;
1327
+ return this;
1293
1328
  }
1294
1329
 
1295
1330
  /** @internal */
1296
1331
  modelPurpose(purpose: LlmModelPurpose): this {
1297
- this.modelPurposeValue = purpose;
1332
+ this.configuration.modelPurpose = purpose;
1298
1333
  return this;
1299
1334
  }
1300
1335
 
1301
1336
  /** @public */
1302
1337
  tools(...tools: readonly PiBuiltInToolName[]): this {
1303
- this.availableTools = tools;
1338
+ this.configuration.availableTools = tools;
1304
1339
  return this;
1305
1340
  }
1306
1341
 
1307
1342
  /** @public */
1308
1343
  integrationTools(...tools: readonly string[]): this {
1309
- this.availableIntegrationTools = tools.map((tool) => tool.trim());
1344
+ if (tools.length) this.configuration.integrationTools = tools.map((tool) => tool.trim());
1345
+ else delete this.configuration.integrationTools;
1310
1346
  return this;
1311
1347
  }
1312
1348
 
1313
1349
  /** @public */
1314
1350
  resolveIntegrationTools(resolver: (params: TParams, state: TState) => readonly string[]): this {
1315
- this.integrationToolResolver = resolver;
1351
+ this.configuration.resolveIntegrationTools = resolver;
1316
1352
  return this;
1317
1353
  }
1318
1354
 
1319
1355
  /** @public */
1320
1356
  prepare<TNextPrepared>(
1321
- fn: (ctx: FlowLlmPreparationContext<TParams, TState>) => MaybePromise<TNextPrepared>,
1322
- ): LlmFlowBuilder<TParams, TState, TConsumedProducts, TNextPrepared> {
1323
- this.preparation = fn;
1324
- return this as unknown as LlmFlowBuilder<TParams, TState, TConsumedProducts, TNextPrepared>;
1357
+ fn: (
1358
+ ctx: FlowLlmPreparationContext<TParams, TState> & LlmItemContext<TFamily>,
1359
+ ) => MaybePromise<TNextPrepared>,
1360
+ ): ConfiguredLlmBuilder<TFamily, TParams, TState, TConsumedProducts, TNextPrepared> {
1361
+ this.configuration.prepare = (ctx) =>
1362
+ fn({ ...createFlowAutomaticRunContext(ctx), ...this.itemContext(ctx) });
1363
+ return this.refineContext<TConsumedProducts, TNextPrepared>();
1364
+ }
1365
+
1366
+ /** Return correction errors before accepting an outcome. @public */
1367
+ validateOutcome(
1368
+ fn: (
1369
+ ctx: FlowOutcomeValidationContext<TParams, TState> & LlmItemContext<TFamily>,
1370
+ outcome: LlmOutcomeSubmission,
1371
+ ) => MaybePromise<readonly string[]>,
1372
+ ): this {
1373
+ this.configuration.validateOutcome = (ctx, outcome) =>
1374
+ fn(
1375
+ {
1376
+ ...createFlowAutomaticRunContext(ctx),
1377
+ ...this.itemContext(ctx),
1378
+ prepared: ctx.prepared,
1379
+ },
1380
+ outcome,
1381
+ );
1382
+ return this;
1325
1383
  }
1326
1384
 
1327
- /** Enable durable operator questions for this LLM turn. @public */
1328
- askQuestions(): this {
1329
- this.questionsEnabled = true;
1385
+ /** Enable durable questions, optionally constrained by captured input. @public */
1386
+ askQuestions(
1387
+ when?: (
1388
+ ctx: FlowPromptContext<TParams, TState, TConsumedProducts, TPrepared> &
1389
+ LlmItemContext<TFamily>,
1390
+ ) => boolean,
1391
+ ): this {
1392
+ this.configuration.askQuestions = true;
1393
+ this.configuration.resolveAskQuestions = when
1394
+ ? (ctx) =>
1395
+ when({
1396
+ ...createFlowPromptContext<TParams, TState, TConsumedProducts, TPrepared>(
1397
+ ctx,
1398
+ [...this.consumedProductNames] as TConsumedProducts[],
1399
+ [...this.optionalConsumedProductNames],
1400
+ ),
1401
+ ...this.itemContext(ctx),
1402
+ })
1403
+ : undefined;
1330
1404
  return this;
1331
1405
  }
1332
1406
 
1333
1407
  /** @public */
1334
1408
  freshPrimary(): this {
1335
- this.branchType = "primary";
1336
- this.context = "fresh";
1337
- this.startFrom = undefined;
1338
- this.restorePrimaryLeafAfterTurn = undefined;
1409
+ this.configuration.branchType = "primary";
1410
+ this.configuration.context = "fresh";
1411
+ delete this.configuration.startFrom;
1412
+ delete this.configuration.restorePrimaryLeafAfterTurn;
1339
1413
  return this;
1340
1414
  }
1341
1415
 
1342
1416
  /** @internal */
1343
1417
  freshSeededPrimary(): this {
1344
- this.branchType = "primary";
1345
- this.context = "fresh_seeded";
1346
- this.startFrom = undefined;
1347
- this.restorePrimaryLeafAfterTurn = undefined;
1418
+ this.configuration.branchType = "primary";
1419
+ this.configuration.context = "fresh_seeded";
1420
+ delete this.configuration.startFrom;
1421
+ delete this.configuration.restorePrimaryLeafAfterTurn;
1348
1422
  return this;
1349
1423
  }
1350
1424
 
1351
1425
  /** @public */
1352
1426
  fullPrimary(): this {
1353
- this.branchType = "primary";
1354
- this.context = "full";
1427
+ this.configuration.branchType = "primary";
1428
+ this.configuration.context = "full";
1355
1429
  return this;
1356
1430
  }
1357
1431
 
1358
1432
  /** @internal */
1359
1433
  rootBranchReview(): this {
1360
- this.branchType = "root_branch";
1361
- this.context = "full";
1362
- this.restorePrimaryLeafAfterTurn = true;
1434
+ this.configuration.branchType = "root_branch";
1435
+ this.configuration.context = "full";
1436
+ this.configuration.restorePrimaryLeafAfterTurn = true;
1363
1437
  return this;
1364
1438
  }
1365
1439
 
1366
1440
  /** @public */
1367
1441
  continueFromPrimaryLeaf(): this {
1368
- this.startFrom = {
1442
+ this.configuration.startFrom = {
1369
1443
  kind: "semantic_ref",
1370
1444
  ref: "currentPrimaryPathLeaf",
1371
1445
  fallback: { kind: "current_leaf" },
@@ -1375,7 +1449,7 @@ export class LlmFlowBuilder<
1375
1449
 
1376
1450
  /** @internal */
1377
1451
  continueFromReviewBranch(): this {
1378
- this.startFrom = {
1452
+ this.configuration.startFrom = {
1379
1453
  kind: "semantic_ref",
1380
1454
  ref: "review",
1381
1455
  fallback: { kind: "current_leaf" },
@@ -1393,7 +1467,7 @@ export class LlmFlowBuilder<
1393
1467
 
1394
1468
  /** @internal */
1395
1469
  startFromReviewBranch(): this {
1396
- this.startFrom = {
1470
+ this.configuration.startFrom = {
1397
1471
  kind: "semantic_ref",
1398
1472
  ref: "review",
1399
1473
  fallback: { kind: "session_root" },
@@ -1406,7 +1480,7 @@ export class LlmFlowBuilder<
1406
1480
  productName: string,
1407
1481
  fallback: ProcessTurnStartSelection = { kind: "session_root" },
1408
1482
  ): this {
1409
- this.startFrom = {
1483
+ this.configuration.startFrom = {
1410
1484
  kind: "product_ref",
1411
1485
  productName: normalizeProductName(productName),
1412
1486
  fallback,
@@ -1416,39 +1490,126 @@ export class LlmFlowBuilder<
1416
1490
 
1417
1491
  /** @internal */
1418
1492
  startFromRoot(): this {
1419
- this.startFrom = { kind: "session_root" };
1493
+ this.configuration.startFrom = { kind: "session_root" };
1420
1494
  return this;
1421
1495
  }
1422
1496
 
1423
1497
  /** @public */
1424
1498
  consume<TProductName extends string>(
1425
1499
  productName: TProductName,
1426
- ): LlmFlowBuilder<TParams, TState, TConsumedProducts | TProductName, TPrepared> {
1500
+ ): ConfiguredLlmBuilder<TFamily, TParams, TState, TConsumedProducts | TProductName, TPrepared> {
1427
1501
  this.consumedProductNames.add(normalizeProductName(productName));
1428
- return this as unknown as LlmFlowBuilder<
1429
- TParams,
1430
- TState,
1431
- TConsumedProducts | TProductName,
1432
- TPrepared
1433
- >;
1502
+ return this.refineContext<TConsumedProducts | TProductName, TPrepared>();
1434
1503
  }
1435
1504
 
1436
1505
  /** @public */
1437
1506
  optionalConsume<TProductName extends string>(
1438
1507
  productName: TProductName,
1439
- ): LlmFlowBuilder<TParams, TState, TConsumedProducts | TProductName, TPrepared> {
1508
+ ): ConfiguredLlmBuilder<TFamily, TParams, TState, TConsumedProducts | TProductName, TPrepared> {
1440
1509
  this.optionalConsumedProductNames.add(normalizeProductName(productName));
1441
- return this as unknown as LlmFlowBuilder<
1510
+ return this.refineContext<TConsumedProducts | TProductName, TPrepared>();
1511
+ }
1512
+
1513
+ private refineContext<
1514
+ TNextConsumedProducts extends string,
1515
+ TNextPrepared,
1516
+ >(): ConfiguredLlmBuilder<TFamily, TParams, TState, TNextConsumedProducts, TNextPrepared> {
1517
+ // Fluent configuration mutates this builder; only its context type changes.
1518
+ return this as unknown as ConfiguredLlmBuilder<
1519
+ TFamily,
1442
1520
  TParams,
1443
1521
  TState,
1444
- TConsumedProducts | TProductName,
1445
- TPrepared
1522
+ TNextConsumedProducts,
1523
+ TNextPrepared
1446
1524
  >;
1447
1525
  }
1448
1526
 
1527
+ /** @public */
1528
+ buildPrompt(
1529
+ fn: (
1530
+ ctx: FlowPromptContext<TParams, TState, TConsumedProducts, TPrepared> &
1531
+ LlmItemContext<TFamily>,
1532
+ ) => MaybePromise<string>,
1533
+ ): this {
1534
+ this.promptBuilder = (ctx) =>
1535
+ fn({
1536
+ ...createFlowPromptContext<TParams, TState, TConsumedProducts, TPrepared>(
1537
+ ctx,
1538
+ [...this.consumedProductNames] as TConsumedProducts[],
1539
+ [...this.optionalConsumedProductNames],
1540
+ ),
1541
+ ...this.itemContext(ctx),
1542
+ });
1543
+ return this;
1544
+ }
1545
+
1546
+ /** @public */
1547
+ prompt(
1548
+ prompt: string | ((ctx: ProcessRuntimeTurnContext<TParams, TState>) => MaybePromise<string>),
1549
+ ): this {
1550
+ this.promptBuilder = typeof prompt === "string" ? () => prompt : prompt;
1551
+ return this;
1552
+ }
1553
+
1554
+ /** @internal */
1555
+ protected buildBaseDefinition(): Omit<
1556
+ LlmTurnDefinition<string, TParams, TState>,
1557
+ "outcomes" | "turnEnd" | "forEach"
1558
+ > {
1559
+ if (!this.turnDescription) {
1560
+ throw new Error(`LLM turn '${this.turnId}' must declare .description(...)`);
1561
+ }
1562
+ const prompt = this.promptBuilder;
1563
+ if (!prompt) {
1564
+ throw new Error(`LLM turn '${this.turnId}' must declare .buildPrompt(...)`);
1565
+ }
1566
+ const externalActions = this.buildExternalActions();
1567
+ return {
1568
+ ...this.configuration,
1569
+ ...(externalActions ? { externalActions } : {}),
1570
+ kind: "llm",
1571
+ description: this.turnDescription,
1572
+ prompt,
1573
+ ...(this.consumedProductNames.size > 0
1574
+ ? { consumedProducts: [...this.consumedProductNames] }
1575
+ : {}),
1576
+ ...(this.optionalConsumedProductNames.size > 0
1577
+ ? { optionalConsumedProducts: [...this.optionalConsumedProductNames] }
1578
+ : {}),
1579
+ };
1580
+ }
1581
+ }
1582
+
1583
+ /** @public */
1584
+ export class LlmFlowBuilder<
1585
+ TParams = unknown,
1586
+ TState = unknown,
1587
+ TConsumedProducts extends string = never,
1588
+ TPrepared = undefined,
1589
+ >
1590
+ extends LlmConfigurationBuilder<
1591
+ TParams,
1592
+ TState,
1593
+ TConsumedProducts,
1594
+ TPrepared,
1595
+ { kind: "ordinary" }
1596
+ >
1597
+ implements FlowLlmTurn<TParams, TState, string>
1598
+ {
1599
+ private publishedResult: {
1600
+ productName: string;
1601
+ builder: PublishedResultBuilder<TParams, TState>;
1602
+ } | null = null;
1603
+ private endResult: LlmTurnEndBuilder<TParams, TState> | null = null;
1604
+ private outcomeToolBuilders = new Map<string, OutcomeToolBuilder<TParams, TState>>();
1605
+
1606
+ /** @internal */
1607
+ protected itemContext(): Record<never, never> {
1608
+ return {};
1609
+ }
1610
+
1449
1611
  /** @public */
1450
1612
  publish(productName: string): PublishedResultBuilder<TParams, TState> {
1451
- this.assertNotMapped(".publish(...)");
1452
1613
  const normalized = normalizeProductName(productName);
1453
1614
  if (this.publishedResult) {
1454
1615
  throw new Error(`LLM turn '${this.turnId}' can publish only one product in flow v1`);
@@ -1463,7 +1624,6 @@ export class LlmFlowBuilder<
1463
1624
 
1464
1625
  /** @public */
1465
1626
  end(outcomeId: string): LlmTurnEndBuilder<TParams, TState> {
1466
- this.assertNotMapped(".end(...)");
1467
1627
  if (this.endResult) {
1468
1628
  throw new Error(`LLM turn '${this.turnId}' declares duplicate .end(...) completion`);
1469
1629
  }
@@ -1477,34 +1637,6 @@ export class LlmFlowBuilder<
1477
1637
  return this.endResult;
1478
1638
  }
1479
1639
 
1480
- /** @public */
1481
- buildPrompt(fn: LlmPromptBuilder<TParams, TState, TConsumedProducts, TPrepared>): this {
1482
- this.promptBuilder = (ctx) =>
1483
- fn({
1484
- ...createFlowPromptContext<TParams, TState, TConsumedProducts, TPrepared>(
1485
- ctx,
1486
- [...this.consumedProductNames] as TConsumedProducts[],
1487
- [...this.optionalConsumedProductNames],
1488
- ),
1489
- ...this.mappedItemContext(ctx),
1490
- });
1491
- return this;
1492
- }
1493
-
1494
- private assertNotMapped(feature: string): void {
1495
- if (this.mapped) {
1496
- throw new Error(
1497
- `Mapped turn '${this.turnId}' cannot declare ${feature}; items yield results and .collect(...) routes`,
1498
- );
1499
- }
1500
- }
1501
-
1502
- /** @public */
1503
- prompt(prompt: (ctx: ProcessRuntimeTurnContext<TParams, TState>) => MaybePromise<string>): this {
1504
- this.promptBuilder = prompt;
1505
- return this;
1506
- }
1507
-
1508
1640
  /** @public */
1509
1641
  outcomeTool(
1510
1642
  id: string,
@@ -1512,7 +1644,6 @@ export class LlmFlowBuilder<
1512
1644
  tool: OutcomeToolBuilder<TParams, TState>,
1513
1645
  ) => OutcomeToolBuilder<TParams, TState> | undefined,
1514
1646
  ): this {
1515
- this.assertNotMapped("routed outcome tools");
1516
1647
  if (id.trim() === "") {
1517
1648
  throw new Error(`LLM turn '${this.turnId}' declares an empty outcome tool id`);
1518
1649
  }
@@ -1531,47 +1662,6 @@ export class LlmFlowBuilder<
1531
1662
  return this;
1532
1663
  }
1533
1664
 
1534
- private buildBaseDefinition() {
1535
- if (!this.turnDescription) {
1536
- throw new Error(`LLM turn '${this.turnId}' must declare .description(...)`);
1537
- }
1538
- const prompt = this.promptBuilder;
1539
- if (!prompt) {
1540
- throw new Error(`LLM turn '${this.turnId}' must declare .buildPrompt(...)`);
1541
- }
1542
- const preparation = this.preparation;
1543
- return {
1544
- kind: "llm" as const,
1545
- description: this.turnDescription,
1546
- ...(this.modelPurposeValue ? { modelPurpose: this.modelPurposeValue } : {}),
1547
- availableTools: this.availableTools,
1548
- ...(this.availableIntegrationTools.length > 0
1549
- ? { integrationTools: this.availableIntegrationTools }
1550
- : {}),
1551
- ...(this.integrationToolResolver
1552
- ? { resolveIntegrationTools: this.integrationToolResolver }
1553
- : {}),
1554
- ...(this.questionsEnabled ? { askQuestions: true as const } : {}),
1555
- ...(preparation
1556
- ? {
1557
- prepare: (ctx: ProcessRuntimeTurnContext<TParams, TState>) =>
1558
- preparation({
1559
- ...createFlowAutomaticRunContext(ctx),
1560
- ...this.mappedItemContext(ctx),
1561
- }),
1562
- }
1563
- : {}),
1564
- completionMode: "turn_end" as const,
1565
- branchType: this.branchType,
1566
- context: this.context,
1567
- ...(this.startFrom ? { startFrom: this.startFrom } : {}),
1568
- ...(this.restorePrimaryLeafAfterTurn !== undefined
1569
- ? { restorePrimaryLeafAfterTurn: this.restorePrimaryLeafAfterTurn }
1570
- : {}),
1571
- prompt,
1572
- };
1573
- }
1574
-
1575
1665
  /** @internal */
1576
1666
  producesPlan(
1577
1667
  configure: (plan: PlanResultBuilder<TParams, TState>) => PlanResultBuilder<TParams, TState>,
@@ -1593,22 +1683,20 @@ export class LlmFlowBuilder<
1593
1683
  };
1594
1684
  }
1595
1685
 
1596
- private buildDefinition(): LlmTurnDefinition<string, TParams, TState> {
1686
+ /** @internal */
1687
+ get definition(): LlmTurnDefinition<string, TParams, TState> {
1597
1688
  const definition = this.buildBaseDefinition();
1598
- const hasOutcomeTools = this.outcomeToolBuilders.size > 0;
1599
1689
  const explicitTurnEnd = this.endResult;
1600
1690
  const published = this.publishedResult;
1601
- const outcomes: Record<string, ProcessToolOutcomeSpec<TParams, TState>> = {};
1602
- for (const [outcomeId, builder] of this.outcomeToolBuilders) {
1603
- outcomes[outcomeId] = builder.build();
1604
- }
1691
+ const outcomes = buildSpecs(this.outcomeToolBuilders);
1692
+ const hasOutcomeTools = Object.keys(outcomes).length > 0;
1605
1693
  const outcomePublishedProducts = new Set(
1606
1694
  Object.values(outcomes)
1607
1695
  .map((outcome) => outcome.publishedProduct)
1608
1696
  .filter((productName): productName is string => typeof productName === "string"),
1609
1697
  );
1610
1698
  const hasOutcomePublishedProduct = outcomePublishedProducts.size > 0;
1611
- let turnEnd: ProcessTurnEndSpec<TParams, TState, string> | undefined;
1699
+ let turnEnd = explicitTurnEnd?.build();
1612
1700
  let resultSemanticRef: "plan" | "review" | undefined = outcomePublishedProducts.has("review")
1613
1701
  ? "review"
1614
1702
  : outcomePublishedProducts.has("plan")
@@ -1619,76 +1707,48 @@ export class LlmFlowBuilder<
1619
1707
 
1620
1708
  if (published) {
1621
1709
  publishedProduct = published.productName;
1622
- if (published.productName === "plan") {
1623
- resultSemanticRef = "plan";
1624
- }
1625
- if (published.productName === "review") {
1626
- resultSemanticRef = "review";
1710
+ if (published.productName === "plan" || published.productName === "review") {
1711
+ resultSemanticRef = published.productName;
1627
1712
  }
1628
1713
  const publishHasRoute = published.builder.hasRoute();
1629
- if (publishHasRoute && hasOutcomeTools) {
1630
- throw new Error(
1631
- `LLM turn '${this.turnId}' cannot route published product '${published.productName}' and declare outcome tools in flow v1`,
1632
- );
1633
- }
1634
- if (publishHasRoute && !hasOutcomeTools) {
1635
- turnResultMarkdown = ASSISTANT_OUTPUT_TURN_RESULT;
1636
- turnEnd = published.builder.buildTurnEnd();
1637
- }
1638
- if (!publishHasRoute && hasOutcomeTools) {
1639
- turnResultMarkdown = OUTCOME_TOOL_ARGUMENT_TURN_RESULT;
1640
- }
1641
- if (!publishHasRoute && !hasOutcomeTools) {
1714
+ if (publishHasRoute === hasOutcomeTools) {
1642
1715
  throw new Error(
1643
- `LLM turn '${this.turnId}' publishes product '${published.productName}' but declares no route or outcome tool completion path`,
1716
+ hasOutcomeTools
1717
+ ? `LLM turn '${this.turnId}' cannot route published product '${published.productName}' and declare outcome tools in flow v1`
1718
+ : `LLM turn '${this.turnId}' publishes product '${published.productName}' but declares no route or outcome tool completion path`,
1644
1719
  );
1645
1720
  }
1721
+ turnResultMarkdown = publishHasRoute
1722
+ ? ASSISTANT_OUTPUT_TURN_RESULT
1723
+ : OUTCOME_TOOL_ARGUMENT_TURN_RESULT;
1724
+ if (publishHasRoute) turnEnd = published.builder.buildTurnEnd();
1646
1725
  } else if (hasOutcomeTools && !hasOutcomePublishedProduct) {
1647
1726
  turnResultMarkdown = OUTCOME_TOOL_ARGUMENT_TURN_RESULT;
1648
1727
  } else if (explicitTurnEnd) {
1649
1728
  turnResultMarkdown = ASSISTANT_OUTPUT_TURN_RESULT;
1650
1729
  }
1651
1730
 
1652
- if (hasOutcomeTools) {
1653
- for (const [outcomeId, outcome] of Object.entries(outcomes)) {
1654
- if (OUTCOME_TOOL_MARKDOWN_PARAMETER_NAME in outcome.parameters) {
1655
- throw new Error(
1656
- `LLM turn '${this.turnId}' outcome tool '${outcomeId}' cannot declare reserved markdown parameter '${OUTCOME_TOOL_MARKDOWN_PARAMETER_NAME}'`,
1657
- );
1658
- }
1659
- }
1660
- }
1731
+ assertLlmOutcomeParameters(this.turnId, outcomes);
1661
1732
 
1662
- if (explicitTurnEnd) {
1663
- if (turnEnd || Object.keys(outcomes).length > 0) {
1664
- throw new Error(`LLM turn '${this.turnId}' cannot declare multiple completion paths`);
1665
- }
1666
- turnEnd = explicitTurnEnd.build();
1733
+ if (explicitTurnEnd && hasOutcomeTools) {
1734
+ throw new Error(`LLM turn '${this.turnId}' cannot declare multiple completion paths`);
1667
1735
  }
1668
- if (Object.keys(outcomes).length === 0 && !turnEnd) {
1736
+ if (!hasOutcomeTools && !turnEnd) {
1669
1737
  throw new Error(`LLM turn '${this.turnId}' must declare a completion path`);
1670
1738
  }
1671
- const forEach = this.buildMappedSpec();
1672
1739
 
1673
1740
  return {
1674
1741
  ...definition,
1675
- ...(forEach ? { forEach } : {}),
1676
- ...(Object.keys(outcomes).length > 0 ? { outcomes } : {}),
1742
+ ...(hasOutcomeTools ? { outcomes } : {}),
1677
1743
  ...(turnEnd ? { turnEnd } : {}),
1678
1744
  ...(turnResultMarkdown ? { turnResultMarkdown } : {}),
1679
1745
  ...(resultSemanticRef ? { resultSemanticRef } : {}),
1680
1746
  ...(publishedProduct ? { publishedProduct } : {}),
1681
- ...(this.consumedProductNames.size > 0
1682
- ? { consumedProducts: [...this.consumedProductNames] }
1683
- : {}),
1684
- ...(this.optionalConsumedProductNames.size > 0
1685
- ? { optionalConsumedProducts: [...this.optionalConsumedProductNames] }
1686
- : {}),
1687
1747
  };
1688
1748
  }
1689
1749
  }
1690
1750
 
1691
- /** Item selection for `flow.llm(...).forEach(...)`. @public */
1751
+ /** Item selection for `flow.mappedLlm(...)`. @public */
1692
1752
  export type FlowForEachOptions<TParams, TState, TItem, TResult> = Pick<
1693
1753
  MappedLlmTurnSpec<TParams, TState, TItem, TResult>,
1694
1754
  "items" | "itemCodec" | "resultCodec" | "key" | "label" | "stateAfterSnapshot"
@@ -1720,63 +1780,18 @@ export class MappedOutcomeBuilder<
1720
1780
  TState = unknown,
1721
1781
  TItem = unknown,
1722
1782
  TResult = unknown,
1723
- > {
1724
- private readonly tool = new OutcomeToolBuilder<TParams, TState>();
1725
- private yieldResult: MappedItemYield<TParams, TState, TItem, TResult> | null = null;
1726
-
1727
- /** @public */
1728
- description(text: string): this {
1729
- this.tool.description(text);
1730
- return this;
1731
- }
1732
-
1733
- /** @public */
1734
- resultSummary(name?: string): this {
1735
- this.tool.resultSummary(name);
1736
- return this;
1737
- }
1738
-
1739
- /** @public */
1740
- requiredString(name: string, options: string | ParameterOptions = {}): this {
1741
- this.tool.requiredString(name, options);
1742
- return this;
1743
- }
1744
-
1745
- /** @public */
1746
- string(name: string, options: string | ParameterOptions = {}): this {
1747
- this.tool.string(name, options);
1748
- return this;
1749
- }
1750
-
1751
- /** @public */
1752
- requiredNumber(name: string, options: string | ParameterOptions = {}): this {
1753
- this.tool.requiredNumber(name, options);
1754
- return this;
1755
- }
1756
-
1757
- /** @public */
1758
- requiredBoolean(name: string, options: string | ParameterOptions = {}): this {
1759
- this.tool.requiredBoolean(name, options);
1760
- return this;
1761
- }
1762
-
1763
- /** @public */
1764
- requiredStringArray(name: string, options: string | ArrayParameterOptions = {}): this {
1765
- this.tool.requiredStringArray(name, options);
1766
- return this;
1767
- }
1768
-
1769
- /** @public */
1770
- object(name: string, options: string | ParameterOptions = {}): this {
1771
- this.tool.object(name, options);
1772
- return this;
1773
- }
1774
-
1775
- /** @public */
1776
- requiredArray(name: string, options: string | ArrayParameterOptions = {}): this {
1777
- this.tool.requiredArray(name, options);
1783
+ > extends OutcomeParametersBuilder<TParams, TState> {
1784
+ /** Resolve parameters from captured state and the frozen mapped item. @public */
1785
+ resolveParameters(
1786
+ fn: (
1787
+ ctx: OutcomeParameterContext<TParams, TState> & MappedTurnItemContext<TItem>,
1788
+ ) => Record<string, OutcomeToolParameterSpec>,
1789
+ ): this {
1790
+ this.parameterResolver = (ctx) =>
1791
+ fn(ctx as OutcomeParameterContext<TParams, TState> & MappedTurnItemContext<TItem>);
1778
1792
  return this;
1779
1793
  }
1794
+ private yieldResult: MappedItemYield<TParams, TState, TItem, TResult> | null = null;
1780
1795
 
1781
1796
  /** Map this outcome to the item's typed result. @public */
1782
1797
  yield(fn: MappedItemYield<TParams, TState, TItem, TResult>): this {
@@ -1787,59 +1802,52 @@ export class MappedOutcomeBuilder<
1787
1802
  /** @internal */
1788
1803
  build(): {
1789
1804
  /** @internal */
1790
- tool: OutcomeToolBuilder<TParams, TState>;
1805
+ tool: ProcessToolOutcomeSpec<TParams, TState>;
1791
1806
  /** @internal */
1792
1807
  yieldResult: MappedItemYield<TParams, TState, TItem, TResult>;
1793
1808
  } {
1794
1809
  if (!this.yieldResult) {
1795
1810
  throw new Error("Mapped outcome must declare .yield(...)");
1796
1811
  }
1797
- return { tool: this.tool, yieldResult: this.yieldResult };
1812
+ return { tool: this.buildParameterSpec("Mapped outcome tool"), yieldResult: this.yieldResult };
1798
1813
  }
1799
1814
  }
1800
1815
 
1801
- /** @public */
1802
- abstract class MappedTurnFacade<TParams, TState> implements FlowLlmTurn<TParams, TState, string> {
1816
+ /** Routes a mapped turn once, after all item results are collected. @public */
1817
+ export class MappedCollectBuilder<TParams = unknown, TState = unknown>
1818
+ implements FlowLlmTurn<TParams, TState, string>
1819
+ {
1803
1820
  /** @internal */
1804
1821
  constructor(
1805
- /** @internal */
1806
- protected readonly base: LlmFlowBuilder<TParams, TState, string, unknown>,
1822
+ private readonly turn: FlowLlmTurn<TParams, TState, string>,
1823
+ private readonly setRouting: (routing: MappedCollectRouting<TParams, TState>) => void,
1807
1824
  ) {}
1808
1825
 
1809
1826
  /** @internal */
1810
1827
  get id(): TurnId {
1811
- return this.base.id;
1828
+ return this.turn.id;
1812
1829
  }
1813
1830
 
1814
1831
  /** @internal */
1815
1832
  get definition(): LlmTurnDefinition<string, TParams, TState> {
1816
- return this.base.definition;
1833
+ return this.turn.definition;
1817
1834
  }
1818
- }
1819
1835
 
1820
- /**
1821
- * Routes a mapped turn once, after all item results are collected.
1822
- * @public
1823
- */
1824
- export class MappedCollectBuilder<TParams = unknown, TState = unknown> extends MappedTurnFacade<
1825
- TParams,
1826
- TState
1827
- > {
1828
1836
  /** @public */
1829
1837
  to(turnId: TurnId): this {
1830
- this.base.setMappedRouting({ kind: "static", to: turnId });
1838
+ this.setRouting({ kind: "static", to: turnId });
1831
1839
  return this;
1832
1840
  }
1833
1841
 
1834
1842
  /** @public */
1835
1843
  complete(): this {
1836
- this.base.setMappedRouting({ kind: "static", lifecycleStatus: "completed" });
1844
+ this.setRouting({ kind: "static", lifecycleStatus: "completed" });
1837
1845
  return this;
1838
1846
  }
1839
1847
 
1840
1848
  /** @public */
1841
1849
  lifecycleStatus(status: ProcessTurnTerminalLifecycleStatus): this {
1842
- this.base.setMappedRouting({ kind: "static", lifecycleStatus: status });
1850
+ this.setRouting({ kind: "static", lifecycleStatus: status });
1843
1851
  return this;
1844
1852
  }
1845
1853
 
@@ -1851,7 +1859,7 @@ export class MappedCollectBuilder<TParams = unknown, TState = unknown> extends M
1851
1859
  if (Object.keys(branches).length === 0) {
1852
1860
  throw new Error("Mapped collection routing must declare at least one branch");
1853
1861
  }
1854
- this.base.setMappedRouting({ kind: "branches", branches: { ...branches }, choose });
1862
+ this.setRouting({ kind: "branches", branches: { ...branches }, choose });
1855
1863
  return this;
1856
1864
  }
1857
1865
  }
@@ -1862,97 +1870,52 @@ export class MappedCollectBuilder<TParams = unknown, TState = unknown> extends M
1862
1870
  * @public
1863
1871
  */
1864
1872
  export class MappedLlmFlowBuilder<
1865
- TParams = unknown,
1866
- TState = unknown,
1867
- TItem = unknown,
1868
- TResult = unknown,
1869
- TConsumedProducts extends string = never,
1870
- TPrepared = undefined,
1871
- > extends MappedTurnFacade<TParams, TState> {
1872
- /** @internal */
1873
- constructor(base: LlmFlowBuilder<TParams, TState, TConsumedProducts, TPrepared>) {
1874
- super(base as unknown as LlmFlowBuilder<TParams, TState, string, unknown>);
1875
- }
1876
-
1877
- /** @public */
1878
- description(description: string): this {
1879
- this.base.description(description);
1880
- return this;
1881
- }
1882
-
1883
- /** @public */
1884
- tools(...tools: readonly PiBuiltInToolName[]): this {
1885
- this.base.tools(...tools);
1886
- return this;
1887
- }
1888
-
1889
- /** @public */
1890
- integrationTools(...tools: readonly string[]): this {
1891
- this.base.integrationTools(...tools);
1892
- return this;
1893
- }
1894
-
1895
- /** @public */
1896
- freshPrimary(): this {
1897
- this.base.freshPrimary();
1898
- return this;
1899
- }
1900
-
1901
- /** @public */
1902
- consume<TProductName extends string>(
1903
- productName: TProductName,
1904
- ): MappedLlmFlowBuilder<
1873
+ TParams = unknown,
1874
+ TState = unknown,
1875
+ TItem = unknown,
1876
+ TResult = unknown,
1877
+ TConsumedProducts extends string = never,
1878
+ TPrepared = undefined,
1879
+ >
1880
+ extends LlmConfigurationBuilder<
1905
1881
  TParams,
1906
1882
  TState,
1907
- TItem,
1908
- TResult,
1909
- TConsumedProducts | TProductName,
1910
- TPrepared
1911
- > {
1912
- this.base.consume(productName);
1913
- return this as unknown as MappedLlmFlowBuilder<
1914
- TParams,
1915
- TState,
1916
- TItem,
1917
- TResult,
1918
- TConsumedProducts | TProductName,
1919
- TPrepared
1920
- >;
1921
- }
1883
+ TConsumedProducts,
1884
+ TPrepared,
1885
+ { kind: "mapped"; item: TItem; result: TResult }
1886
+ >
1887
+ implements FlowLlmTurn<TParams, TState, string>
1888
+ {
1889
+ private readonly outcomes = new Map<
1890
+ string,
1891
+ MappedOutcomeBuilder<TParams, TState, TItem, TResult>
1892
+ >();
1893
+ private collection: MappedCollect<TParams, TState, TResult> | undefined;
1894
+ private routing: MappedCollectRouting<TParams, TState> | undefined;
1922
1895
 
1923
- /** Deterministic worker preparation for the active item. @public */
1924
- prepare<TNextPrepared>(
1925
- fn: (ctx: FlowMappedPreparationContext<TParams, TState, TItem>) => MaybePromise<TNextPrepared>,
1926
- ): MappedLlmFlowBuilder<TParams, TState, TItem, TResult, TConsumedProducts, TNextPrepared> {
1927
- this.base.prepare((ctx) => fn(ctx as FlowMappedPreparationContext<TParams, TState, TItem>));
1928
- return this as unknown as MappedLlmFlowBuilder<
1929
- TParams,
1930
- TState,
1931
- TItem,
1932
- TResult,
1933
- TConsumedProducts,
1934
- TNextPrepared
1935
- >;
1896
+ /** @internal */
1897
+ constructor(
1898
+ turnId: TurnId,
1899
+ private readonly items: FlowForEachOptions<TParams, TState, TItem, TResult>,
1900
+ ) {
1901
+ super(turnId);
1936
1902
  }
1937
1903
 
1938
- /** Build the prompt for the active item. @public */
1939
- buildPrompt(
1940
- fn: (
1941
- ctx: FlowMappedPromptContext<TParams, TState, TItem, TConsumedProducts, TPrepared>,
1942
- ) => MaybePromise<string>,
1943
- ): this {
1944
- this.base.buildPrompt((ctx) =>
1945
- fn(
1946
- ctx as unknown as FlowMappedPromptContext<
1947
- TParams,
1948
- TState,
1949
- TItem,
1950
- TConsumedProducts,
1951
- TPrepared
1952
- >,
1953
- ),
1954
- );
1955
- return this;
1904
+ /** @internal */
1905
+ protected itemContext(
1906
+ ctx: ProcessRuntimeTurnContext<TParams, TState>,
1907
+ ): MappedTurnItemContext<TItem> {
1908
+ const iteration = ctx.iteration;
1909
+ if (!iteration) {
1910
+ throw new Error(`Mapped turn '${this.turnId}' requires an active item`);
1911
+ }
1912
+ return {
1913
+ item: this.items.itemCodec.parse(iteration.item),
1914
+ itemKey: iteration.itemKey,
1915
+ itemLabel: iteration.itemLabel,
1916
+ itemIndex: iteration.itemIndex,
1917
+ itemCount: iteration.itemCount,
1918
+ };
1956
1919
  }
1957
1920
 
1958
1921
  /** @public */
@@ -1962,71 +1925,66 @@ export class MappedLlmFlowBuilder<
1962
1925
  outcome: MappedOutcomeBuilder<TParams, TState, TItem, TResult>,
1963
1926
  ) => MappedOutcomeBuilder<TParams, TState, TItem, TResult> | undefined,
1964
1927
  ): this {
1928
+ if (id.trim() === "") {
1929
+ throw new Error(`LLM turn '${this.turnId}' declares an empty outcome tool id`);
1930
+ }
1931
+ if (this.outcomes.has(id)) {
1932
+ throw new Error(`LLM turn '${this.turnId}' declares duplicate outcome tool '${id}'`);
1933
+ }
1965
1934
  const outcome = new MappedOutcomeBuilder<TParams, TState, TItem, TResult>();
1966
1935
  configure(outcome);
1967
- const built = outcome.build();
1968
- this.base.addMappedOutcome(
1969
- id,
1970
- built.tool,
1971
- built.yieldResult as MappedItemYield<TParams, TState, unknown, unknown>,
1972
- );
1936
+ outcome.build();
1937
+ this.outcomes.set(id, outcome);
1973
1938
  return this;
1974
1939
  }
1975
1940
 
1976
1941
  /** Combine ordered item results into process state, once. @public */
1977
1942
  collect(fn: MappedCollect<TParams, TState, TResult>): MappedCollectBuilder<TParams, TState> {
1978
- this.base.setMappedCollect(fn as MappedCollect<TParams, TState, unknown>);
1979
- return new MappedCollectBuilder<TParams, TState>(this.base);
1980
- }
1981
- }
1982
-
1983
- type StoredExternalActionBuilder<TParams, TState> = ExternalActionBuilder<
1984
- TParams,
1985
- TState,
1986
- unknown,
1987
- Record<string, unknown>
1988
- >;
1989
-
1990
- /** @public */
1991
- abstract class ExternalActionTurnBuilder<TParams, TState> extends DescribedTurnBuilder {
1992
- /** @internal */
1993
- protected abstract readonly turnKind: "Automatic" | "Human";
1994
- private externalActionBuilders = new Map<string, StoredExternalActionBuilder<TParams, TState>>();
1995
-
1996
- /** @public */
1997
- externalAction<
1998
- TEvent = unknown,
1999
- TInput extends Record<string, unknown> = Record<string, unknown>,
2000
- >(
2001
- externalActionId: string,
2002
- source: ExternalActionSource<TParams, TState, TEvent, TInput>,
2003
- configure: (
2004
- external: ExternalActionBuilder<TParams, TState, TEvent, TInput>,
2005
- ) => ExternalActionBuilder<TParams, TState, TEvent, TInput> | undefined,
2006
- ): this {
2007
- if (this.externalActionBuilders.has(externalActionId)) {
2008
- throw new Error(
2009
- `${this.turnKind} turn '${this.turnId}' declares duplicate external action '${externalActionId}'`,
2010
- );
1943
+ if (this.collection) {
1944
+ throw new Error(`Mapped turn '${this.turnId}' declares .collect(...) more than once`);
2011
1945
  }
2012
- const builder = new ExternalActionBuilder(externalActionId, source);
2013
- configure(builder);
2014
- this.externalActionBuilders.set(
2015
- externalActionId,
2016
- builder as unknown as StoredExternalActionBuilder<TParams, TState>,
2017
- );
2018
- return this;
1946
+ this.collection = fn;
1947
+ return new MappedCollectBuilder(this, (routing) => {
1948
+ if (this.routing) {
1949
+ throw new Error(`Mapped turn '${this.turnId}' collection already declares a route`);
1950
+ }
1951
+ this.routing = routing;
1952
+ });
2019
1953
  }
2020
1954
 
2021
1955
  /** @internal */
2022
- protected buildExternalActions():
2023
- | Record<string, ProcessHumanTurnExternalActionSpec<TParams, TState>>
2024
- | undefined {
2025
- return this.externalActionBuilders.size > 0
2026
- ? Object.fromEntries(
2027
- [...this.externalActionBuilders].map(([id, builder]) => [id, builder.build()]),
2028
- )
2029
- : undefined;
1956
+ get definition(): LlmTurnDefinition<string, TParams, TState> {
1957
+ const definition = this.buildBaseDefinition();
1958
+ if (this.outcomes.size === 0) {
1959
+ throw new Error(`Mapped turn '${this.turnId}' must declare an item outcome tool`);
1960
+ }
1961
+ if (!this.collection) {
1962
+ throw new Error(`Mapped turn '${this.turnId}' must declare .collect(...)`);
1963
+ }
1964
+ if (!this.routing) {
1965
+ throw new Error(`Mapped turn '${this.turnId}' must declare a collection route`);
1966
+ }
1967
+ const outcomes: Record<string, ProcessToolOutcomeSpec<TParams, TState>> = {};
1968
+ const yields: Record<string, MappedItemYield<TParams, TState, TItem, TResult>> = {};
1969
+ for (const [id, builder] of this.outcomes) {
1970
+ const built = builder.build();
1971
+ outcomes[id] = built.tool;
1972
+ yields[id] = built.yieldResult;
1973
+ }
1974
+ assertLlmOutcomeParameters(this.turnId, outcomes);
1975
+ const forEach: MappedLlmTurnSpec<TParams, TState, TItem, TResult> = {
1976
+ ...this.items,
1977
+ yields,
1978
+ collect: this.collection,
1979
+ routing: this.routing,
1980
+ };
1981
+ return {
1982
+ ...definition,
1983
+ outcomes,
1984
+ turnResultMarkdown: OUTCOME_TOOL_ARGUMENT_TURN_RESULT,
1985
+ // The codecs preserve item/result types across the erased runtime definition boundary.
1986
+ forEach: forEach as MappedLlmTurnSpec<TParams, TState>,
1987
+ };
2030
1988
  }
2031
1989
  }
2032
1990
 
@@ -2042,10 +2000,12 @@ export class AutomaticFlowBuilder<TParams = unknown, TState = unknown>
2042
2000
  | null = null;
2043
2001
  private outcomeBuilders = new Map<string, AutomaticOutcomeBuilder<TParams, TState>>();
2044
2002
  private availableIntegrationTools: readonly string[] = [];
2045
-
2046
- /** @internal */
2047
- get definition(): AutomaticTurnDefinition<string, TParams, TState> {
2048
- return this.buildDefinition();
2003
+ private waitPredicate: TurnWaitPredicate<TParams, TState> | undefined;
2004
+ /** Wait on the server before this turn may allocate a worker. @public */
2005
+ waitFor(predicate: TurnWaitPredicate<TParams, TState>): this {
2006
+ if (this.waitPredicate) throw new Error(`Turn '${this.turnId}' already declares .waitFor(...)`);
2007
+ this.waitPredicate = predicate;
2008
+ return this;
2049
2009
  }
2050
2010
 
2051
2011
  /** @public */
@@ -2083,7 +2043,8 @@ export class AutomaticFlowBuilder<TParams = unknown, TState = unknown>
2083
2043
  return this;
2084
2044
  }
2085
2045
 
2086
- private buildDefinition(): AutomaticTurnDefinition<string, TParams, TState> {
2046
+ /** @internal */
2047
+ get definition(): AutomaticTurnDefinition<string, TParams, TState> {
2087
2048
  if (!this.turnDescription) {
2088
2049
  throw new Error(`Automatic turn '${this.turnId}' must declare .description(...)`);
2089
2050
  }
@@ -2093,15 +2054,13 @@ export class AutomaticFlowBuilder<TParams = unknown, TState = unknown>
2093
2054
  if (this.outcomeBuilders.size === 0) {
2094
2055
  throw new Error(`Automatic turn '${this.turnId}' must declare at least one outcome`);
2095
2056
  }
2096
- const outcomes: Record<string, ProcessToolOutcomeSpec<TParams, TState>> = {};
2097
- for (const [outcomeId, builder] of this.outcomeBuilders) {
2098
- outcomes[outcomeId] = builder.build();
2099
- }
2057
+ const outcomes = buildSpecs(this.outcomeBuilders);
2100
2058
  const runFn = this.runFn;
2101
2059
  const externalActions = this.buildExternalActions();
2102
2060
  return {
2103
2061
  kind: "automatic",
2104
2062
  description: this.turnDescription,
2063
+ ...(this.waitPredicate ? { waitFor: this.waitPredicate } : {}),
2105
2064
  ...(this.availableIntegrationTools.length > 0
2106
2065
  ? { integrationTools: this.availableIntegrationTools }
2107
2066
  : {}),
@@ -2288,11 +2247,10 @@ export class HumanFlowBuilder<TParams = unknown, TState = unknown>
2288
2247
  {
2289
2248
  /** @internal */
2290
2249
  protected readonly turnKind = "Human";
2291
- private reviewProductName: string | undefined;
2292
- private reviewSemanticRef: ProcessSemanticEntryRefKey | undefined;
2293
- private operatorAttentionValue: HumanTurnOperatorAttention | undefined;
2294
- private turnCommentary: string | undefined;
2295
- private notes: HumanTurnDefinition<TParams, TState>["notesFields"] | undefined;
2250
+ private readonly metadata: Omit<
2251
+ HumanTurnDefinition<TParams, TState>,
2252
+ "kind" | "description" | "actions" | "externalActions"
2253
+ > = {};
2296
2254
  private actions = new Map<string, HumanActionBuilder<TParams, TState>>();
2297
2255
 
2298
2256
  /** @public */
@@ -2304,42 +2262,38 @@ export class HumanFlowBuilder<TParams = unknown, TState = unknown>
2304
2262
  return {
2305
2263
  kind: "human",
2306
2264
  description: this.turnDescription,
2307
- ...(this.reviewProductName ? { reviewProduct: this.reviewProductName } : {}),
2308
- ...(this.reviewSemanticRef ? { reviewSemanticRef: this.reviewSemanticRef } : {}),
2309
- ...(this.operatorAttentionValue ? { operatorAttention: this.operatorAttentionValue } : {}),
2310
- ...(this.notes ? { notesFields: this.notes } : {}),
2311
- ...(this.turnCommentary ? { commentary: this.turnCommentary } : {}),
2312
- actions: Object.fromEntries(
2313
- [...this.actions.entries()].map(([actionId, builder]) => [actionId, builder.build()]),
2314
- ),
2265
+ ...this.metadata,
2266
+ actions: buildSpecs(this.actions),
2315
2267
  ...(externalActions ? { externalActions } : {}),
2316
2268
  };
2317
2269
  }
2318
2270
 
2319
2271
  /** @public */
2320
2272
  reviewProduct(productName: string): this {
2321
- const normalized = normalizeProductName(productName);
2322
- this.reviewProductName = normalized;
2323
- this.reviewSemanticRef =
2324
- normalized === "plan" ? "plan" : normalized === "review" ? "review" : undefined;
2273
+ this.metadata.reviewProduct = normalizeProductName(productName);
2274
+ if (productName === "plan" || productName === "review")
2275
+ this.metadata.reviewSemanticRef = productName;
2276
+ else delete this.metadata.reviewSemanticRef;
2325
2277
  return this;
2326
2278
  }
2327
2279
 
2328
2280
  /** @public */
2329
2281
  operatorAttention(attention: HumanTurnOperatorAttention): this {
2330
- this.operatorAttentionValue = attention;
2282
+ this.metadata.operatorAttention = attention;
2331
2283
  return this;
2332
2284
  }
2333
2285
 
2334
2286
  /** @internal */
2335
2287
  commentary(commentary: string): this {
2336
- this.turnCommentary = commentary;
2288
+ if (commentary) this.metadata.commentary = commentary;
2289
+ else delete this.metadata.commentary;
2337
2290
  return this;
2338
2291
  }
2339
2292
 
2340
2293
  /** @internal */
2341
2294
  notesFields(notes: HumanTurnDefinition<TParams, TState>["notesFields"]): this {
2342
- this.notes = notes;
2295
+ if (notes) this.metadata.notesFields = notes;
2296
+ else delete this.metadata.notesFields;
2343
2297
  return this;
2344
2298
  }
2345
2299
 
@@ -2396,17 +2350,17 @@ export class ExternalRouteBuilder<
2396
2350
 
2397
2351
  /** @public */
2398
2352
  to(turnId: TurnId): this {
2399
- return this.setTarget({ kind: "to", turnId });
2353
+ return this.setTarget({ to: turnId });
2400
2354
  }
2401
2355
 
2402
2356
  /** @internal */
2403
2357
  complete(): this {
2404
- return this.setTarget({ kind: "complete" });
2358
+ return this.setTarget({ complete: true });
2405
2359
  }
2406
2360
 
2407
2361
  /** @internal */
2408
2362
  lifecycleStatus(status: ProcessTurnTerminalLifecycleStatus): this {
2409
- return this.setTarget({ kind: "lifecycleStatus", status });
2363
+ return this.setTarget({ lifecycleStatus: status });
2410
2364
  }
2411
2365
 
2412
2366
  /** @internal */
@@ -2446,7 +2400,7 @@ export class ExternalRouteBuilder<
2446
2400
  return {
2447
2401
  /** @internal */
2448
2402
  source: this.source,
2449
- ...buildRouteTargetSpec(this.target),
2403
+ ...this.target,
2450
2404
  ...(this.externalEffect
2451
2405
  ? {
2452
2406
  /** @internal */
@@ -2590,21 +2544,8 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2590
2544
  TState
2591
2545
  > {
2592
2546
  private readonly processId: string;
2593
- private processDisplayName: string | null = null;
2594
- private entryTurnId: TurnId | null = null;
2547
+ private readonly configuration: Partial<DefinedProcessInput<TParams, TState>> = {};
2595
2548
  private readonly alternateEntryTurnIds: TurnId[] = [];
2596
- private happyPathTurnIds: readonly TurnId[] | null = null;
2597
- private paramsCodec: Codec<TParams> | null = null;
2598
- private stateCodec: Codec<TState> | null = null;
2599
- private initialStateFn: ((params: TParams) => TState) | null = null;
2600
- private repositoryCredentialsFn: ExtensionProcessDefinition<
2601
- TParams,
2602
- TState
2603
- >["repositoryCredentials"];
2604
- private storageSizeResolver: ExtensionProcessDefinition<TParams, TState>["resolveStorageSize"];
2605
- private processPiConfig: ProcessPiConfig | undefined;
2606
- private developmentTools = false;
2607
- private docker = false;
2608
2549
 
2609
2550
  /** @internal */
2610
2551
  constructor(processId: string) {
@@ -2617,13 +2558,13 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2617
2558
 
2618
2559
  /** @public */
2619
2560
  displayName(displayName: string): this {
2620
- this.processDisplayName = displayName;
2561
+ this.configuration.displayName = displayName;
2621
2562
  return this;
2622
2563
  }
2623
2564
 
2624
2565
  /** @public */
2625
2566
  entry(turnId: TurnId): this {
2626
- this.entryTurnId = turnId;
2567
+ this.configuration.entry = turnId;
2627
2568
  return this;
2628
2569
  }
2629
2570
 
@@ -2640,7 +2581,7 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2640
2581
  */
2641
2582
  /** @public */
2642
2583
  happyPath(...turnIds: readonly TurnId[]): this {
2643
- this.happyPathTurnIds = turnIds;
2584
+ this.configuration.happyPath = turnIds;
2644
2585
  return this;
2645
2586
  }
2646
2587
 
@@ -2651,14 +2592,14 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2651
2592
  /** @public */
2652
2593
  state: Codec<TState>;
2653
2594
  }): this {
2654
- this.paramsCodec = input.params;
2655
- this.stateCodec = input.state;
2595
+ this.configuration.paramsCodec = input.params;
2596
+ this.configuration.stateCodec = input.state;
2656
2597
  return this;
2657
2598
  }
2658
2599
 
2659
2600
  /** @public */
2660
2601
  initialState(fn: (params: TParams) => TState): this {
2661
- this.initialStateFn = fn;
2602
+ this.configuration.initialState = fn;
2662
2603
  return this;
2663
2604
  }
2664
2605
 
@@ -2666,7 +2607,7 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2666
2607
  repositoryCredentials(
2667
2608
  fn: NonNullable<ExtensionProcessDefinition<TParams, TState>["repositoryCredentials"]>,
2668
2609
  ): this {
2669
- this.repositoryCredentialsFn = fn;
2610
+ this.configuration.repositoryCredentials = fn;
2670
2611
  return this;
2671
2612
  }
2672
2613
 
@@ -2674,13 +2615,13 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2674
2615
  resolveStorageSize(
2675
2616
  fn: NonNullable<ExtensionProcessDefinition<TParams, TState>["resolveStorageSize"]>,
2676
2617
  ): this {
2677
- this.storageSizeResolver = fn;
2618
+ this.configuration.resolveStorageSize = fn;
2678
2619
  return this;
2679
2620
  }
2680
2621
 
2681
2622
  /** @public */
2682
2623
  piConfig(config: ProcessPiConfig): this {
2683
- this.processPiConfig = config;
2624
+ this.configuration.piConfig = config;
2684
2625
  return this;
2685
2626
  }
2686
2627
 
@@ -2690,9 +2631,18 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2690
2631
  developmentTools?: boolean;
2691
2632
  /** @public */
2692
2633
  docker?: boolean;
2634
+ /** @internal */
2635
+ repositoryCheckout?: "eager" | "on_demand" | "none";
2693
2636
  }): this {
2694
- this.developmentTools = capabilities.developmentTools === true;
2695
- this.docker = capabilities.docker === true;
2637
+ const runtime = {
2638
+ ...(capabilities.developmentTools === true ? { developmentTools: true } : {}),
2639
+ ...(capabilities.docker === true ? { docker: true } : {}),
2640
+ ...(capabilities.repositoryCheckout
2641
+ ? { repositoryCheckout: capabilities.repositoryCheckout }
2642
+ : {}),
2643
+ };
2644
+ if (Object.keys(runtime).length) this.configuration.runtime = runtime;
2645
+ else delete this.configuration.runtime;
2696
2646
  return this;
2697
2647
  }
2698
2648
 
@@ -2708,16 +2658,17 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2708
2658
 
2709
2659
  /** @public */
2710
2660
  define(): ExtensionProcessDefinition<TParams, TState> {
2711
- if (!this.processDisplayName) {
2661
+ const { displayName, entry, paramsCodec, stateCodec, initialState } = this.configuration;
2662
+ if (!displayName) {
2712
2663
  throw new Error(`Flow process '${this.processId}' must declare .displayName(...)`);
2713
2664
  }
2714
- if (!this.entryTurnId) {
2665
+ if (!entry) {
2715
2666
  throw new Error(`Flow process '${this.processId}' must declare .entry(turnId)`);
2716
2667
  }
2717
- if (!this.paramsCodec || !this.stateCodec) {
2668
+ if (!paramsCodec || !stateCodec) {
2718
2669
  throw new Error(`Flow process '${this.processId}' must declare .codecs(...)`);
2719
2670
  }
2720
- if (!this.initialStateFn) {
2671
+ if (!initialState) {
2721
2672
  throw new Error(`Flow process '${this.processId}' must declare .initialState(...)`);
2722
2673
  }
2723
2674
 
@@ -2730,42 +2681,23 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2730
2681
  }
2731
2682
 
2732
2683
  const input: DefinedProcessInput<TParams, TState> = {
2684
+ ...this.configuration,
2733
2685
  id: this.processId,
2734
- displayName: this.processDisplayName,
2735
- entry: this.entryTurnId,
2686
+ displayName,
2687
+ entry,
2736
2688
  ...(this.alternateEntryTurnIds.length > 0
2737
2689
  ? { alternateEntries: [...this.alternateEntryTurnIds] }
2738
2690
  : {}),
2739
- ...(this.happyPathTurnIds ? { happyPath: [...this.happyPathTurnIds] } : {}),
2740
- paramsCodec: this.paramsCodec,
2741
- stateCodec: this.stateCodec,
2742
- initialState: this.initialStateFn,
2743
- ...(this.developmentTools || this.docker
2744
- ? {
2745
- runtime: {
2746
- ...(this.developmentTools ? { developmentTools: true } : {}),
2747
- ...(this.docker ? { docker: true } : {}),
2748
- },
2749
- }
2750
- : {}),
2751
- ...(this.repositoryCredentialsFn
2752
- ? { repositoryCredentials: this.repositoryCredentialsFn }
2753
- : {}),
2754
- ...(this.storageSizeResolver ? { resolveStorageSize: this.storageSizeResolver } : {}),
2755
- ...(this.processPiConfig ? { piConfig: this.processPiConfig } : {}),
2691
+ paramsCodec,
2692
+ stateCodec,
2693
+ initialState,
2756
2694
  turns,
2757
2695
  ...(this.serverHooks.length > 0 ? { server: chainHooks(this.serverHooks) } : {}),
2758
2696
  ...(this.uiHooks.length > 0 ? { ui: chainHooks(this.uiHooks) } : {}),
2759
2697
  ...(this.launcherHooks.length > 0 ? { launchers: chainHooks(this.launcherHooks) } : {}),
2760
2698
  ...(this.watcherHooks.length > 0 ? { watchers: chainHooks(this.watcherHooks) } : {}),
2761
2699
  };
2762
- const process = defineProcess(input);
2763
- const errors = validateProcessGraphProducts(
2764
- toProcessGraphView(process as unknown as ProcessGraphSource),
2765
- );
2766
- if (errors.length > 0)
2767
- throw new Error(`Flow process '${this.processId}': ${errors.join("; ")}`);
2768
- return process;
2700
+ return defineProcess(input);
2769
2701
  }
2770
2702
  }
2771
2703
 
@@ -2775,6 +2707,13 @@ export const flow = {
2775
2707
  llm<TParams = unknown, TState = unknown>(turnId: TurnId): LlmFlowBuilder<TParams, TState> {
2776
2708
  return new LlmFlowBuilder<TParams, TState>(turnId);
2777
2709
  },
2710
+ /** Run an LLM turn sequentially over frozen items, then collect and route once. @public */
2711
+ mappedLlm<TParams = unknown, TState = unknown, TItem = unknown, TResult = unknown>(
2712
+ turnId: TurnId,
2713
+ items: FlowForEachOptions<TParams, TState, TItem, TResult>,
2714
+ ): MappedLlmFlowBuilder<TParams, TState, TItem, TResult> {
2715
+ return new MappedLlmFlowBuilder<TParams, TState, TItem, TResult>(turnId, items);
2716
+ },
2778
2717
  /** @public */
2779
2718
  automatic<TParams = unknown, TState = unknown>(
2780
2719
  turnId: TurnId,