@leitwerk-dev/process-sdk 0.3.0 → 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-I7U6HCLN.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 +43 -26
  6. package/dist/define-process.d.ts.map +1 -1
  7. package/dist/{extension-api-3Vr3RE8S.d.ts → extension-api-Ljc4UTZ0.d.ts} +440 -49
  8. package/dist/extension-api.d.ts +66 -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 +234 -118
  17. package/dist/flow.d.ts.map +1 -1
  18. package/dist/index.d.ts +15 -7
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +4189 -3534
  21. package/dist/index.js.map +1 -1
  22. package/dist/mapped-turn.d.ts +169 -0
  23. package/dist/mapped-turn.d.ts.map +1 -0
  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 +45 -24
  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 +447 -540
  47. package/src/extension-api.ts +78 -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 +888 -532
  52. package/src/index.ts +77 -2
  53. package/src/mapped-turn.ts +437 -0
  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 +102 -116
  61. package/src/turn-wait.ts +76 -0
  62. package/src/types.ts +44 -22
  63. package/dist/chunk-I7U6HCLN.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,16 +49,26 @@ 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";
49
56
  import { isPathInside } from "./fs-utils.js";
50
- import {
51
- type ProcessGraphSource,
52
- toProcessGraphView,
53
- validateProcessGraphProducts,
54
- } from "./process-graph.js";
55
- import type { OutcomeToolParameterSpec, PiBuiltInToolName, ProcessPiConfig } from "./types.js";
57
+ import type {
58
+ MappedCollect,
59
+ MappedCollectRouting,
60
+ MappedItemYield,
61
+ MappedLlmTurnSpec,
62
+ MappedTurnItemContext,
63
+ MappedTurnServerContext,
64
+ } from "./mapped-turn.js";
65
+ import type { TurnWaitPredicate } from "./turn-wait.js";
66
+ import type {
67
+ OutcomeToolArrayItemSpec,
68
+ OutcomeToolParameterSpec,
69
+ PiBuiltInToolName,
70
+ ProcessPiConfig,
71
+ } from "./types.js";
56
72
 
57
73
  /** @public */
58
74
  type MaybePromise<T> = T | Promise<T>;
@@ -206,6 +222,8 @@ export type FlowPromptContext<
206
222
 
207
223
  /** @public */
208
224
  export interface FlowAutomaticRunContext<TParams = unknown, TState = unknown> {
225
+ /** Immutable non-secret settings captured for this turn. @public */
226
+ readonly scopedSettings?: ScopedSettingsSnapshot;
209
227
  /** @public */
210
228
  process: ProcessInstance;
211
229
  /** @public */
@@ -222,6 +240,15 @@ export interface FlowAutomaticRunContext<TParams = unknown, TState = unknown> {
222
240
  callIntegrationTool(name: string, args: Record<string, unknown>): Promise<unknown>;
223
241
  /** @public */
224
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;
225
252
  }
226
253
 
227
254
  /** @public */
@@ -285,35 +312,6 @@ type FlowOutcomeStateEffect<TParams, TState, TContext> = (
285
312
  input: FlowOutcomeEffectInput<TParams, TState, TContext>,
286
313
  ) => MaybePromise<TState>;
287
314
 
288
- function textField(input: {
289
- description: string;
290
- requiredErrorCode: string;
291
- }): OutcomeToolParameterSpec {
292
- return {
293
- type: "string",
294
- description: input.description,
295
- required: true,
296
- requiredErrorCode: input.requiredErrorCode,
297
- };
298
- }
299
-
300
- function stringArrayField(input: {
301
- description: string;
302
- requiredErrorCode: string;
303
- minItems: number;
304
- minItemsErrorCode: string;
305
- }): OutcomeToolParameterSpec {
306
- return {
307
- type: "array",
308
- description: input.description,
309
- items: { type: "string" },
310
- required: true,
311
- requiredErrorCode: input.requiredErrorCode,
312
- minItems: input.minItems,
313
- minItemsErrorCode: input.minItemsErrorCode,
314
- };
315
- }
316
-
317
315
  function normalizeProductName(productName: string): string {
318
316
  assertValidProcessProductName(productName);
319
317
  return productName;
@@ -347,10 +345,6 @@ function safeJoinInside(parent: string, childPath: string, context: string): str
347
345
  return targetPath;
348
346
  }
349
347
 
350
- function toWorkspaceClonePath(relativePath: string): string {
351
- return `./${relativePath.split(path.sep).join("/")}`;
352
- }
353
-
354
348
  function resolveSafeProjectWorkspacePath(key: string): {
355
349
  relativePath: string;
356
350
  workspaceClonePath: string;
@@ -367,7 +361,7 @@ function resolveSafeProjectWorkspacePath(key: string): {
367
361
  const relativePath = path.relative(virtualWorkspaceRoot, virtualTarget);
368
362
  return {
369
363
  relativePath,
370
- workspaceClonePath: toWorkspaceClonePath(relativePath),
364
+ workspaceClonePath: `./${relativePath.split(path.sep).join("/")}`,
371
365
  };
372
366
  }
373
367
 
@@ -375,47 +369,17 @@ function resolveRepoByKey(input: {
375
369
  projects: readonly ProcessProject[];
376
370
  workspaceRoot?: string;
377
371
  key: string;
378
- required: true;
379
- }): FlowRepoContext;
380
- function resolveRepoByKey(input: {
381
- projects: readonly ProcessProject[];
382
- workspaceRoot?: string;
383
- key: string;
384
- required: false;
385
- }): FlowRepoContext | undefined;
386
- function resolveRepoByKey(input: {
387
- projects: readonly ProcessProject[];
388
- workspaceRoot?: string;
389
- key: string;
390
- required: boolean;
391
372
  }): FlowRepoContext | undefined {
392
- const requestedKey = input.key.trim();
393
- if (!requestedKey) {
373
+ const key = input.key.trim();
374
+ if (!key) {
394
375
  throw new Error("Flow repo lookup requires a non-empty project key");
395
376
  }
396
- const matches = input.projects.filter((project) => project.key.trim() === requestedKey);
397
- if (matches.length === 0) {
398
- if (!input.required) {
399
- return undefined;
400
- }
401
- const availableKeys = input.projects
402
- .map((project) => project.key.trim())
403
- .filter((key) => key !== "")
404
- .join(", ");
405
- throw new Error(
406
- `Flow context requires project '${requestedKey}', but this process has no project with that key${
407
- availableKeys ? ` (available: ${availableKeys})` : ""
408
- }`,
409
- );
410
- }
377
+ const matches = input.projects.filter((project) => project.key.trim() === key);
378
+ if (matches.length === 0) return undefined;
411
379
  if (matches.length > 1) {
412
- throw new Error(`Flow context found duplicate project key '${requestedKey}'`);
380
+ throw new Error(`Flow context found duplicate project key '${key}'`);
413
381
  }
414
382
  const project = matches[0];
415
- const key = project.key.trim();
416
- if (!key) {
417
- throw new Error("Flow context requires projects to have non-empty keys");
418
- }
419
383
  const baseBranch = project.baseBranch.trim();
420
384
  if (!baseBranch) {
421
385
  throw new Error(`Flow context project '${key}' has no base branch`);
@@ -446,13 +410,23 @@ function createFlowRepoLookup(input: {
446
410
  projects: readonly ProcessProject[];
447
411
  workspaceRoot?: string;
448
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
+ };
449
426
  return {
450
- get: (key) => resolveRepoByKey({ ...input, key, required: true }),
451
- optional: (key) => resolveRepoByKey({ ...input, key, required: false }),
452
- all: () =>
453
- input.projects.map((project) =>
454
- resolveRepoByKey({ ...input, key: project.key, required: true }),
455
- ),
427
+ get,
428
+ optional: (key) => resolveRepoByKey({ ...input, key }),
429
+ all: () => input.projects.map((project) => get(project.key)),
456
430
  };
457
431
  }
458
432
 
@@ -480,23 +454,16 @@ export function createFlowPromptContext<
480
454
  optionalConsumedProducts: readonly string[] = [],
481
455
  ): FlowPromptContext<TParams, TState, TConsumedProducts, TPrepared> {
482
456
  const productInput: Record<string, string> = {};
483
- for (const productName of consumedProducts) {
457
+ const required = new Set<string>(consumedProducts);
458
+ for (const productName of new Set([...required, ...optionalConsumedProducts])) {
484
459
  const markdown = ctx.turnResultMarkdownByProduct?.[productName];
485
- if (typeof markdown !== "string" || markdown.trim() === "") {
460
+ if (typeof markdown === "string" && markdown.trim() !== "") {
461
+ productInput[productName] = markdown;
462
+ } else if (required.has(productName)) {
486
463
  throw new Error(
487
464
  `Flow prompt context requires product '${productName}' markdown, but the worker payload did not provide it`,
488
465
  );
489
466
  }
490
- productInput[productName] = markdown;
491
- }
492
- for (const productName of optionalConsumedProducts) {
493
- if (productName in productInput) {
494
- continue;
495
- }
496
- const markdown = ctx.turnResultMarkdownByProduct?.[productName];
497
- if (typeof markdown === "string" && markdown.trim() !== "") {
498
- productInput[productName] = markdown;
499
- }
500
467
  }
501
468
  return {
502
469
  ...createFlowContextBase(ctx),
@@ -514,6 +481,7 @@ export function createFlowAutomaticRunContext<TParams, TState>(
514
481
  ): FlowAutomaticRunContext<TParams, TState> {
515
482
  return {
516
483
  ...createFlowContextBase(ctx),
484
+ scopedSettings: ctx.scopedSettings,
517
485
  callIntegrationTool(name, args) {
518
486
  if (!ctx.callIntegrationTool) {
519
487
  throw new Error(`Automatic integration tool '${name}' is unavailable`);
@@ -523,6 +491,9 @@ export function createFlowAutomaticRunContext<TParams, TState>(
523
491
  reportProgress(report) {
524
492
  ctx.reportProgress?.(report);
525
493
  },
494
+ reportDiagnostic(report) {
495
+ ctx.reportDiagnostic?.(report);
496
+ },
526
497
  };
527
498
  }
528
499
 
@@ -567,17 +538,17 @@ class RouteAndEffectBuilder<TParams, TState, TContext> {
567
538
 
568
539
  /** @public */
569
540
  to(turnId: TurnId): this {
570
- return this.setTarget({ kind: "to", turnId });
541
+ return this.setTarget({ to: turnId });
571
542
  }
572
543
 
573
544
  /** @public */
574
545
  complete(): this {
575
- return this.setTarget({ kind: "complete" });
546
+ return this.setTarget({ complete: true });
576
547
  }
577
548
 
578
549
  /** @public */
579
550
  lifecycleStatus(status: ProcessTurnTerminalLifecycleStatus): this {
580
- return this.setTarget({ kind: "lifecycleStatus", status });
551
+ return this.setTarget({ lifecycleStatus: status });
581
552
  }
582
553
 
583
554
  /** @internal */
@@ -598,21 +569,19 @@ class RouteAndEffectBuilder<TParams, TState, TContext> {
598
569
  return this;
599
570
  }
600
571
 
572
+ /** @internal */
573
+ getEffect(): FlowOutcomeEffect<TParams, TState, TContext> | undefined {
574
+ return this.flowEffect;
575
+ }
576
+
601
577
  /** @internal */
602
578
  hasRoute(): boolean {
603
579
  return this.target !== null;
604
580
  }
605
581
 
606
582
  /** @internal */
607
- protected buildRouteTarget(): {
608
- /** @internal */
609
- to?: TurnId;
610
- /** @internal */
611
- complete?: boolean;
612
- /** @internal */
613
- lifecycleStatus?: ProcessTurnTerminalLifecycleStatus;
614
- } {
615
- return buildRouteTargetSpec(this.target);
583
+ buildRouteTarget(): Pick<ProcessTurnEndSpec, "to" | "complete" | "lifecycleStatus"> {
584
+ return { ...this.target };
616
585
  }
617
586
  }
618
587
 
@@ -620,42 +589,18 @@ class RouteAndEffectBuilder<TParams, TState, TContext> {
620
589
  export type FlowTargetSpec =
621
590
  | {
622
591
  /** @internal */
623
- kind: "to";
624
- /** @internal */
625
- turnId: TurnId;
592
+ to: TurnId;
626
593
  }
627
594
  | {
628
595
  /** @internal */
629
- kind: "complete";
596
+ complete: true;
630
597
  }
631
598
  | {
632
599
  /** @internal */
633
- kind: "lifecycleStatus";
634
- /** @internal */
635
- status: ProcessTurnTerminalLifecycleStatus;
600
+ lifecycleStatus: ProcessTurnTerminalLifecycleStatus;
636
601
  }
637
602
  | null;
638
603
 
639
- export function buildRouteTargetSpec(target: FlowTargetSpec): {
640
- /** @internal */
641
- to?: TurnId;
642
- /** @internal */
643
- complete?: boolean;
644
- /** @internal */
645
- lifecycleStatus?: ProcessTurnTerminalLifecycleStatus;
646
- } {
647
- if (!target) {
648
- return {};
649
- }
650
- if (target.kind === "to") {
651
- return { to: target.turnId };
652
- }
653
- if (target.kind === "complete") {
654
- return { complete: true };
655
- }
656
- return { lifecycleStatus: target.status };
657
- }
658
-
659
604
  /** @public */
660
605
  interface ParameterOptions extends Partial<Omit<OutcomeToolParameterSpec, "type" | "description">> {
661
606
  /** @public */
@@ -664,9 +609,9 @@ interface ParameterOptions extends Partial<Omit<OutcomeToolParameterSpec, "type"
664
609
  requiredErrorCode?: string;
665
610
  }
666
611
 
667
- /** @internal */
612
+ /** @public */
668
613
  interface ArrayParameterOptions extends ParameterOptions {
669
- /** @internal */
614
+ /** @public */
670
615
  items?: OutcomeToolParameterSpec["items"];
671
616
  }
672
617
 
@@ -687,19 +632,38 @@ function isStringArray(value: unknown): value is readonly string[] {
687
632
  }
688
633
 
689
634
  /** @public */
690
- class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEffectBuilder<
691
- TParams,
692
- TState,
693
- TContext
694
- > {
635
+ class OutcomeParametersBuilder<TParams = unknown, TState = unknown> {
695
636
  /** @internal */
696
637
  protected outcomeDescription: string | null = null;
697
638
  /** @internal */
698
639
  protected parameters: Record<string, OutcomeToolParameterSpec> = {};
699
640
  /** @internal */
700
- protected publishedMarkdownParameter: string | null = null;
701
- /** @internal */
702
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
+ }
703
667
 
704
668
  /** Optional concise result publication, separate from the full Markdown. @public */
705
669
  resultSummary(name = "resultSummary"): this {
@@ -711,15 +675,17 @@ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEff
711
675
  }
712
676
 
713
677
  /** @internal */
714
- protected publishedMarkdownFields() {
715
- return this.publishedMarkdownParameter
716
- ? {
717
- /** @internal */
718
- publishedProduct: this.publishedMarkdownParameter,
719
- /** @internal */
720
- turnResultMarkdownParameter: this.publishedMarkdownParameter,
721
- }
722
- : {};
678
+ protected buildParameterSpec(
679
+ kind: string,
680
+ ): Pick<ProcessToolOutcomeSpec, "description" | "parameters" | "resultSummaryParameter"> {
681
+ if (!this.outcomeDescription) throw new Error(`${kind} must declare .description(...)`);
682
+ return {
683
+ description: this.outcomeDescription,
684
+ parameters: this.parameters,
685
+ ...(this.enforceSchema ? { strictSchema: true } : {}),
686
+ ...(this.parameterResolver ? { resolveParameters: this.parameterResolver } : {}),
687
+ ...(this.summaryParameter ? { resultSummaryParameter: this.summaryParameter } : {}),
688
+ };
723
689
  }
724
690
 
725
691
  /** @public */
@@ -752,7 +718,8 @@ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEff
752
718
  };
753
719
  }
754
720
 
755
- private typedParameter(
721
+ /** @internal */
722
+ protected typedParameter(
756
723
  name: string,
757
724
  type: OutcomeToolParameterSpec["type"],
758
725
  options: string | ArrayParameterOptions = {},
@@ -766,29 +733,11 @@ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEff
766
733
  });
767
734
  }
768
735
 
769
- /** @internal */
736
+ /** @public */
770
737
  string(name: string, options: string | ParameterOptions = {}): this {
771
738
  return this.typedParameter(name, "string", options);
772
739
  }
773
740
 
774
- /** @public */
775
- markdown(name: string, options: string | MarkdownParameterOptions = {}): this {
776
- const resolved = typeof options === "string" ? { description: options } : options;
777
- const { publish, ...parameterOptions } = resolved;
778
- if (publish) {
779
- if (this.publishedMarkdownParameter && this.publishedMarkdownParameter !== name) {
780
- throw new Error("Outcome can publish only one markdown parameter");
781
- }
782
- normalizeProductName(name);
783
- this.publishedMarkdownParameter = name;
784
- }
785
- return this.typedParameter(name, "string", {
786
- ...parameterOptions,
787
- required: publish ? true : resolved.required,
788
- requiredErrorCode: resolved.requiredErrorCode ?? (publish ? `${name}_required` : undefined),
789
- });
790
- }
791
-
792
741
  /** @public */
793
742
  requiredString(name: string, options: string | ParameterOptions = {}): this {
794
743
  return this.typedParameter(name, "string", this.withRequired(name, options));
@@ -799,7 +748,7 @@ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEff
799
748
  return this.typedParameter(name, "number", options);
800
749
  }
801
750
 
802
- /** @internal */
751
+ /** @public */
803
752
  requiredNumber(name: string, options: string | ParameterOptions = {}): this {
804
753
  return this.typedParameter(name, "number", this.withRequired(name, options));
805
754
  }
@@ -809,7 +758,7 @@ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEff
809
758
  return this.typedParameter(name, "boolean", options);
810
759
  }
811
760
 
812
- /** @internal */
761
+ /** @public */
813
762
  requiredBoolean(name: string, options: string | ParameterOptions = {}): this {
814
763
  return this.typedParameter(name, "boolean", this.withRequired(name, options));
815
764
  }
@@ -819,9 +768,9 @@ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEff
819
768
  return this.typedParameter(name, "array", options);
820
769
  }
821
770
 
822
- /** @internal */
771
+ /** @public */
823
772
  requiredStringArray(name: string, options: string | ArrayParameterOptions = {}): this {
824
- return this.typedParameter(name, "array", this.withRequired(name, options));
773
+ return this.typedParameter(name, "array", { minItems: 1, ...this.withRequired(name, options) });
825
774
  }
826
775
 
827
776
  /** @internal */
@@ -847,6 +796,102 @@ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEff
847
796
  array(name: string, options: string | ArrayParameterOptions = {}): this {
848
797
  return this.typedParameter(name, "array", options);
849
798
  }
799
+
800
+ /** @public */
801
+ requiredArray(name: string, options: string | ArrayParameterOptions = {}): this {
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
+ });
894
+ }
850
895
  }
851
896
 
852
897
  /** @public */
@@ -858,9 +903,17 @@ export class OutcomeToolBuilder<
858
903
  TState,
859
904
  FlowLlmOutcomeEffectContext<TParams, TState>
860
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
+
861
914
  private stateRouting:
862
915
  | {
863
- branches: Record<string, TurnId>;
916
+ branches: Record<string, TurnId | ProcessOutcomeBranchSpec>;
864
917
  choose: (
865
918
  input: FlowOutcomeEffectInput<
866
919
  TParams,
@@ -873,7 +926,7 @@ export class OutcomeToolBuilder<
873
926
 
874
927
  /** @public */
875
928
  routeByState(
876
- branches: Record<string, TurnId>,
929
+ branches: Record<string, TurnId | ProcessOutcomeBranchSpec>,
877
930
  choose: (
878
931
  input: FlowOutcomeEffectInput<TParams, TState, FlowLlmOutcomeEffectContext<TParams, TState>>,
879
932
  ) => MaybePromise<string>,
@@ -890,24 +943,19 @@ export class OutcomeToolBuilder<
890
943
 
891
944
  /** @internal */
892
945
  build(): ProcessToolOutcomeSpec<TParams, TState> {
893
- if (!this.outcomeDescription) {
894
- throw new Error("LLM outcome tool must declare .description(...)");
895
- }
946
+ const parameters = this.buildParameterSpec("LLM outcome tool");
896
947
  if (this.stateRouting && this.hasRoute()) {
897
948
  throw new Error("State-routed outcome cannot declare another route");
898
949
  }
899
950
  const stateRouting = this.stateRouting;
900
951
  return {
901
- description: this.outcomeDescription,
902
- parameters: this.parameters,
903
- ...(this.summaryParameter ? { resultSummaryParameter: this.summaryParameter } : {}),
904
- ...this.publishedMarkdownFields(),
952
+ ...parameters,
905
953
  ...(stateRouting
906
954
  ? {
907
955
  branches: Object.fromEntries(
908
- Object.entries(stateRouting.branches).map(([branchId, turnId]) => [
956
+ Object.entries(stateRouting.branches).map(([branchId, branch]) => [
909
957
  branchId,
910
- { to: turnId },
958
+ typeof branch === "string" ? { to: branch } : { ...branch },
911
959
  ]),
912
960
  ),
913
961
  choose: wrapOutcomeCallback((input) => stateRouting.choose(input)),
@@ -938,9 +986,7 @@ export class AutomaticOutcomeBuilder<
938
986
 
939
987
  /** @internal */
940
988
  build(): ProcessToolOutcomeSpec<TParams, TState> {
941
- if (!this.outcomeDescription) {
942
- throw new Error("Automatic outcome must declare .description(...)");
943
- }
989
+ const parameters = this.buildParameterSpec("Automatic outcome");
944
990
  const configuredEffect = this.flowEffect ? wrapOutcomeCallback(this.flowEffect) : undefined;
945
991
  const effect = this.waits
946
992
  ? async (
@@ -954,10 +1000,7 @@ export class AutomaticOutcomeBuilder<
954
1000
  }
955
1001
  : configuredEffect;
956
1002
  return {
957
- description: this.outcomeDescription,
958
- parameters: this.parameters,
959
- ...(this.summaryParameter ? { resultSummaryParameter: this.summaryParameter } : {}),
960
- ...this.publishedMarkdownFields(),
1003
+ ...parameters,
961
1004
  ...this.buildRouteTarget(),
962
1005
  ...(effect ? { effect } : {}),
963
1006
  };
@@ -984,29 +1027,34 @@ export class PlanResultBuilder<TParams = unknown, TState = unknown> extends Rout
984
1027
  /** @internal */
985
1028
  summary(options: string | PlanFieldOptions = {}): this {
986
1029
  const resolved = typeof options === "string" ? { description: options } : options;
987
- this.summarySpec = textField({
1030
+ this.summarySpec = {
1031
+ type: "string",
988
1032
  description: resolved.description ?? "Short summary of the proposed plan",
1033
+ required: true,
989
1034
  requiredErrorCode: resolved.requiredErrorCode ?? "summary_required",
990
- });
1035
+ };
991
1036
  return this;
992
1037
  }
993
1038
 
994
1039
  /** @internal */
995
1040
  acceptanceCriteria(options: string | PlanAcceptanceCriteriaOptions = {}): this {
996
1041
  const resolved = typeof options === "string" ? { description: options } : options;
997
- this.acceptanceCriteriaSpec = stringArrayField({
1042
+ this.acceptanceCriteriaSpec = {
1043
+ type: "array",
998
1044
  description: resolved.description ?? "Acceptance criteria for the requested change",
1045
+ items: { type: "string" },
1046
+ required: true,
999
1047
  requiredErrorCode: resolved.requiredErrorCode ?? "acceptance_criteria_required",
1000
1048
  minItems: resolved.minItems ?? 1,
1001
1049
  minItemsErrorCode: resolved.minItemsErrorCode ?? "acceptance_criteria_required",
1002
- });
1050
+ };
1003
1051
  return this;
1004
1052
  }
1005
1053
 
1006
1054
  /** @internal */
1007
1055
  review(turnId: TurnId): this {
1008
1056
  this.reviewTurnId = turnId;
1009
- return this.setTarget({ kind: "to", turnId });
1057
+ return this.setTarget({ to: turnId });
1010
1058
  }
1011
1059
 
1012
1060
  /** @internal */
@@ -1028,26 +1076,45 @@ export class PlanResultBuilder<TParams = unknown, TState = unknown> extends Rout
1028
1076
  acceptanceCriteria: this.acceptanceCriteriaSpec,
1029
1077
  },
1030
1078
  to: this.reviewTurnId,
1031
- lifecycleIntent: {
1032
- kind: "save_plan_result",
1033
- summaryParam: "summary",
1034
- acceptanceCriteriaParam: "acceptanceCriteria",
1035
- planMarkdownParam: "planMarkdown",
1036
- emitEventType: DEFAULT_PLAN_RESULT_OUTCOME_ID,
1037
- broadcastType: "plan.updated",
1038
- ...(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
+ };
1039
1106
  },
1040
1107
  };
1041
1108
  }
1042
1109
  }
1043
1110
 
1044
1111
  /** @public */
1045
- abstract class TurnEndBuilder<TParams, TState>
1112
+ export class LlmTurnEndBuilder<TParams = unknown, TState = unknown>
1046
1113
  extends RouteAndEffectBuilder<TParams, TState, FlowLlmOutcomeEffectContext<TParams, TState>>
1047
1114
  implements FlowLlmTurn<TParams, TState, string>
1048
1115
  {
1049
1116
  /** @internal */
1050
- protected abstract readonly builderName: string;
1117
+ protected readonly builderName: string = "LLM turn end";
1051
1118
 
1052
1119
  /** @internal */
1053
1120
  constructor(
@@ -1055,6 +1122,7 @@ abstract class TurnEndBuilder<TParams, TState>
1055
1122
  private readonly parent?: FlowLlmTurn<TParams, TState, string>,
1056
1123
  ) {
1057
1124
  super();
1125
+ if (outcomeId.trim() === "") throw new Error("LLM turn end outcome must be non-empty");
1058
1126
  }
1059
1127
 
1060
1128
  private get turn(): FlowLlmTurn<TParams, TState, string> {
@@ -1073,7 +1141,7 @@ abstract class TurnEndBuilder<TParams, TState>
1073
1141
  }
1074
1142
 
1075
1143
  /** @internal */
1076
- protected buildResult(): ProcessTurnEndSpec<TParams, TState, string> {
1144
+ build(): ProcessTurnEndSpec<TParams, TState, string> {
1077
1145
  const effect = this.flowEffect ? wrapOutcomeCallback(this.flowEffect) : undefined;
1078
1146
  return {
1079
1147
  outcome: this.outcomeId,
@@ -1084,44 +1152,19 @@ abstract class TurnEndBuilder<TParams, TState>
1084
1152
  }
1085
1153
 
1086
1154
  /** @public */
1087
- export class PublishedResultBuilder<TParams = unknown, TState = unknown> extends TurnEndBuilder<
1155
+ export class PublishedResultBuilder<TParams = unknown, TState = unknown> extends LlmTurnEndBuilder<
1088
1156
  TParams,
1089
1157
  TState
1090
1158
  > {
1091
1159
  /** @internal */
1092
- protected readonly builderName = "Published result";
1160
+ protected override readonly builderName = "Published result";
1093
1161
 
1094
1162
  /** @internal */
1095
1163
  buildTurnEnd(): ProcessTurnEndSpec<TParams, TState, string> {
1096
- return this.buildResult();
1097
- }
1098
- }
1099
-
1100
- /** @public */
1101
- export class LlmTurnEndBuilder<TParams = unknown, TState = unknown> extends TurnEndBuilder<
1102
- TParams,
1103
- TState
1104
- > {
1105
- /** @internal */
1106
- protected readonly builderName = "LLM turn end";
1107
-
1108
- /** @internal */
1109
- constructor(outcomeId: string, parent?: FlowLlmTurn<TParams, TState, string>) {
1110
- super(outcomeId, parent);
1111
- if (outcomeId.trim() === "") throw new Error("LLM turn end outcome must be non-empty");
1112
- }
1113
-
1114
- /** @internal */
1115
- build(): ProcessTurnEndSpec<TParams, TState, string> {
1116
- return this.buildResult();
1164
+ return this.build();
1117
1165
  }
1118
1166
  }
1119
1167
 
1120
- /** @public */
1121
- type LlmPromptBuilder<TParams, TState, TConsumedProducts extends string, TPrepared> = (
1122
- ctx: FlowPromptContext<TParams, TState, TConsumedProducts, TPrepared>,
1123
- ) => MaybePromise<string>;
1124
-
1125
1168
  /** @public */
1126
1169
  abstract class DescribedTurnBuilder {
1127
1170
  /** @internal */
@@ -1145,121 +1188,258 @@ abstract class DescribedTurnBuilder {
1145
1188
  }
1146
1189
  }
1147
1190
 
1191
+ type StoredExternalActionBuilder<TParams, TState> = ExternalActionBuilder<
1192
+ TParams,
1193
+ TState,
1194
+ unknown,
1195
+ Record<string, unknown>
1196
+ >;
1197
+
1148
1198
  /** @public */
1149
- export class LlmFlowBuilder<
1150
- TParams = unknown,
1151
- TState = unknown,
1152
- TConsumedProducts extends string = never,
1153
- TPrepared = undefined,
1154
- >
1155
- extends DescribedTurnBuilder
1156
- implements FlowLlmTurn<TParams, TState, string>
1157
- {
1158
- private modelPurposeValue: LlmModelPurpose | undefined;
1159
- private availableTools: readonly PiBuiltInToolName[] = [];
1160
- private availableIntegrationTools: readonly string[] = [];
1161
- private integrationToolResolver:
1162
- | ((params: TParams, state: TState) => readonly string[])
1163
- | undefined;
1164
- private preparation:
1165
- | ((ctx: FlowLlmPreparationContext<TParams, TState>) => MaybePromise<unknown>)
1166
- | null = null;
1199
+ abstract class ExternalActionTurnBuilder<TParams, TState> extends DescribedTurnBuilder {
1200
+ /** @internal */
1201
+ protected abstract readonly turnKind: "LLM" | "Automatic" | "Human";
1202
+ private externalActionBuilders = new Map<string, StoredExternalActionBuilder<TParams, TState>>();
1203
+
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)) {
1216
+ throw new Error(
1217
+ `${this.turnKind} turn '${this.turnId}' declares duplicate external action '${externalActionId}'`,
1218
+ );
1219
+ }
1220
+ const builder = new ExternalActionBuilder(externalActionId, source);
1221
+ configure(builder);
1222
+ this.externalActionBuilders.set(
1223
+ externalActionId,
1224
+ builder as unknown as StoredExternalActionBuilder<TParams, TState>,
1225
+ );
1226
+ return this;
1227
+ }
1228
+
1229
+ /** @internal */
1230
+ protected buildExternalActions():
1231
+ | Record<string, ProcessHumanTurnExternalActionSpec<TParams, TState>>
1232
+ | undefined {
1233
+ return this.externalActionBuilders.size > 0
1234
+ ? buildSpecs(this.externalActionBuilders)
1235
+ : undefined;
1236
+ }
1237
+ }
1238
+
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
+ );
1252
+ }
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>;
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> {
1298
+ /** @internal */
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;
1311
+ }
1167
1312
  private promptBuilder:
1168
1313
  | ((ctx: ProcessRuntimeTurnContext<TParams, TState>) => MaybePromise<string>)
1169
1314
  | null = null;
1170
- private branchType: LlmTurnDefinition<string, TParams, TState>["branchType"] = "primary";
1171
- private context: LlmTurnDefinition<string, TParams, TState>["context"] = "fresh";
1172
- private questionsEnabled = false;
1173
- private startFrom: LlmTurnDefinition<string, TParams, TState>["startFrom"] | undefined;
1174
- private restorePrimaryLeafAfterTurn: boolean | undefined;
1175
1315
  private readonly consumedProductNames = new Set<string>();
1176
1316
  private readonly optionalConsumedProductNames = new Set<string>();
1177
- private publishedResult: {
1178
- productName: string;
1179
- builder: PublishedResultBuilder<TParams, TState>;
1180
- } | null = null;
1181
- private endResult: LlmTurnEndBuilder<TParams, TState> | null = null;
1182
- private outcomeToolBuilders = new Map<string, OutcomeToolBuilder<TParams, TState>>();
1183
1317
 
1184
1318
  /** @internal */
1185
- get definition(): LlmTurnDefinition<string, TParams, TState> {
1186
- return this.buildDefinition();
1319
+ protected abstract itemContext(
1320
+ ctx: ProcessRuntimeTurnContext<TParams, TState>,
1321
+ ): LlmItemContext<TFamily>;
1322
+
1323
+ /** @public */
1324
+ executionPurpose(purpose: string): this {
1325
+ if (purpose) this.configuration.executionPurpose = purpose;
1326
+ else delete this.configuration.executionPurpose;
1327
+ return this;
1187
1328
  }
1188
1329
 
1189
1330
  /** @internal */
1190
1331
  modelPurpose(purpose: LlmModelPurpose): this {
1191
- this.modelPurposeValue = purpose;
1332
+ this.configuration.modelPurpose = purpose;
1192
1333
  return this;
1193
1334
  }
1194
1335
 
1195
1336
  /** @public */
1196
1337
  tools(...tools: readonly PiBuiltInToolName[]): this {
1197
- this.availableTools = tools;
1338
+ this.configuration.availableTools = tools;
1198
1339
  return this;
1199
1340
  }
1200
1341
 
1201
1342
  /** @public */
1202
1343
  integrationTools(...tools: readonly string[]): this {
1203
- 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;
1204
1346
  return this;
1205
1347
  }
1206
1348
 
1207
1349
  /** @public */
1208
1350
  resolveIntegrationTools(resolver: (params: TParams, state: TState) => readonly string[]): this {
1209
- this.integrationToolResolver = resolver;
1351
+ this.configuration.resolveIntegrationTools = resolver;
1210
1352
  return this;
1211
1353
  }
1212
1354
 
1213
1355
  /** @public */
1214
1356
  prepare<TNextPrepared>(
1215
- fn: (ctx: FlowLlmPreparationContext<TParams, TState>) => MaybePromise<TNextPrepared>,
1216
- ): LlmFlowBuilder<TParams, TState, TConsumedProducts, TNextPrepared> {
1217
- this.preparation = fn;
1218
- 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;
1219
1383
  }
1220
1384
 
1221
- /** Enable durable operator questions for this LLM turn. @public */
1222
- askQuestions(): this {
1223
- 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;
1224
1404
  return this;
1225
1405
  }
1226
1406
 
1227
1407
  /** @public */
1228
1408
  freshPrimary(): this {
1229
- this.branchType = "primary";
1230
- this.context = "fresh";
1231
- this.startFrom = undefined;
1232
- this.restorePrimaryLeafAfterTurn = undefined;
1409
+ this.configuration.branchType = "primary";
1410
+ this.configuration.context = "fresh";
1411
+ delete this.configuration.startFrom;
1412
+ delete this.configuration.restorePrimaryLeafAfterTurn;
1233
1413
  return this;
1234
1414
  }
1235
1415
 
1236
1416
  /** @internal */
1237
1417
  freshSeededPrimary(): this {
1238
- this.branchType = "primary";
1239
- this.context = "fresh_seeded";
1240
- this.startFrom = undefined;
1241
- this.restorePrimaryLeafAfterTurn = undefined;
1418
+ this.configuration.branchType = "primary";
1419
+ this.configuration.context = "fresh_seeded";
1420
+ delete this.configuration.startFrom;
1421
+ delete this.configuration.restorePrimaryLeafAfterTurn;
1242
1422
  return this;
1243
1423
  }
1244
1424
 
1245
1425
  /** @public */
1246
1426
  fullPrimary(): this {
1247
- this.branchType = "primary";
1248
- this.context = "full";
1427
+ this.configuration.branchType = "primary";
1428
+ this.configuration.context = "full";
1249
1429
  return this;
1250
1430
  }
1251
1431
 
1252
1432
  /** @internal */
1253
1433
  rootBranchReview(): this {
1254
- this.branchType = "root_branch";
1255
- this.context = "full";
1256
- this.restorePrimaryLeafAfterTurn = true;
1434
+ this.configuration.branchType = "root_branch";
1435
+ this.configuration.context = "full";
1436
+ this.configuration.restorePrimaryLeafAfterTurn = true;
1257
1437
  return this;
1258
1438
  }
1259
1439
 
1260
1440
  /** @public */
1261
1441
  continueFromPrimaryLeaf(): this {
1262
- this.startFrom = {
1442
+ this.configuration.startFrom = {
1263
1443
  kind: "semantic_ref",
1264
1444
  ref: "currentPrimaryPathLeaf",
1265
1445
  fallback: { kind: "current_leaf" },
@@ -1269,7 +1449,7 @@ export class LlmFlowBuilder<
1269
1449
 
1270
1450
  /** @internal */
1271
1451
  continueFromReviewBranch(): this {
1272
- this.startFrom = {
1452
+ this.configuration.startFrom = {
1273
1453
  kind: "semantic_ref",
1274
1454
  ref: "review",
1275
1455
  fallback: { kind: "current_leaf" },
@@ -1287,7 +1467,7 @@ export class LlmFlowBuilder<
1287
1467
 
1288
1468
  /** @internal */
1289
1469
  startFromReviewBranch(): this {
1290
- this.startFrom = {
1470
+ this.configuration.startFrom = {
1291
1471
  kind: "semantic_ref",
1292
1472
  ref: "review",
1293
1473
  fallback: { kind: "session_root" },
@@ -1300,7 +1480,7 @@ export class LlmFlowBuilder<
1300
1480
  productName: string,
1301
1481
  fallback: ProcessTurnStartSelection = { kind: "session_root" },
1302
1482
  ): this {
1303
- this.startFrom = {
1483
+ this.configuration.startFrom = {
1304
1484
  kind: "product_ref",
1305
1485
  productName: normalizeProductName(productName),
1306
1486
  fallback,
@@ -1310,36 +1490,124 @@ export class LlmFlowBuilder<
1310
1490
 
1311
1491
  /** @internal */
1312
1492
  startFromRoot(): this {
1313
- this.startFrom = { kind: "session_root" };
1493
+ this.configuration.startFrom = { kind: "session_root" };
1314
1494
  return this;
1315
1495
  }
1316
1496
 
1317
1497
  /** @public */
1318
1498
  consume<TProductName extends string>(
1319
1499
  productName: TProductName,
1320
- ): LlmFlowBuilder<TParams, TState, TConsumedProducts | TProductName, TPrepared> {
1500
+ ): ConfiguredLlmBuilder<TFamily, TParams, TState, TConsumedProducts | TProductName, TPrepared> {
1321
1501
  this.consumedProductNames.add(normalizeProductName(productName));
1322
- return this as unknown as LlmFlowBuilder<
1323
- TParams,
1324
- TState,
1325
- TConsumedProducts | TProductName,
1326
- TPrepared
1327
- >;
1502
+ return this.refineContext<TConsumedProducts | TProductName, TPrepared>();
1328
1503
  }
1329
1504
 
1330
1505
  /** @public */
1331
1506
  optionalConsume<TProductName extends string>(
1332
1507
  productName: TProductName,
1333
- ): LlmFlowBuilder<TParams, TState, TConsumedProducts | TProductName, TPrepared> {
1508
+ ): ConfiguredLlmBuilder<TFamily, TParams, TState, TConsumedProducts | TProductName, TPrepared> {
1334
1509
  this.optionalConsumedProductNames.add(normalizeProductName(productName));
1335
- 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,
1336
1520
  TParams,
1337
1521
  TState,
1338
- TConsumedProducts | TProductName,
1339
- TPrepared
1522
+ TNextConsumedProducts,
1523
+ TNextPrepared
1340
1524
  >;
1341
1525
  }
1342
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
+
1343
1611
  /** @public */
1344
1612
  publish(productName: string): PublishedResultBuilder<TParams, TState> {
1345
1613
  const normalized = normalizeProductName(productName);
@@ -1369,23 +1637,6 @@ export class LlmFlowBuilder<
1369
1637
  return this.endResult;
1370
1638
  }
1371
1639
 
1372
- /** @public */
1373
- buildPrompt(fn: LlmPromptBuilder<TParams, TState, TConsumedProducts, TPrepared>): this {
1374
- this.promptBuilder = (ctx) =>
1375
- fn(
1376
- createFlowPromptContext(ctx, [...this.consumedProductNames] as TConsumedProducts[], [
1377
- ...this.optionalConsumedProductNames,
1378
- ]),
1379
- );
1380
- return this;
1381
- }
1382
-
1383
- /** @public */
1384
- prompt(prompt: (ctx: ProcessRuntimeTurnContext<TParams, TState>) => MaybePromise<string>): this {
1385
- this.promptBuilder = prompt;
1386
- return this;
1387
- }
1388
-
1389
1640
  /** @public */
1390
1641
  outcomeTool(
1391
1642
  id: string,
@@ -1411,44 +1662,6 @@ export class LlmFlowBuilder<
1411
1662
  return this;
1412
1663
  }
1413
1664
 
1414
- private buildBaseDefinition() {
1415
- if (!this.turnDescription) {
1416
- throw new Error(`LLM turn '${this.turnId}' must declare .description(...)`);
1417
- }
1418
- const prompt = this.promptBuilder;
1419
- if (!prompt) {
1420
- throw new Error(`LLM turn '${this.turnId}' must declare .buildPrompt(...)`);
1421
- }
1422
- const preparation = this.preparation;
1423
- return {
1424
- kind: "llm" as const,
1425
- description: this.turnDescription,
1426
- ...(this.modelPurposeValue ? { modelPurpose: this.modelPurposeValue } : {}),
1427
- availableTools: this.availableTools,
1428
- ...(this.availableIntegrationTools.length > 0
1429
- ? { integrationTools: this.availableIntegrationTools }
1430
- : {}),
1431
- ...(this.integrationToolResolver
1432
- ? { resolveIntegrationTools: this.integrationToolResolver }
1433
- : {}),
1434
- ...(this.questionsEnabled ? { askQuestions: true as const } : {}),
1435
- ...(preparation
1436
- ? {
1437
- prepare: (ctx: ProcessRuntimeTurnContext<TParams, TState>) =>
1438
- preparation(createFlowAutomaticRunContext(ctx)),
1439
- }
1440
- : {}),
1441
- completionMode: "turn_end" as const,
1442
- branchType: this.branchType,
1443
- context: this.context,
1444
- ...(this.startFrom ? { startFrom: this.startFrom } : {}),
1445
- ...(this.restorePrimaryLeafAfterTurn !== undefined
1446
- ? { restorePrimaryLeafAfterTurn: this.restorePrimaryLeafAfterTurn }
1447
- : {}),
1448
- prompt,
1449
- };
1450
- }
1451
-
1452
1665
  /** @internal */
1453
1666
  producesPlan(
1454
1667
  configure: (plan: PlanResultBuilder<TParams, TState>) => PlanResultBuilder<TParams, TState>,
@@ -1470,22 +1683,20 @@ export class LlmFlowBuilder<
1470
1683
  };
1471
1684
  }
1472
1685
 
1473
- private buildDefinition(): LlmTurnDefinition<string, TParams, TState> {
1686
+ /** @internal */
1687
+ get definition(): LlmTurnDefinition<string, TParams, TState> {
1474
1688
  const definition = this.buildBaseDefinition();
1475
- const hasOutcomeTools = this.outcomeToolBuilders.size > 0;
1476
1689
  const explicitTurnEnd = this.endResult;
1477
1690
  const published = this.publishedResult;
1478
- const outcomes: Record<string, ProcessToolOutcomeSpec<TParams, TState>> = {};
1479
- for (const [outcomeId, builder] of this.outcomeToolBuilders) {
1480
- outcomes[outcomeId] = builder.build();
1481
- }
1691
+ const outcomes = buildSpecs(this.outcomeToolBuilders);
1692
+ const hasOutcomeTools = Object.keys(outcomes).length > 0;
1482
1693
  const outcomePublishedProducts = new Set(
1483
1694
  Object.values(outcomes)
1484
1695
  .map((outcome) => outcome.publishedProduct)
1485
1696
  .filter((productName): productName is string => typeof productName === "string"),
1486
1697
  );
1487
1698
  const hasOutcomePublishedProduct = outcomePublishedProducts.size > 0;
1488
- let turnEnd: ProcessTurnEndSpec<TParams, TState, string> | undefined;
1699
+ let turnEnd = explicitTurnEnd?.build();
1489
1700
  let resultSemanticRef: "plan" | "review" | undefined = outcomePublishedProducts.has("review")
1490
1701
  ? "review"
1491
1702
  : outcomePublishedProducts.has("plan")
@@ -1496,120 +1707,284 @@ export class LlmFlowBuilder<
1496
1707
 
1497
1708
  if (published) {
1498
1709
  publishedProduct = published.productName;
1499
- if (published.productName === "plan") {
1500
- resultSemanticRef = "plan";
1501
- }
1502
- if (published.productName === "review") {
1503
- resultSemanticRef = "review";
1710
+ if (published.productName === "plan" || published.productName === "review") {
1711
+ resultSemanticRef = published.productName;
1504
1712
  }
1505
1713
  const publishHasRoute = published.builder.hasRoute();
1506
- if (publishHasRoute && hasOutcomeTools) {
1507
- throw new Error(
1508
- `LLM turn '${this.turnId}' cannot route published product '${published.productName}' and declare outcome tools in flow v1`,
1509
- );
1510
- }
1511
- if (publishHasRoute && !hasOutcomeTools) {
1512
- turnResultMarkdown = ASSISTANT_OUTPUT_TURN_RESULT;
1513
- turnEnd = published.builder.buildTurnEnd();
1514
- }
1515
- if (!publishHasRoute && hasOutcomeTools) {
1516
- turnResultMarkdown = OUTCOME_TOOL_ARGUMENT_TURN_RESULT;
1517
- }
1518
- if (!publishHasRoute && !hasOutcomeTools) {
1714
+ if (publishHasRoute === hasOutcomeTools) {
1519
1715
  throw new Error(
1520
- `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`,
1521
1719
  );
1522
1720
  }
1721
+ turnResultMarkdown = publishHasRoute
1722
+ ? ASSISTANT_OUTPUT_TURN_RESULT
1723
+ : OUTCOME_TOOL_ARGUMENT_TURN_RESULT;
1724
+ if (publishHasRoute) turnEnd = published.builder.buildTurnEnd();
1523
1725
  } else if (hasOutcomeTools && !hasOutcomePublishedProduct) {
1524
1726
  turnResultMarkdown = OUTCOME_TOOL_ARGUMENT_TURN_RESULT;
1525
1727
  } else if (explicitTurnEnd) {
1526
1728
  turnResultMarkdown = ASSISTANT_OUTPUT_TURN_RESULT;
1527
1729
  }
1528
1730
 
1529
- if (hasOutcomeTools) {
1530
- for (const [outcomeId, outcome] of Object.entries(outcomes)) {
1531
- if (OUTCOME_TOOL_MARKDOWN_PARAMETER_NAME in outcome.parameters) {
1532
- throw new Error(
1533
- `LLM turn '${this.turnId}' outcome tool '${outcomeId}' cannot declare reserved markdown parameter '${OUTCOME_TOOL_MARKDOWN_PARAMETER_NAME}'`,
1534
- );
1535
- }
1536
- }
1537
- }
1731
+ assertLlmOutcomeParameters(this.turnId, outcomes);
1538
1732
 
1539
- if (explicitTurnEnd) {
1540
- if (turnEnd || Object.keys(outcomes).length > 0) {
1541
- throw new Error(`LLM turn '${this.turnId}' cannot declare multiple completion paths`);
1542
- }
1543
- turnEnd = explicitTurnEnd.build();
1733
+ if (explicitTurnEnd && hasOutcomeTools) {
1734
+ throw new Error(`LLM turn '${this.turnId}' cannot declare multiple completion paths`);
1544
1735
  }
1545
- if (Object.keys(outcomes).length === 0 && !turnEnd) {
1736
+ if (!hasOutcomeTools && !turnEnd) {
1546
1737
  throw new Error(`LLM turn '${this.turnId}' must declare a completion path`);
1547
1738
  }
1548
1739
 
1549
1740
  return {
1550
1741
  ...definition,
1551
- ...(Object.keys(outcomes).length > 0 ? { outcomes } : {}),
1742
+ ...(hasOutcomeTools ? { outcomes } : {}),
1552
1743
  ...(turnEnd ? { turnEnd } : {}),
1553
1744
  ...(turnResultMarkdown ? { turnResultMarkdown } : {}),
1554
1745
  ...(resultSemanticRef ? { resultSemanticRef } : {}),
1555
1746
  ...(publishedProduct ? { publishedProduct } : {}),
1556
- ...(this.consumedProductNames.size > 0
1557
- ? { consumedProducts: [...this.consumedProductNames] }
1558
- : {}),
1559
- ...(this.optionalConsumedProductNames.size > 0
1560
- ? { optionalConsumedProducts: [...this.optionalConsumedProductNames] }
1561
- : {}),
1562
1747
  };
1563
1748
  }
1564
1749
  }
1565
1750
 
1566
- type StoredExternalActionBuilder<TParams, TState> = ExternalActionBuilder<
1751
+ /** Item selection for `flow.mappedLlm(...)`. @public */
1752
+ export type FlowForEachOptions<TParams, TState, TItem, TResult> = Pick<
1753
+ MappedLlmTurnSpec<TParams, TState, TItem, TResult>,
1754
+ "items" | "itemCodec" | "resultCodec" | "key" | "label" | "stateAfterSnapshot"
1755
+ >;
1756
+
1757
+ /** @public */
1758
+ export type FlowMappedPromptContext<
1567
1759
  TParams,
1568
1760
  TState,
1569
- unknown,
1570
- Record<string, unknown>
1571
- >;
1761
+ TItem,
1762
+ TConsumedProducts extends string,
1763
+ TPrepared,
1764
+ > = FlowPromptContext<TParams, TState, TConsumedProducts, TPrepared> & MappedTurnItemContext<TItem>;
1572
1765
 
1573
1766
  /** @public */
1574
- abstract class ExternalActionTurnBuilder<TParams, TState> extends DescribedTurnBuilder {
1767
+ export type FlowMappedPreparationContext<TParams, TState, TItem> = FlowLlmPreparationContext<
1768
+ TParams,
1769
+ TState
1770
+ > &
1771
+ MappedTurnItemContext<TItem>;
1772
+
1773
+ /**
1774
+ * Outcome of one mapped item. It declares parameters and yields the item's
1775
+ * result; it cannot route, change process state, or publish products.
1776
+ * @public
1777
+ */
1778
+ export class MappedOutcomeBuilder<
1779
+ TParams = unknown,
1780
+ TState = unknown,
1781
+ TItem = unknown,
1782
+ TResult = unknown,
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>);
1792
+ return this;
1793
+ }
1794
+ private yieldResult: MappedItemYield<TParams, TState, TItem, TResult> | null = null;
1795
+
1796
+ /** Map this outcome to the item's typed result. @public */
1797
+ yield(fn: MappedItemYield<TParams, TState, TItem, TResult>): this {
1798
+ this.yieldResult = fn;
1799
+ return this;
1800
+ }
1801
+
1575
1802
  /** @internal */
1576
- protected abstract readonly turnKind: "Automatic" | "Human";
1577
- private externalActionBuilders = new Map<string, StoredExternalActionBuilder<TParams, TState>>();
1803
+ build(): {
1804
+ /** @internal */
1805
+ tool: ProcessToolOutcomeSpec<TParams, TState>;
1806
+ /** @internal */
1807
+ yieldResult: MappedItemYield<TParams, TState, TItem, TResult>;
1808
+ } {
1809
+ if (!this.yieldResult) {
1810
+ throw new Error("Mapped outcome must declare .yield(...)");
1811
+ }
1812
+ return { tool: this.buildParameterSpec("Mapped outcome tool"), yieldResult: this.yieldResult };
1813
+ }
1814
+ }
1815
+
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
+ {
1820
+ /** @internal */
1821
+ constructor(
1822
+ private readonly turn: FlowLlmTurn<TParams, TState, string>,
1823
+ private readonly setRouting: (routing: MappedCollectRouting<TParams, TState>) => void,
1824
+ ) {}
1825
+
1826
+ /** @internal */
1827
+ get id(): TurnId {
1828
+ return this.turn.id;
1829
+ }
1830
+
1831
+ /** @internal */
1832
+ get definition(): LlmTurnDefinition<string, TParams, TState> {
1833
+ return this.turn.definition;
1834
+ }
1578
1835
 
1579
1836
  /** @public */
1580
- externalAction<
1581
- TEvent = unknown,
1582
- TInput extends Record<string, unknown> = Record<string, unknown>,
1583
- >(
1584
- externalActionId: string,
1585
- source: ExternalActionSource<TParams, TState, TEvent, TInput>,
1837
+ to(turnId: TurnId): this {
1838
+ this.setRouting({ kind: "static", to: turnId });
1839
+ return this;
1840
+ }
1841
+
1842
+ /** @public */
1843
+ complete(): this {
1844
+ this.setRouting({ kind: "static", lifecycleStatus: "completed" });
1845
+ return this;
1846
+ }
1847
+
1848
+ /** @public */
1849
+ lifecycleStatus(status: ProcessTurnTerminalLifecycleStatus): this {
1850
+ this.setRouting({ kind: "static", lifecycleStatus: status });
1851
+ return this;
1852
+ }
1853
+
1854
+ /** Choose the next turn from the collected state. @public */
1855
+ routeByState(
1856
+ branches: Record<string, TurnId>,
1857
+ choose: (ctx: MappedTurnServerContext<TParams, TState>) => MaybePromise<string>,
1858
+ ): this {
1859
+ if (Object.keys(branches).length === 0) {
1860
+ throw new Error("Mapped collection routing must declare at least one branch");
1861
+ }
1862
+ this.setRouting({ kind: "branches", branches: { ...branches }, choose });
1863
+ return this;
1864
+ }
1865
+ }
1866
+
1867
+ /**
1868
+ * LLM turn that runs once per frozen item. Business state and routing belong
1869
+ * to `.collect(...)`.
1870
+ * @public
1871
+ */
1872
+ export class 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<
1881
+ TParams,
1882
+ TState,
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;
1895
+
1896
+ /** @internal */
1897
+ constructor(
1898
+ turnId: TurnId,
1899
+ private readonly items: FlowForEachOptions<TParams, TState, TItem, TResult>,
1900
+ ) {
1901
+ super(turnId);
1902
+ }
1903
+
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
+ };
1919
+ }
1920
+
1921
+ /** @public */
1922
+ outcomeTool(
1923
+ id: string,
1586
1924
  configure: (
1587
- external: ExternalActionBuilder<TParams, TState, TEvent, TInput>,
1588
- ) => ExternalActionBuilder<TParams, TState, TEvent, TInput> | undefined,
1925
+ outcome: MappedOutcomeBuilder<TParams, TState, TItem, TResult>,
1926
+ ) => MappedOutcomeBuilder<TParams, TState, TItem, TResult> | undefined,
1589
1927
  ): this {
1590
- if (this.externalActionBuilders.has(externalActionId)) {
1591
- throw new Error(
1592
- `${this.turnKind} turn '${this.turnId}' declares duplicate external action '${externalActionId}'`,
1593
- );
1928
+ if (id.trim() === "") {
1929
+ throw new Error(`LLM turn '${this.turnId}' declares an empty outcome tool id`);
1594
1930
  }
1595
- const builder = new ExternalActionBuilder(externalActionId, source);
1596
- configure(builder);
1597
- this.externalActionBuilders.set(
1598
- externalActionId,
1599
- builder as unknown as StoredExternalActionBuilder<TParams, TState>,
1600
- );
1931
+ if (this.outcomes.has(id)) {
1932
+ throw new Error(`LLM turn '${this.turnId}' declares duplicate outcome tool '${id}'`);
1933
+ }
1934
+ const outcome = new MappedOutcomeBuilder<TParams, TState, TItem, TResult>();
1935
+ configure(outcome);
1936
+ outcome.build();
1937
+ this.outcomes.set(id, outcome);
1601
1938
  return this;
1602
1939
  }
1603
1940
 
1941
+ /** Combine ordered item results into process state, once. @public */
1942
+ collect(fn: MappedCollect<TParams, TState, TResult>): MappedCollectBuilder<TParams, TState> {
1943
+ if (this.collection) {
1944
+ throw new Error(`Mapped turn '${this.turnId}' declares .collect(...) more than once`);
1945
+ }
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
+ });
1953
+ }
1954
+
1604
1955
  /** @internal */
1605
- protected buildExternalActions():
1606
- | Record<string, ProcessHumanTurnExternalActionSpec<TParams, TState>>
1607
- | undefined {
1608
- return this.externalActionBuilders.size > 0
1609
- ? Object.fromEntries(
1610
- [...this.externalActionBuilders].map(([id, builder]) => [id, builder.build()]),
1611
- )
1612
- : 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
+ };
1613
1988
  }
1614
1989
  }
1615
1990
 
@@ -1625,10 +2000,12 @@ export class AutomaticFlowBuilder<TParams = unknown, TState = unknown>
1625
2000
  | null = null;
1626
2001
  private outcomeBuilders = new Map<string, AutomaticOutcomeBuilder<TParams, TState>>();
1627
2002
  private availableIntegrationTools: readonly string[] = [];
1628
-
1629
- /** @internal */
1630
- get definition(): AutomaticTurnDefinition<string, TParams, TState> {
1631
- 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;
1632
2009
  }
1633
2010
 
1634
2011
  /** @public */
@@ -1666,7 +2043,8 @@ export class AutomaticFlowBuilder<TParams = unknown, TState = unknown>
1666
2043
  return this;
1667
2044
  }
1668
2045
 
1669
- private buildDefinition(): AutomaticTurnDefinition<string, TParams, TState> {
2046
+ /** @internal */
2047
+ get definition(): AutomaticTurnDefinition<string, TParams, TState> {
1670
2048
  if (!this.turnDescription) {
1671
2049
  throw new Error(`Automatic turn '${this.turnId}' must declare .description(...)`);
1672
2050
  }
@@ -1676,15 +2054,13 @@ export class AutomaticFlowBuilder<TParams = unknown, TState = unknown>
1676
2054
  if (this.outcomeBuilders.size === 0) {
1677
2055
  throw new Error(`Automatic turn '${this.turnId}' must declare at least one outcome`);
1678
2056
  }
1679
- const outcomes: Record<string, ProcessToolOutcomeSpec<TParams, TState>> = {};
1680
- for (const [outcomeId, builder] of this.outcomeBuilders) {
1681
- outcomes[outcomeId] = builder.build();
1682
- }
2057
+ const outcomes = buildSpecs(this.outcomeBuilders);
1683
2058
  const runFn = this.runFn;
1684
2059
  const externalActions = this.buildExternalActions();
1685
2060
  return {
1686
2061
  kind: "automatic",
1687
2062
  description: this.turnDescription,
2063
+ ...(this.waitPredicate ? { waitFor: this.waitPredicate } : {}),
1688
2064
  ...(this.availableIntegrationTools.length > 0
1689
2065
  ? { integrationTools: this.availableIntegrationTools }
1690
2066
  : {}),
@@ -1871,11 +2247,10 @@ export class HumanFlowBuilder<TParams = unknown, TState = unknown>
1871
2247
  {
1872
2248
  /** @internal */
1873
2249
  protected readonly turnKind = "Human";
1874
- private reviewProductName: string | undefined;
1875
- private reviewSemanticRef: ProcessSemanticEntryRefKey | undefined;
1876
- private operatorAttentionValue: HumanTurnOperatorAttention | undefined;
1877
- private turnCommentary: string | undefined;
1878
- private notes: HumanTurnDefinition<TParams, TState>["notesFields"] | undefined;
2250
+ private readonly metadata: Omit<
2251
+ HumanTurnDefinition<TParams, TState>,
2252
+ "kind" | "description" | "actions" | "externalActions"
2253
+ > = {};
1879
2254
  private actions = new Map<string, HumanActionBuilder<TParams, TState>>();
1880
2255
 
1881
2256
  /** @public */
@@ -1887,42 +2262,38 @@ export class HumanFlowBuilder<TParams = unknown, TState = unknown>
1887
2262
  return {
1888
2263
  kind: "human",
1889
2264
  description: this.turnDescription,
1890
- ...(this.reviewProductName ? { reviewProduct: this.reviewProductName } : {}),
1891
- ...(this.reviewSemanticRef ? { reviewSemanticRef: this.reviewSemanticRef } : {}),
1892
- ...(this.operatorAttentionValue ? { operatorAttention: this.operatorAttentionValue } : {}),
1893
- ...(this.notes ? { notesFields: this.notes } : {}),
1894
- ...(this.turnCommentary ? { commentary: this.turnCommentary } : {}),
1895
- actions: Object.fromEntries(
1896
- [...this.actions.entries()].map(([actionId, builder]) => [actionId, builder.build()]),
1897
- ),
2265
+ ...this.metadata,
2266
+ actions: buildSpecs(this.actions),
1898
2267
  ...(externalActions ? { externalActions } : {}),
1899
2268
  };
1900
2269
  }
1901
2270
 
1902
2271
  /** @public */
1903
2272
  reviewProduct(productName: string): this {
1904
- const normalized = normalizeProductName(productName);
1905
- this.reviewProductName = normalized;
1906
- this.reviewSemanticRef =
1907
- 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;
1908
2277
  return this;
1909
2278
  }
1910
2279
 
1911
2280
  /** @public */
1912
2281
  operatorAttention(attention: HumanTurnOperatorAttention): this {
1913
- this.operatorAttentionValue = attention;
2282
+ this.metadata.operatorAttention = attention;
1914
2283
  return this;
1915
2284
  }
1916
2285
 
1917
2286
  /** @internal */
1918
2287
  commentary(commentary: string): this {
1919
- this.turnCommentary = commentary;
2288
+ if (commentary) this.metadata.commentary = commentary;
2289
+ else delete this.metadata.commentary;
1920
2290
  return this;
1921
2291
  }
1922
2292
 
1923
2293
  /** @internal */
1924
2294
  notesFields(notes: HumanTurnDefinition<TParams, TState>["notesFields"]): this {
1925
- this.notes = notes;
2295
+ if (notes) this.metadata.notesFields = notes;
2296
+ else delete this.metadata.notesFields;
1926
2297
  return this;
1927
2298
  }
1928
2299
 
@@ -1979,17 +2350,17 @@ export class ExternalRouteBuilder<
1979
2350
 
1980
2351
  /** @public */
1981
2352
  to(turnId: TurnId): this {
1982
- return this.setTarget({ kind: "to", turnId });
2353
+ return this.setTarget({ to: turnId });
1983
2354
  }
1984
2355
 
1985
2356
  /** @internal */
1986
2357
  complete(): this {
1987
- return this.setTarget({ kind: "complete" });
2358
+ return this.setTarget({ complete: true });
1988
2359
  }
1989
2360
 
1990
2361
  /** @internal */
1991
2362
  lifecycleStatus(status: ProcessTurnTerminalLifecycleStatus): this {
1992
- return this.setTarget({ kind: "lifecycleStatus", status });
2363
+ return this.setTarget({ lifecycleStatus: status });
1993
2364
  }
1994
2365
 
1995
2366
  /** @internal */
@@ -2029,7 +2400,7 @@ export class ExternalRouteBuilder<
2029
2400
  return {
2030
2401
  /** @internal */
2031
2402
  source: this.source,
2032
- ...buildRouteTargetSpec(this.target),
2403
+ ...this.target,
2033
2404
  ...(this.externalEffect
2034
2405
  ? {
2035
2406
  /** @internal */
@@ -2173,21 +2544,8 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2173
2544
  TState
2174
2545
  > {
2175
2546
  private readonly processId: string;
2176
- private processDisplayName: string | null = null;
2177
- private entryTurnId: TurnId | null = null;
2547
+ private readonly configuration: Partial<DefinedProcessInput<TParams, TState>> = {};
2178
2548
  private readonly alternateEntryTurnIds: TurnId[] = [];
2179
- private happyPathTurnIds: readonly TurnId[] | null = null;
2180
- private paramsCodec: Codec<TParams> | null = null;
2181
- private stateCodec: Codec<TState> | null = null;
2182
- private initialStateFn: ((params: TParams) => TState) | null = null;
2183
- private repositoryCredentialsFn: ExtensionProcessDefinition<
2184
- TParams,
2185
- TState
2186
- >["repositoryCredentials"];
2187
- private storageSizeResolver: ExtensionProcessDefinition<TParams, TState>["resolveStorageSize"];
2188
- private processPiConfig: ProcessPiConfig | undefined;
2189
- private developmentTools = false;
2190
- private docker = false;
2191
2549
 
2192
2550
  /** @internal */
2193
2551
  constructor(processId: string) {
@@ -2200,13 +2558,13 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2200
2558
 
2201
2559
  /** @public */
2202
2560
  displayName(displayName: string): this {
2203
- this.processDisplayName = displayName;
2561
+ this.configuration.displayName = displayName;
2204
2562
  return this;
2205
2563
  }
2206
2564
 
2207
2565
  /** @public */
2208
2566
  entry(turnId: TurnId): this {
2209
- this.entryTurnId = turnId;
2567
+ this.configuration.entry = turnId;
2210
2568
  return this;
2211
2569
  }
2212
2570
 
@@ -2223,7 +2581,7 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2223
2581
  */
2224
2582
  /** @public */
2225
2583
  happyPath(...turnIds: readonly TurnId[]): this {
2226
- this.happyPathTurnIds = turnIds;
2584
+ this.configuration.happyPath = turnIds;
2227
2585
  return this;
2228
2586
  }
2229
2587
 
@@ -2234,14 +2592,14 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2234
2592
  /** @public */
2235
2593
  state: Codec<TState>;
2236
2594
  }): this {
2237
- this.paramsCodec = input.params;
2238
- this.stateCodec = input.state;
2595
+ this.configuration.paramsCodec = input.params;
2596
+ this.configuration.stateCodec = input.state;
2239
2597
  return this;
2240
2598
  }
2241
2599
 
2242
2600
  /** @public */
2243
2601
  initialState(fn: (params: TParams) => TState): this {
2244
- this.initialStateFn = fn;
2602
+ this.configuration.initialState = fn;
2245
2603
  return this;
2246
2604
  }
2247
2605
 
@@ -2249,7 +2607,7 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2249
2607
  repositoryCredentials(
2250
2608
  fn: NonNullable<ExtensionProcessDefinition<TParams, TState>["repositoryCredentials"]>,
2251
2609
  ): this {
2252
- this.repositoryCredentialsFn = fn;
2610
+ this.configuration.repositoryCredentials = fn;
2253
2611
  return this;
2254
2612
  }
2255
2613
 
@@ -2257,13 +2615,13 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2257
2615
  resolveStorageSize(
2258
2616
  fn: NonNullable<ExtensionProcessDefinition<TParams, TState>["resolveStorageSize"]>,
2259
2617
  ): this {
2260
- this.storageSizeResolver = fn;
2618
+ this.configuration.resolveStorageSize = fn;
2261
2619
  return this;
2262
2620
  }
2263
2621
 
2264
2622
  /** @public */
2265
2623
  piConfig(config: ProcessPiConfig): this {
2266
- this.processPiConfig = config;
2624
+ this.configuration.piConfig = config;
2267
2625
  return this;
2268
2626
  }
2269
2627
 
@@ -2273,9 +2631,18 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2273
2631
  developmentTools?: boolean;
2274
2632
  /** @public */
2275
2633
  docker?: boolean;
2634
+ /** @internal */
2635
+ repositoryCheckout?: "eager" | "on_demand" | "none";
2276
2636
  }): this {
2277
- this.developmentTools = capabilities.developmentTools === true;
2278
- 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;
2279
2646
  return this;
2280
2647
  }
2281
2648
 
@@ -2291,16 +2658,17 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2291
2658
 
2292
2659
  /** @public */
2293
2660
  define(): ExtensionProcessDefinition<TParams, TState> {
2294
- if (!this.processDisplayName) {
2661
+ const { displayName, entry, paramsCodec, stateCodec, initialState } = this.configuration;
2662
+ if (!displayName) {
2295
2663
  throw new Error(`Flow process '${this.processId}' must declare .displayName(...)`);
2296
2664
  }
2297
- if (!this.entryTurnId) {
2665
+ if (!entry) {
2298
2666
  throw new Error(`Flow process '${this.processId}' must declare .entry(turnId)`);
2299
2667
  }
2300
- if (!this.paramsCodec || !this.stateCodec) {
2668
+ if (!paramsCodec || !stateCodec) {
2301
2669
  throw new Error(`Flow process '${this.processId}' must declare .codecs(...)`);
2302
2670
  }
2303
- if (!this.initialStateFn) {
2671
+ if (!initialState) {
2304
2672
  throw new Error(`Flow process '${this.processId}' must declare .initialState(...)`);
2305
2673
  }
2306
2674
 
@@ -2313,42 +2681,23 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2313
2681
  }
2314
2682
 
2315
2683
  const input: DefinedProcessInput<TParams, TState> = {
2684
+ ...this.configuration,
2316
2685
  id: this.processId,
2317
- displayName: this.processDisplayName,
2318
- entry: this.entryTurnId,
2686
+ displayName,
2687
+ entry,
2319
2688
  ...(this.alternateEntryTurnIds.length > 0
2320
2689
  ? { alternateEntries: [...this.alternateEntryTurnIds] }
2321
2690
  : {}),
2322
- ...(this.happyPathTurnIds ? { happyPath: [...this.happyPathTurnIds] } : {}),
2323
- paramsCodec: this.paramsCodec,
2324
- stateCodec: this.stateCodec,
2325
- initialState: this.initialStateFn,
2326
- ...(this.developmentTools || this.docker
2327
- ? {
2328
- runtime: {
2329
- ...(this.developmentTools ? { developmentTools: true } : {}),
2330
- ...(this.docker ? { docker: true } : {}),
2331
- },
2332
- }
2333
- : {}),
2334
- ...(this.repositoryCredentialsFn
2335
- ? { repositoryCredentials: this.repositoryCredentialsFn }
2336
- : {}),
2337
- ...(this.storageSizeResolver ? { resolveStorageSize: this.storageSizeResolver } : {}),
2338
- ...(this.processPiConfig ? { piConfig: this.processPiConfig } : {}),
2691
+ paramsCodec,
2692
+ stateCodec,
2693
+ initialState,
2339
2694
  turns,
2340
2695
  ...(this.serverHooks.length > 0 ? { server: chainHooks(this.serverHooks) } : {}),
2341
2696
  ...(this.uiHooks.length > 0 ? { ui: chainHooks(this.uiHooks) } : {}),
2342
2697
  ...(this.launcherHooks.length > 0 ? { launchers: chainHooks(this.launcherHooks) } : {}),
2343
2698
  ...(this.watcherHooks.length > 0 ? { watchers: chainHooks(this.watcherHooks) } : {}),
2344
2699
  };
2345
- const process = defineProcess(input);
2346
- const errors = validateProcessGraphProducts(
2347
- toProcessGraphView(process as unknown as ProcessGraphSource),
2348
- );
2349
- if (errors.length > 0)
2350
- throw new Error(`Flow process '${this.processId}': ${errors.join("; ")}`);
2351
- return process;
2700
+ return defineProcess(input);
2352
2701
  }
2353
2702
  }
2354
2703
 
@@ -2358,6 +2707,13 @@ export const flow = {
2358
2707
  llm<TParams = unknown, TState = unknown>(turnId: TurnId): LlmFlowBuilder<TParams, TState> {
2359
2708
  return new LlmFlowBuilder<TParams, TState>(turnId);
2360
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
+ },
2361
2717
  /** @public */
2362
2718
  automatic<TParams = unknown, TState = unknown>(
2363
2719
  turnId: TurnId,