@leitwerk-dev/process-sdk 0.3.1 → 0.4.1

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 +63 -2
  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 +4387 -4313
  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 +25 -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 +87 -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 +746 -815
  52. package/src/index.ts +48 -1
  53. package/src/mapped-turn.ts +74 -23
  54. package/src/outcome-contract.ts +119 -0
  55. package/src/outcome-schema.ts +315 -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 +85 -193
  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,14 @@ 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 { snakeCase } from "./outcome-schema.js";
66
+ import type { TurnWaitPredicate } from "./turn-wait.js";
67
+ import type {
68
+ OutcomeToolArrayItemSpec,
69
+ OutcomeToolParameterSpec,
70
+ PiBuiltInToolName,
71
+ ProcessPiConfig,
72
+ } from "./types.js";
64
73
 
65
74
  /** @public */
66
75
  type MaybePromise<T> = T | Promise<T>;
@@ -214,6 +223,8 @@ export type FlowPromptContext<
214
223
 
215
224
  /** @public */
216
225
  export interface FlowAutomaticRunContext<TParams = unknown, TState = unknown> {
226
+ /** Immutable non-secret settings captured for this turn. @public */
227
+ readonly scopedSettings?: ScopedSettingsSnapshot;
217
228
  /** @public */
218
229
  process: ProcessInstance;
219
230
  /** @public */
@@ -230,6 +241,15 @@ export interface FlowAutomaticRunContext<TParams = unknown, TState = unknown> {
230
241
  callIntegrationTool(name: string, args: Record<string, unknown>): Promise<unknown>;
231
242
  /** @public */
232
243
  reportProgress(report: TurnProgressReport): void;
244
+ /** Append a non-secret worker diagnostic for this turn attempt. @internal */
245
+ reportDiagnostic(report: TurnDiagnosticReport): void;
246
+ }
247
+
248
+ /** Worker context for correcting a submission before accepting it. @public */
249
+ export interface FlowOutcomeValidationContext<TParams = unknown, TState = unknown>
250
+ extends FlowAutomaticRunContext<TParams, TState> {
251
+ /** Preparation captured before prompting. @public */
252
+ prepared?: unknown;
233
253
  }
234
254
 
235
255
  /** @public */
@@ -293,49 +313,11 @@ type FlowOutcomeStateEffect<TParams, TState, TContext> = (
293
313
  input: FlowOutcomeEffectInput<TParams, TState, TContext>,
294
314
  ) => MaybePromise<TState>;
295
315
 
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
316
  function normalizeProductName(productName: string): string {
326
317
  assertValidProcessProductName(productName);
327
318
  return productName;
328
319
  }
329
320
 
330
- function toRequiredErrorCode(name: string): string {
331
- const snake = name
332
- .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
333
- .replace(/[^a-zA-Z0-9]+/g, "_")
334
- .replace(/^_+|_+$/g, "")
335
- .toLowerCase();
336
- return `${snake || "value"}_required`;
337
- }
338
-
339
321
  function readInitialPrompt<TParams>(params: TParams): string {
340
322
  if (typeof params === "object" && params !== null && "prompt" in params) {
341
323
  const value = (params as { prompt?: unknown }).prompt;
@@ -355,10 +337,6 @@ function safeJoinInside(parent: string, childPath: string, context: string): str
355
337
  return targetPath;
356
338
  }
357
339
 
358
- function toWorkspaceClonePath(relativePath: string): string {
359
- return `./${relativePath.split(path.sep).join("/")}`;
360
- }
361
-
362
340
  function resolveSafeProjectWorkspacePath(key: string): {
363
341
  relativePath: string;
364
342
  workspaceClonePath: string;
@@ -375,7 +353,7 @@ function resolveSafeProjectWorkspacePath(key: string): {
375
353
  const relativePath = path.relative(virtualWorkspaceRoot, virtualTarget);
376
354
  return {
377
355
  relativePath,
378
- workspaceClonePath: toWorkspaceClonePath(relativePath),
356
+ workspaceClonePath: `./${relativePath.split(path.sep).join("/")}`,
379
357
  };
380
358
  }
381
359
 
@@ -383,47 +361,17 @@ function resolveRepoByKey(input: {
383
361
  projects: readonly ProcessProject[];
384
362
  workspaceRoot?: string;
385
363
  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
364
  }): FlowRepoContext | undefined {
400
- const requestedKey = input.key.trim();
401
- if (!requestedKey) {
365
+ const key = input.key.trim();
366
+ if (!key) {
402
367
  throw new Error("Flow repo lookup requires a non-empty project key");
403
368
  }
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
- }
369
+ const matches = input.projects.filter((project) => project.key.trim() === key);
370
+ if (matches.length === 0) return undefined;
419
371
  if (matches.length > 1) {
420
- throw new Error(`Flow context found duplicate project key '${requestedKey}'`);
372
+ throw new Error(`Flow context found duplicate project key '${key}'`);
421
373
  }
422
374
  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
375
  const baseBranch = project.baseBranch.trim();
428
376
  if (!baseBranch) {
429
377
  throw new Error(`Flow context project '${key}' has no base branch`);
@@ -454,13 +402,23 @@ function createFlowRepoLookup(input: {
454
402
  projects: readonly ProcessProject[];
455
403
  workspaceRoot?: string;
456
404
  }): FlowRepoLookup {
405
+ const get = (key: string): FlowRepoContext => {
406
+ const repo = resolveRepoByKey({ ...input, key });
407
+ if (repo) return repo;
408
+ const availableKeys = input.projects
409
+ .map((project) => project.key.trim())
410
+ .filter((key) => key !== "")
411
+ .join(", ");
412
+ throw new Error(
413
+ `Flow context requires project '${key.trim()}', but this process has no project with that key${
414
+ availableKeys ? ` (available: ${availableKeys})` : ""
415
+ }`,
416
+ );
417
+ };
457
418
  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
- ),
419
+ get,
420
+ optional: (key) => resolveRepoByKey({ ...input, key }),
421
+ all: () => input.projects.map((project) => get(project.key)),
464
422
  };
465
423
  }
466
424
 
@@ -488,23 +446,16 @@ export function createFlowPromptContext<
488
446
  optionalConsumedProducts: readonly string[] = [],
489
447
  ): FlowPromptContext<TParams, TState, TConsumedProducts, TPrepared> {
490
448
  const productInput: Record<string, string> = {};
491
- for (const productName of consumedProducts) {
449
+ const required = new Set<string>(consumedProducts);
450
+ for (const productName of new Set([...required, ...optionalConsumedProducts])) {
492
451
  const markdown = ctx.turnResultMarkdownByProduct?.[productName];
493
- if (typeof markdown !== "string" || markdown.trim() === "") {
452
+ if (typeof markdown === "string" && markdown.trim() !== "") {
453
+ productInput[productName] = markdown;
454
+ } else if (required.has(productName)) {
494
455
  throw new Error(
495
456
  `Flow prompt context requires product '${productName}' markdown, but the worker payload did not provide it`,
496
457
  );
497
458
  }
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
459
  }
509
460
  return {
510
461
  ...createFlowContextBase(ctx),
@@ -522,6 +473,7 @@ export function createFlowAutomaticRunContext<TParams, TState>(
522
473
  ): FlowAutomaticRunContext<TParams, TState> {
523
474
  return {
524
475
  ...createFlowContextBase(ctx),
476
+ scopedSettings: ctx.scopedSettings,
525
477
  callIntegrationTool(name, args) {
526
478
  if (!ctx.callIntegrationTool) {
527
479
  throw new Error(`Automatic integration tool '${name}' is unavailable`);
@@ -531,6 +483,9 @@ export function createFlowAutomaticRunContext<TParams, TState>(
531
483
  reportProgress(report) {
532
484
  ctx.reportProgress?.(report);
533
485
  },
486
+ reportDiagnostic(report) {
487
+ ctx.reportDiagnostic?.(report);
488
+ },
534
489
  };
535
490
  }
536
491
 
@@ -575,17 +530,17 @@ class RouteAndEffectBuilder<TParams, TState, TContext> {
575
530
 
576
531
  /** @public */
577
532
  to(turnId: TurnId): this {
578
- return this.setTarget({ kind: "to", turnId });
533
+ return this.setTarget({ to: turnId });
579
534
  }
580
535
 
581
536
  /** @public */
582
537
  complete(): this {
583
- return this.setTarget({ kind: "complete" });
538
+ return this.setTarget({ complete: true });
584
539
  }
585
540
 
586
541
  /** @public */
587
542
  lifecycleStatus(status: ProcessTurnTerminalLifecycleStatus): this {
588
- return this.setTarget({ kind: "lifecycleStatus", status });
543
+ return this.setTarget({ lifecycleStatus: status });
589
544
  }
590
545
 
591
546
  /** @internal */
@@ -606,21 +561,19 @@ class RouteAndEffectBuilder<TParams, TState, TContext> {
606
561
  return this;
607
562
  }
608
563
 
564
+ /** @internal */
565
+ getEffect(): FlowOutcomeEffect<TParams, TState, TContext> | undefined {
566
+ return this.flowEffect;
567
+ }
568
+
609
569
  /** @internal */
610
570
  hasRoute(): boolean {
611
571
  return this.target !== null;
612
572
  }
613
573
 
614
574
  /** @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);
575
+ buildRouteTarget(): Pick<ProcessTurnEndSpec, "to" | "complete" | "lifecycleStatus"> {
576
+ return { ...this.target };
624
577
  }
625
578
  }
626
579
 
@@ -628,42 +581,18 @@ class RouteAndEffectBuilder<TParams, TState, TContext> {
628
581
  export type FlowTargetSpec =
629
582
  | {
630
583
  /** @internal */
631
- kind: "to";
632
- /** @internal */
633
- turnId: TurnId;
584
+ to: TurnId;
634
585
  }
635
586
  | {
636
587
  /** @internal */
637
- kind: "complete";
588
+ complete: true;
638
589
  }
639
590
  | {
640
591
  /** @internal */
641
- kind: "lifecycleStatus";
642
- /** @internal */
643
- status: ProcessTurnTerminalLifecycleStatus;
592
+ lifecycleStatus: ProcessTurnTerminalLifecycleStatus;
644
593
  }
645
594
  | null;
646
595
 
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
596
  /** @public */
668
597
  interface ParameterOptions extends Partial<Omit<OutcomeToolParameterSpec, "type" | "description">> {
669
598
  /** @public */
@@ -695,19 +624,38 @@ function isStringArray(value: unknown): value is readonly string[] {
695
624
  }
696
625
 
697
626
  /** @public */
698
- class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEffectBuilder<
699
- TParams,
700
- TState,
701
- TContext
702
- > {
627
+ class OutcomeParametersBuilder<TParams = unknown, TState = unknown> {
703
628
  /** @internal */
704
629
  protected outcomeDescription: string | null = null;
705
630
  /** @internal */
706
631
  protected parameters: Record<string, OutcomeToolParameterSpec> = {};
707
632
  /** @internal */
708
- protected publishedMarkdownParameter: string | null = null;
709
- /** @internal */
710
633
  protected summaryParameter: string | null = null;
634
+ private enforceSchema = false;
635
+ /** @internal */
636
+ protected parameterResolver?: (
637
+ ctx: OutcomeParameterContext<TParams, TState>,
638
+ ) => Record<string, OutcomeToolParameterSpec>;
639
+
640
+ /** Enforce a closed schema with no optional properties at supported providers. @public */
641
+ strictSchema(): this {
642
+ this.enforceSchema = true;
643
+ return this;
644
+ }
645
+
646
+ /** Declare alternatives for one argument. @public */
647
+ union(
648
+ name: string,
649
+ variants: readonly OutcomeToolArrayItemSpec[],
650
+ options: string | ParameterOptions = {},
651
+ ): this {
652
+ const resolved = typeof options === "string" ? { description: options } : options;
653
+ return this.parameter(name, {
654
+ ...resolved,
655
+ anyOf: variants,
656
+ description: resolved.description ?? "",
657
+ });
658
+ }
711
659
 
712
660
  /** Optional concise result publication, separate from the full Markdown. @public */
713
661
  resultSummary(name = "resultSummary"): this {
@@ -719,18 +667,16 @@ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEff
719
667
  }
720
668
 
721
669
  /** @internal */
722
- protected buildParameterSpec(kind: string): ProcessToolOutcomeSpec<TParams, TState> {
670
+ protected buildParameterSpec(
671
+ kind: string,
672
+ ): Pick<ProcessToolOutcomeSpec, "description" | "parameters" | "resultSummaryParameter"> {
723
673
  if (!this.outcomeDescription) throw new Error(`${kind} must declare .description(...)`);
724
674
  return {
725
675
  description: this.outcomeDescription,
726
676
  parameters: this.parameters,
677
+ ...(this.enforceSchema ? { strictSchema: true } : {}),
678
+ ...(this.parameterResolver ? { resolveParameters: this.parameterResolver } : {}),
727
679
  ...(this.summaryParameter ? { resultSummaryParameter: this.summaryParameter } : {}),
728
- ...(this.publishedMarkdownParameter
729
- ? {
730
- publishedProduct: this.publishedMarkdownParameter,
731
- turnResultMarkdownParameter: this.publishedMarkdownParameter,
732
- }
733
- : {}),
734
680
  };
735
681
  }
736
682
 
@@ -760,11 +706,12 @@ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEff
760
706
  return {
761
707
  ...resolved,
762
708
  required: true,
763
- requiredErrorCode: resolved.requiredErrorCode ?? toRequiredErrorCode(name),
709
+ requiredErrorCode: resolved.requiredErrorCode ?? `${snakeCase(name) || "value"}_required`,
764
710
  };
765
711
  }
766
712
 
767
- private typedParameter(
713
+ /** @internal */
714
+ protected typedParameter(
768
715
  name: string,
769
716
  type: OutcomeToolParameterSpec["type"],
770
717
  options: string | ArrayParameterOptions = {},
@@ -778,29 +725,11 @@ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEff
778
725
  });
779
726
  }
780
727
 
781
- /** @internal */
728
+ /** @public */
782
729
  string(name: string, options: string | ParameterOptions = {}): this {
783
730
  return this.typedParameter(name, "string", options);
784
731
  }
785
732
 
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
733
  /** @public */
805
734
  requiredString(name: string, options: string | ParameterOptions = {}): this {
806
735
  return this.typedParameter(name, "string", this.withRequired(name, options));
@@ -811,7 +740,7 @@ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEff
811
740
  return this.typedParameter(name, "number", options);
812
741
  }
813
742
 
814
- /** @internal */
743
+ /** @public */
815
744
  requiredNumber(name: string, options: string | ParameterOptions = {}): this {
816
745
  return this.typedParameter(name, "number", this.withRequired(name, options));
817
746
  }
@@ -821,7 +750,7 @@ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEff
821
750
  return this.typedParameter(name, "boolean", options);
822
751
  }
823
752
 
824
- /** @internal */
753
+ /** @public */
825
754
  requiredBoolean(name: string, options: string | ParameterOptions = {}): this {
826
755
  return this.typedParameter(name, "boolean", this.withRequired(name, options));
827
756
  }
@@ -831,9 +760,9 @@ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEff
831
760
  return this.typedParameter(name, "array", options);
832
761
  }
833
762
 
834
- /** @internal */
763
+ /** @public */
835
764
  requiredStringArray(name: string, options: string | ArrayParameterOptions = {}): this {
836
- return this.typedParameter(name, "array", this.withRequired(name, options));
765
+ return this.typedParameter(name, "array", { minItems: 1, ...this.withRequired(name, options) });
837
766
  }
838
767
 
839
768
  /** @internal */
@@ -862,7 +791,98 @@ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends RouteAndEff
862
791
 
863
792
  /** @public */
864
793
  requiredArray(name: string, options: string | ArrayParameterOptions = {}): this {
865
- return this.typedParameter(name, "array", this.withRequired(name, options));
794
+ return this.typedParameter(name, "array", { minItems: 1, ...this.withRequired(name, options) });
795
+ }
796
+ }
797
+
798
+ /** @public */
799
+ class ParameterizedOutcomeBuilder<TParams, TState, TContext> extends OutcomeParametersBuilder<
800
+ TParams,
801
+ TState
802
+ > {
803
+ private readonly route = new RouteAndEffectBuilder<TParams, TState, TContext>();
804
+ private publishedMarkdownParameter: string | null = null;
805
+
806
+ /** @public */
807
+ to(turnId: TurnId): this {
808
+ this.route.to(turnId);
809
+ return this;
810
+ }
811
+
812
+ /** @public */
813
+ complete(): this {
814
+ this.route.complete();
815
+ return this;
816
+ }
817
+
818
+ /** @public */
819
+ lifecycleStatus(status: ProcessTurnTerminalLifecycleStatus): this {
820
+ this.route.lifecycleStatus(status);
821
+ return this;
822
+ }
823
+
824
+ /** @internal */
825
+ stay(): this {
826
+ this.route.stay();
827
+ return this;
828
+ }
829
+
830
+ /** @public */
831
+ state(fn: FlowOutcomeStateEffect<TParams, TState, TContext>): this {
832
+ this.route.state(fn);
833
+ return this;
834
+ }
835
+
836
+ /** @public */
837
+ effect(fn: FlowOutcomeEffect<TParams, TState, TContext>): this {
838
+ this.route.effect(fn);
839
+ return this;
840
+ }
841
+
842
+ /** @internal */
843
+ hasRoute(): boolean {
844
+ return this.route.hasRoute();
845
+ }
846
+
847
+ /** @internal */
848
+ protected get flowEffect(): FlowOutcomeEffect<TParams, TState, TContext> | undefined {
849
+ return this.route.getEffect();
850
+ }
851
+
852
+ /** @internal */
853
+ protected buildRouteTarget() {
854
+ return this.route.buildRouteTarget();
855
+ }
856
+
857
+ /** @internal */
858
+ protected override buildParameterSpec(kind: string): ProcessToolOutcomeSpec<TParams, TState> {
859
+ return {
860
+ ...super.buildParameterSpec(kind),
861
+ ...(this.publishedMarkdownParameter
862
+ ? {
863
+ publishedProduct: this.publishedMarkdownParameter,
864
+ turnResultMarkdownParameter: this.publishedMarkdownParameter,
865
+ }
866
+ : {}),
867
+ };
868
+ }
869
+
870
+ /** @public */
871
+ markdown(name: string, options: string | MarkdownParameterOptions = {}): this {
872
+ const resolved = typeof options === "string" ? { description: options } : options;
873
+ const { publish, ...parameterOptions } = resolved;
874
+ if (publish) {
875
+ if (this.publishedMarkdownParameter && this.publishedMarkdownParameter !== name) {
876
+ throw new Error("Outcome can publish only one markdown parameter");
877
+ }
878
+ normalizeProductName(name);
879
+ this.publishedMarkdownParameter = name;
880
+ }
881
+ return this.typedParameter(name, "string", {
882
+ ...parameterOptions,
883
+ required: publish ? true : resolved.required,
884
+ requiredErrorCode: resolved.requiredErrorCode ?? (publish ? `${name}_required` : undefined),
885
+ });
866
886
  }
867
887
  }
868
888
 
@@ -875,9 +895,17 @@ export class OutcomeToolBuilder<
875
895
  TState,
876
896
  FlowLlmOutcomeEffectContext<TParams, TState>
877
897
  > {
898
+ /** Pure synchronous resolution at turn-start preparation. @public */
899
+ resolveParameters(
900
+ fn: (ctx: OutcomeParameterContext<TParams, TState>) => Record<string, OutcomeToolParameterSpec>,
901
+ ): this {
902
+ this.parameterResolver = fn;
903
+ return this;
904
+ }
905
+
878
906
  private stateRouting:
879
907
  | {
880
- branches: Record<string, TurnId>;
908
+ branches: Record<string, TurnId | ProcessOutcomeBranchSpec>;
881
909
  choose: (
882
910
  input: FlowOutcomeEffectInput<
883
911
  TParams,
@@ -890,7 +918,7 @@ export class OutcomeToolBuilder<
890
918
 
891
919
  /** @public */
892
920
  routeByState(
893
- branches: Record<string, TurnId>,
921
+ branches: Record<string, TurnId | ProcessOutcomeBranchSpec>,
894
922
  choose: (
895
923
  input: FlowOutcomeEffectInput<TParams, TState, FlowLlmOutcomeEffectContext<TParams, TState>>,
896
924
  ) => MaybePromise<string>,
@@ -917,9 +945,9 @@ export class OutcomeToolBuilder<
917
945
  ...(stateRouting
918
946
  ? {
919
947
  branches: Object.fromEntries(
920
- Object.entries(stateRouting.branches).map(([branchId, turnId]) => [
948
+ Object.entries(stateRouting.branches).map(([branchId, branch]) => [
921
949
  branchId,
922
- { to: turnId },
950
+ typeof branch === "string" ? { to: branch } : { ...branch },
923
951
  ]),
924
952
  ),
925
953
  choose: wrapOutcomeCallback((input) => stateRouting.choose(input)),
@@ -991,29 +1019,34 @@ export class PlanResultBuilder<TParams = unknown, TState = unknown> extends Rout
991
1019
  /** @internal */
992
1020
  summary(options: string | PlanFieldOptions = {}): this {
993
1021
  const resolved = typeof options === "string" ? { description: options } : options;
994
- this.summarySpec = textField({
1022
+ this.summarySpec = {
1023
+ type: "string",
995
1024
  description: resolved.description ?? "Short summary of the proposed plan",
1025
+ required: true,
996
1026
  requiredErrorCode: resolved.requiredErrorCode ?? "summary_required",
997
- });
1027
+ };
998
1028
  return this;
999
1029
  }
1000
1030
 
1001
1031
  /** @internal */
1002
1032
  acceptanceCriteria(options: string | PlanAcceptanceCriteriaOptions = {}): this {
1003
1033
  const resolved = typeof options === "string" ? { description: options } : options;
1004
- this.acceptanceCriteriaSpec = stringArrayField({
1034
+ this.acceptanceCriteriaSpec = {
1035
+ type: "array",
1005
1036
  description: resolved.description ?? "Acceptance criteria for the requested change",
1037
+ items: { type: "string" },
1038
+ required: true,
1006
1039
  requiredErrorCode: resolved.requiredErrorCode ?? "acceptance_criteria_required",
1007
1040
  minItems: resolved.minItems ?? 1,
1008
1041
  minItemsErrorCode: resolved.minItemsErrorCode ?? "acceptance_criteria_required",
1009
- });
1042
+ };
1010
1043
  return this;
1011
1044
  }
1012
1045
 
1013
1046
  /** @internal */
1014
1047
  review(turnId: TurnId): this {
1015
1048
  this.reviewTurnId = turnId;
1016
- return this.setTarget({ kind: "to", turnId });
1049
+ return this.setTarget({ to: turnId });
1017
1050
  }
1018
1051
 
1019
1052
  /** @internal */
@@ -1035,26 +1068,45 @@ export class PlanResultBuilder<TParams = unknown, TState = unknown> extends Rout
1035
1068
  acceptanceCriteria: this.acceptanceCriteriaSpec,
1036
1069
  },
1037
1070
  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 } : {}),
1071
+ async effect(execution) {
1072
+ const plan = await stateEffect?.(execution);
1073
+ const planRevision = execution.ctx.process.planRevision + 1;
1074
+ const summary = trimString(execution.event.params.summary);
1075
+ const acceptanceCriteria = normalizeStringArray(execution.event.params.acceptanceCriteria);
1076
+ const planMarkdown =
1077
+ typeof execution.event.turnResultMarkdown === "string"
1078
+ ? execution.event.turnResultMarkdown
1079
+ : trimString(execution.event.params.planMarkdown);
1080
+ return {
1081
+ ...plan,
1082
+ processPatch: { ...plan?.processPatch, planRevision },
1083
+ broadcasts: [
1084
+ ...(plan?.broadcasts ?? []),
1085
+ {
1086
+ type: "plan.updated",
1087
+ payload: { planRevision, reviewState: "awaiting_approval", approved: false, summary },
1088
+ },
1089
+ ],
1090
+ emit: [
1091
+ ...(plan?.emit ?? []),
1092
+ {
1093
+ type: DEFAULT_PLAN_RESULT_OUTCOME_ID,
1094
+ data: { planRevision, summary, planMarkdown, acceptanceCriteria },
1095
+ },
1096
+ ],
1097
+ };
1046
1098
  },
1047
1099
  };
1048
1100
  }
1049
1101
  }
1050
1102
 
1051
1103
  /** @public */
1052
- abstract class TurnEndBuilder<TParams, TState>
1104
+ export class LlmTurnEndBuilder<TParams = unknown, TState = unknown>
1053
1105
  extends RouteAndEffectBuilder<TParams, TState, FlowLlmOutcomeEffectContext<TParams, TState>>
1054
1106
  implements FlowLlmTurn<TParams, TState, string>
1055
1107
  {
1056
1108
  /** @internal */
1057
- protected abstract readonly builderName: string;
1109
+ protected readonly builderName: string = "LLM turn end";
1058
1110
 
1059
1111
  /** @internal */
1060
1112
  constructor(
@@ -1062,6 +1114,7 @@ abstract class TurnEndBuilder<TParams, TState>
1062
1114
  private readonly parent?: FlowLlmTurn<TParams, TState, string>,
1063
1115
  ) {
1064
1116
  super();
1117
+ if (outcomeId.trim() === "") throw new Error("LLM turn end outcome must be non-empty");
1065
1118
  }
1066
1119
 
1067
1120
  private get turn(): FlowLlmTurn<TParams, TState, string> {
@@ -1080,7 +1133,7 @@ abstract class TurnEndBuilder<TParams, TState>
1080
1133
  }
1081
1134
 
1082
1135
  /** @internal */
1083
- protected buildResult(): ProcessTurnEndSpec<TParams, TState, string> {
1136
+ build(): ProcessTurnEndSpec<TParams, TState, string> {
1084
1137
  const effect = this.flowEffect ? wrapOutcomeCallback(this.flowEffect) : undefined;
1085
1138
  return {
1086
1139
  outcome: this.outcomeId,
@@ -1091,44 +1144,19 @@ abstract class TurnEndBuilder<TParams, TState>
1091
1144
  }
1092
1145
 
1093
1146
  /** @public */
1094
- export class PublishedResultBuilder<TParams = unknown, TState = unknown> extends TurnEndBuilder<
1147
+ export class PublishedResultBuilder<TParams = unknown, TState = unknown> extends LlmTurnEndBuilder<
1095
1148
  TParams,
1096
1149
  TState
1097
1150
  > {
1098
1151
  /** @internal */
1099
- protected readonly builderName = "Published result";
1152
+ protected override readonly builderName = "Published result";
1100
1153
 
1101
1154
  /** @internal */
1102
1155
  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();
1156
+ return this.build();
1124
1157
  }
1125
1158
  }
1126
1159
 
1127
- /** @public */
1128
- type LlmPromptBuilder<TParams, TState, TConsumedProducts extends string, TPrepared> = (
1129
- ctx: FlowPromptContext<TParams, TState, TConsumedProducts, TPrepared>,
1130
- ) => MaybePromise<string>;
1131
-
1132
1160
  /** @public */
1133
1161
  abstract class DescribedTurnBuilder {
1134
1162
  /** @internal */
@@ -1152,220 +1180,258 @@ abstract class DescribedTurnBuilder {
1152
1180
  }
1153
1181
  }
1154
1182
 
1183
+ type StoredExternalActionBuilder<TParams, TState> = ExternalActionBuilder<
1184
+ TParams,
1185
+ TState,
1186
+ unknown,
1187
+ Record<string, unknown>
1188
+ >;
1189
+
1155
1190
  /** @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
-
1191
+ abstract class ExternalActionTurnBuilder<TParams, TState> extends DescribedTurnBuilder {
1197
1192
  /** @internal */
1198
- get definition(): LlmTurnDefinition<string, TParams, TState> {
1199
- return this.buildDefinition();
1200
- }
1193
+ protected abstract readonly turnKind: "LLM" | "Automatic" | "Human";
1194
+ private externalActionBuilders = new Map<string, StoredExternalActionBuilder<TParams, TState>>();
1201
1195
 
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) {
1196
+ /** @public */
1197
+ externalAction<
1198
+ TEvent = unknown,
1199
+ TInput extends Record<string, unknown> = Record<string, unknown>,
1200
+ >(
1201
+ externalActionId: string,
1202
+ source: ExternalActionSource<TParams, TState, TEvent, TInput>,
1203
+ configure: (
1204
+ external: ExternalActionBuilder<TParams, TState, TEvent, TInput>,
1205
+ ) => ExternalActionBuilder<TParams, TState, TEvent, TInput> | undefined,
1206
+ ): this {
1207
+ if (this.externalActionBuilders.has(externalActionId)) {
1214
1208
  throw new Error(
1215
- `LLM turn '${this.turnId}' must declare .forEach(...) before its completion path`,
1209
+ `${this.turnKind} turn '${this.turnId}' declares duplicate external action '${externalActionId}'`,
1216
1210
  );
1217
1211
  }
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,
1212
+ const builder = new ExternalActionBuilder(externalActionId, source);
1213
+ configure(builder);
1214
+ this.externalActionBuilders.set(
1215
+ externalActionId,
1216
+ builder as unknown as StoredExternalActionBuilder<TParams, TState>,
1224
1217
  );
1218
+ return this;
1225
1219
  }
1226
1220
 
1227
1221
  /** @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);
1222
+ protected buildExternalActions():
1223
+ | Record<string, ProcessHumanTurnExternalActionSpec<TParams, TState>>
1224
+ | undefined {
1225
+ return this.externalActionBuilders.size > 0
1226
+ ? buildSpecs(this.externalActionBuilders)
1227
+ : undefined;
1242
1228
  }
1229
+ }
1243
1230
 
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`);
1231
+ function buildSpecs<T>(builders: ReadonlyMap<string, { build(): T }>): Record<string, T> {
1232
+ return Object.fromEntries([...builders].map(([id, builder]) => [id, builder.build()]));
1233
+ }
1234
+
1235
+ function assertLlmOutcomeParameters<TParams, TState>(
1236
+ turnId: TurnId,
1237
+ outcomes: Record<string, ProcessToolOutcomeSpec<TParams, TState>>,
1238
+ ): void {
1239
+ for (const [outcomeId, outcome] of Object.entries(outcomes)) {
1240
+ if (OUTCOME_TOOL_MARKDOWN_PARAMETER_NAME in outcome.parameters) {
1241
+ throw new Error(
1242
+ `LLM turn '${turnId}' outcome tool '${outcomeId}' cannot declare reserved markdown parameter '${OUTCOME_TOOL_MARKDOWN_PARAMETER_NAME}'`,
1243
+ );
1249
1244
  }
1250
- this.mapped.collect = collect;
1251
1245
  }
1246
+ }
1247
+
1248
+ /** LLM authoring families used to preserve fluent context and completion types. @public */
1249
+ type LlmBuilderFamily =
1250
+ | {
1251
+ /** @public */
1252
+ kind: "ordinary";
1253
+ }
1254
+ | {
1255
+ /** @public */
1256
+ kind: "mapped";
1257
+ /** @public */
1258
+ item: unknown;
1259
+ /** @public */
1260
+ result: unknown;
1261
+ };
1252
1262
 
1263
+ /** Active-item context supplied by an LLM authoring family. @public */
1264
+ type LlmItemContext<TFamily extends LlmBuilderFamily> = TFamily extends {
1265
+ kind: "mapped";
1266
+ item: infer TItem;
1267
+ }
1268
+ ? MappedTurnItemContext<TItem>
1269
+ : Record<never, never>;
1270
+
1271
+ /** Preserve the concrete completion API when preparation or products refine its types. @public */
1272
+ type ConfiguredLlmBuilder<
1273
+ TFamily extends LlmBuilderFamily,
1274
+ TParams,
1275
+ TState,
1276
+ TConsumedProducts extends string,
1277
+ TPrepared,
1278
+ > = TFamily extends { kind: "mapped"; item: infer TItem; result: infer TResult }
1279
+ ? MappedLlmFlowBuilder<TParams, TState, TItem, TResult, TConsumedProducts, TPrepared>
1280
+ : LlmFlowBuilder<TParams, TState, TConsumedProducts, TPrepared>;
1281
+
1282
+ /** @public */
1283
+ abstract class LlmConfigurationBuilder<
1284
+ TParams,
1285
+ TState,
1286
+ TConsumedProducts extends string,
1287
+ TPrepared,
1288
+ TFamily extends LlmBuilderFamily,
1289
+ > extends ExternalActionTurnBuilder<TParams, TState> {
1253
1290
  /** @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;
1291
+ protected readonly turnKind = "LLM";
1292
+ private readonly configuration: Omit<
1293
+ LlmTurnDefinition<string, TParams, TState>,
1294
+ "kind" | "description" | "prompt" | "outcomes" | "turnEnd" | "forEach"
1295
+ > = { availableTools: [], branchType: "primary", context: "fresh", completionMode: "turn_end" };
1296
+
1297
+ /** Wait on the server before this turn may allocate a worker. @public */
1298
+ waitFor(predicate: TurnWaitPredicate<TParams, TState>): this {
1299
+ if (this.configuration.waitFor)
1300
+ throw new Error(`Turn '${this.turnId}' already declares .waitFor(...)`);
1301
+ this.configuration.waitFor = predicate;
1302
+ return this;
1260
1303
  }
1304
+ private promptBuilder:
1305
+ | ((ctx: ProcessRuntimeTurnContext<TParams, TState>) => MaybePromise<string>)
1306
+ | null = null;
1307
+ private readonly consumedProductNames = new Set<string>();
1308
+ private readonly optionalConsumedProductNames = new Set<string>();
1261
1309
 
1262
- private mappedItemContext(
1310
+ /** @internal */
1311
+ protected abstract itemContext(
1263
1312
  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
- }
1313
+ ): LlmItemContext<TFamily>;
1278
1314
 
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
- };
1315
+ /** @public */
1316
+ executionPurpose(purpose: string): this {
1317
+ if (purpose) this.configuration.executionPurpose = purpose;
1318
+ else delete this.configuration.executionPurpose;
1319
+ return this;
1293
1320
  }
1294
1321
 
1295
1322
  /** @internal */
1296
1323
  modelPurpose(purpose: LlmModelPurpose): this {
1297
- this.modelPurposeValue = purpose;
1324
+ this.configuration.modelPurpose = purpose;
1298
1325
  return this;
1299
1326
  }
1300
1327
 
1301
1328
  /** @public */
1302
1329
  tools(...tools: readonly PiBuiltInToolName[]): this {
1303
- this.availableTools = tools;
1330
+ this.configuration.availableTools = tools;
1304
1331
  return this;
1305
1332
  }
1306
1333
 
1307
1334
  /** @public */
1308
1335
  integrationTools(...tools: readonly string[]): this {
1309
- this.availableIntegrationTools = tools.map((tool) => tool.trim());
1336
+ if (tools.length) this.configuration.integrationTools = tools.map((tool) => tool.trim());
1337
+ else delete this.configuration.integrationTools;
1310
1338
  return this;
1311
1339
  }
1312
1340
 
1313
1341
  /** @public */
1314
1342
  resolveIntegrationTools(resolver: (params: TParams, state: TState) => readonly string[]): this {
1315
- this.integrationToolResolver = resolver;
1343
+ this.configuration.resolveIntegrationTools = resolver;
1316
1344
  return this;
1317
1345
  }
1318
1346
 
1319
1347
  /** @public */
1320
1348
  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>;
1349
+ fn: (
1350
+ ctx: FlowLlmPreparationContext<TParams, TState> & LlmItemContext<TFamily>,
1351
+ ) => MaybePromise<TNextPrepared>,
1352
+ ): ConfiguredLlmBuilder<TFamily, TParams, TState, TConsumedProducts, TNextPrepared> {
1353
+ this.configuration.prepare = (ctx) =>
1354
+ fn({ ...createFlowAutomaticRunContext(ctx), ...this.itemContext(ctx) });
1355
+ return this.refineContext<TConsumedProducts, TNextPrepared>();
1356
+ }
1357
+
1358
+ /** Return correction errors before accepting an outcome. @public */
1359
+ validateOutcome(
1360
+ fn: (
1361
+ ctx: FlowOutcomeValidationContext<TParams, TState> & LlmItemContext<TFamily>,
1362
+ outcome: LlmOutcomeSubmission,
1363
+ ) => MaybePromise<readonly string[]>,
1364
+ ): this {
1365
+ this.configuration.validateOutcome = (ctx, outcome) =>
1366
+ fn(
1367
+ {
1368
+ ...createFlowAutomaticRunContext(ctx),
1369
+ ...this.itemContext(ctx),
1370
+ prepared: ctx.prepared,
1371
+ },
1372
+ outcome,
1373
+ );
1374
+ return this;
1325
1375
  }
1326
1376
 
1327
- /** Enable durable operator questions for this LLM turn. @public */
1328
- askQuestions(): this {
1329
- this.questionsEnabled = true;
1377
+ /** Enable durable questions, optionally constrained by captured input. @public */
1378
+ askQuestions(
1379
+ when?: (
1380
+ ctx: FlowPromptContext<TParams, TState, TConsumedProducts, TPrepared> &
1381
+ LlmItemContext<TFamily>,
1382
+ ) => boolean,
1383
+ ): this {
1384
+ this.configuration.askQuestions = true;
1385
+ this.configuration.resolveAskQuestions = when
1386
+ ? (ctx) =>
1387
+ when({
1388
+ ...createFlowPromptContext<TParams, TState, TConsumedProducts, TPrepared>(
1389
+ ctx,
1390
+ [...this.consumedProductNames] as TConsumedProducts[],
1391
+ [...this.optionalConsumedProductNames],
1392
+ ),
1393
+ ...this.itemContext(ctx),
1394
+ })
1395
+ : undefined;
1330
1396
  return this;
1331
1397
  }
1332
1398
 
1333
1399
  /** @public */
1334
1400
  freshPrimary(): this {
1335
- this.branchType = "primary";
1336
- this.context = "fresh";
1337
- this.startFrom = undefined;
1338
- this.restorePrimaryLeafAfterTurn = undefined;
1401
+ this.configuration.branchType = "primary";
1402
+ this.configuration.context = "fresh";
1403
+ delete this.configuration.startFrom;
1404
+ delete this.configuration.restorePrimaryLeafAfterTurn;
1339
1405
  return this;
1340
1406
  }
1341
1407
 
1342
1408
  /** @internal */
1343
1409
  freshSeededPrimary(): this {
1344
- this.branchType = "primary";
1345
- this.context = "fresh_seeded";
1346
- this.startFrom = undefined;
1347
- this.restorePrimaryLeafAfterTurn = undefined;
1410
+ this.configuration.branchType = "primary";
1411
+ this.configuration.context = "fresh_seeded";
1412
+ delete this.configuration.startFrom;
1413
+ delete this.configuration.restorePrimaryLeafAfterTurn;
1348
1414
  return this;
1349
1415
  }
1350
1416
 
1351
1417
  /** @public */
1352
1418
  fullPrimary(): this {
1353
- this.branchType = "primary";
1354
- this.context = "full";
1419
+ this.configuration.branchType = "primary";
1420
+ this.configuration.context = "full";
1355
1421
  return this;
1356
1422
  }
1357
1423
 
1358
1424
  /** @internal */
1359
1425
  rootBranchReview(): this {
1360
- this.branchType = "root_branch";
1361
- this.context = "full";
1362
- this.restorePrimaryLeafAfterTurn = true;
1426
+ this.configuration.branchType = "root_branch";
1427
+ this.configuration.context = "full";
1428
+ this.configuration.restorePrimaryLeafAfterTurn = true;
1363
1429
  return this;
1364
1430
  }
1365
1431
 
1366
1432
  /** @public */
1367
1433
  continueFromPrimaryLeaf(): this {
1368
- this.startFrom = {
1434
+ this.configuration.startFrom = {
1369
1435
  kind: "semantic_ref",
1370
1436
  ref: "currentPrimaryPathLeaf",
1371
1437
  fallback: { kind: "current_leaf" },
@@ -1375,7 +1441,7 @@ export class LlmFlowBuilder<
1375
1441
 
1376
1442
  /** @internal */
1377
1443
  continueFromReviewBranch(): this {
1378
- this.startFrom = {
1444
+ this.configuration.startFrom = {
1379
1445
  kind: "semantic_ref",
1380
1446
  ref: "review",
1381
1447
  fallback: { kind: "current_leaf" },
@@ -1393,7 +1459,7 @@ export class LlmFlowBuilder<
1393
1459
 
1394
1460
  /** @internal */
1395
1461
  startFromReviewBranch(): this {
1396
- this.startFrom = {
1462
+ this.configuration.startFrom = {
1397
1463
  kind: "semantic_ref",
1398
1464
  ref: "review",
1399
1465
  fallback: { kind: "session_root" },
@@ -1406,7 +1472,7 @@ export class LlmFlowBuilder<
1406
1472
  productName: string,
1407
1473
  fallback: ProcessTurnStartSelection = { kind: "session_root" },
1408
1474
  ): this {
1409
- this.startFrom = {
1475
+ this.configuration.startFrom = {
1410
1476
  kind: "product_ref",
1411
1477
  productName: normalizeProductName(productName),
1412
1478
  fallback,
@@ -1416,39 +1482,126 @@ export class LlmFlowBuilder<
1416
1482
 
1417
1483
  /** @internal */
1418
1484
  startFromRoot(): this {
1419
- this.startFrom = { kind: "session_root" };
1485
+ this.configuration.startFrom = { kind: "session_root" };
1420
1486
  return this;
1421
1487
  }
1422
1488
 
1423
1489
  /** @public */
1424
1490
  consume<TProductName extends string>(
1425
1491
  productName: TProductName,
1426
- ): LlmFlowBuilder<TParams, TState, TConsumedProducts | TProductName, TPrepared> {
1492
+ ): ConfiguredLlmBuilder<TFamily, TParams, TState, TConsumedProducts | TProductName, TPrepared> {
1427
1493
  this.consumedProductNames.add(normalizeProductName(productName));
1428
- return this as unknown as LlmFlowBuilder<
1429
- TParams,
1430
- TState,
1431
- TConsumedProducts | TProductName,
1432
- TPrepared
1433
- >;
1494
+ return this.refineContext<TConsumedProducts | TProductName, TPrepared>();
1434
1495
  }
1435
1496
 
1436
1497
  /** @public */
1437
1498
  optionalConsume<TProductName extends string>(
1438
1499
  productName: TProductName,
1439
- ): LlmFlowBuilder<TParams, TState, TConsumedProducts | TProductName, TPrepared> {
1500
+ ): ConfiguredLlmBuilder<TFamily, TParams, TState, TConsumedProducts | TProductName, TPrepared> {
1440
1501
  this.optionalConsumedProductNames.add(normalizeProductName(productName));
1441
- return this as unknown as LlmFlowBuilder<
1502
+ return this.refineContext<TConsumedProducts | TProductName, TPrepared>();
1503
+ }
1504
+
1505
+ private refineContext<
1506
+ TNextConsumedProducts extends string,
1507
+ TNextPrepared,
1508
+ >(): ConfiguredLlmBuilder<TFamily, TParams, TState, TNextConsumedProducts, TNextPrepared> {
1509
+ // Fluent configuration mutates this builder; only its context type changes.
1510
+ return this as unknown as ConfiguredLlmBuilder<
1511
+ TFamily,
1442
1512
  TParams,
1443
1513
  TState,
1444
- TConsumedProducts | TProductName,
1445
- TPrepared
1514
+ TNextConsumedProducts,
1515
+ TNextPrepared
1446
1516
  >;
1447
1517
  }
1448
1518
 
1519
+ /** @public */
1520
+ buildPrompt(
1521
+ fn: (
1522
+ ctx: FlowPromptContext<TParams, TState, TConsumedProducts, TPrepared> &
1523
+ LlmItemContext<TFamily>,
1524
+ ) => MaybePromise<string>,
1525
+ ): this {
1526
+ this.promptBuilder = (ctx) =>
1527
+ fn({
1528
+ ...createFlowPromptContext<TParams, TState, TConsumedProducts, TPrepared>(
1529
+ ctx,
1530
+ [...this.consumedProductNames] as TConsumedProducts[],
1531
+ [...this.optionalConsumedProductNames],
1532
+ ),
1533
+ ...this.itemContext(ctx),
1534
+ });
1535
+ return this;
1536
+ }
1537
+
1538
+ /** @public */
1539
+ prompt(
1540
+ prompt: string | ((ctx: ProcessRuntimeTurnContext<TParams, TState>) => MaybePromise<string>),
1541
+ ): this {
1542
+ this.promptBuilder = typeof prompt === "string" ? () => prompt : prompt;
1543
+ return this;
1544
+ }
1545
+
1546
+ /** @internal */
1547
+ protected buildBaseDefinition(): Omit<
1548
+ LlmTurnDefinition<string, TParams, TState>,
1549
+ "outcomes" | "turnEnd" | "forEach"
1550
+ > {
1551
+ if (!this.turnDescription) {
1552
+ throw new Error(`LLM turn '${this.turnId}' must declare .description(...)`);
1553
+ }
1554
+ const prompt = this.promptBuilder;
1555
+ if (!prompt) {
1556
+ throw new Error(`LLM turn '${this.turnId}' must declare .buildPrompt(...)`);
1557
+ }
1558
+ const externalActions = this.buildExternalActions();
1559
+ return {
1560
+ ...this.configuration,
1561
+ ...(externalActions ? { externalActions } : {}),
1562
+ kind: "llm",
1563
+ description: this.turnDescription,
1564
+ prompt,
1565
+ ...(this.consumedProductNames.size > 0
1566
+ ? { consumedProducts: [...this.consumedProductNames] }
1567
+ : {}),
1568
+ ...(this.optionalConsumedProductNames.size > 0
1569
+ ? { optionalConsumedProducts: [...this.optionalConsumedProductNames] }
1570
+ : {}),
1571
+ };
1572
+ }
1573
+ }
1574
+
1575
+ /** @public */
1576
+ export class LlmFlowBuilder<
1577
+ TParams = unknown,
1578
+ TState = unknown,
1579
+ TConsumedProducts extends string = never,
1580
+ TPrepared = undefined,
1581
+ >
1582
+ extends LlmConfigurationBuilder<
1583
+ TParams,
1584
+ TState,
1585
+ TConsumedProducts,
1586
+ TPrepared,
1587
+ { kind: "ordinary" }
1588
+ >
1589
+ implements FlowLlmTurn<TParams, TState, string>
1590
+ {
1591
+ private publishedResult: {
1592
+ productName: string;
1593
+ builder: PublishedResultBuilder<TParams, TState>;
1594
+ } | null = null;
1595
+ private endResult: LlmTurnEndBuilder<TParams, TState> | null = null;
1596
+ private outcomeToolBuilders = new Map<string, OutcomeToolBuilder<TParams, TState>>();
1597
+
1598
+ /** @internal */
1599
+ protected itemContext(): Record<never, never> {
1600
+ return {};
1601
+ }
1602
+
1449
1603
  /** @public */
1450
1604
  publish(productName: string): PublishedResultBuilder<TParams, TState> {
1451
- this.assertNotMapped(".publish(...)");
1452
1605
  const normalized = normalizeProductName(productName);
1453
1606
  if (this.publishedResult) {
1454
1607
  throw new Error(`LLM turn '${this.turnId}' can publish only one product in flow v1`);
@@ -1463,7 +1616,6 @@ export class LlmFlowBuilder<
1463
1616
 
1464
1617
  /** @public */
1465
1618
  end(outcomeId: string): LlmTurnEndBuilder<TParams, TState> {
1466
- this.assertNotMapped(".end(...)");
1467
1619
  if (this.endResult) {
1468
1620
  throw new Error(`LLM turn '${this.turnId}' declares duplicate .end(...) completion`);
1469
1621
  }
@@ -1477,34 +1629,6 @@ export class LlmFlowBuilder<
1477
1629
  return this.endResult;
1478
1630
  }
1479
1631
 
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
1632
  /** @public */
1509
1633
  outcomeTool(
1510
1634
  id: string,
@@ -1512,7 +1636,6 @@ export class LlmFlowBuilder<
1512
1636
  tool: OutcomeToolBuilder<TParams, TState>,
1513
1637
  ) => OutcomeToolBuilder<TParams, TState> | undefined,
1514
1638
  ): this {
1515
- this.assertNotMapped("routed outcome tools");
1516
1639
  if (id.trim() === "") {
1517
1640
  throw new Error(`LLM turn '${this.turnId}' declares an empty outcome tool id`);
1518
1641
  }
@@ -1531,47 +1654,6 @@ export class LlmFlowBuilder<
1531
1654
  return this;
1532
1655
  }
1533
1656
 
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
1657
  /** @internal */
1576
1658
  producesPlan(
1577
1659
  configure: (plan: PlanResultBuilder<TParams, TState>) => PlanResultBuilder<TParams, TState>,
@@ -1593,22 +1675,20 @@ export class LlmFlowBuilder<
1593
1675
  };
1594
1676
  }
1595
1677
 
1596
- private buildDefinition(): LlmTurnDefinition<string, TParams, TState> {
1678
+ /** @internal */
1679
+ get definition(): LlmTurnDefinition<string, TParams, TState> {
1597
1680
  const definition = this.buildBaseDefinition();
1598
- const hasOutcomeTools = this.outcomeToolBuilders.size > 0;
1599
1681
  const explicitTurnEnd = this.endResult;
1600
1682
  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
- }
1683
+ const outcomes = buildSpecs(this.outcomeToolBuilders);
1684
+ const hasOutcomeTools = Object.keys(outcomes).length > 0;
1605
1685
  const outcomePublishedProducts = new Set(
1606
1686
  Object.values(outcomes)
1607
1687
  .map((outcome) => outcome.publishedProduct)
1608
1688
  .filter((productName): productName is string => typeof productName === "string"),
1609
1689
  );
1610
1690
  const hasOutcomePublishedProduct = outcomePublishedProducts.size > 0;
1611
- let turnEnd: ProcessTurnEndSpec<TParams, TState, string> | undefined;
1691
+ let turnEnd = explicitTurnEnd?.build();
1612
1692
  let resultSemanticRef: "plan" | "review" | undefined = outcomePublishedProducts.has("review")
1613
1693
  ? "review"
1614
1694
  : outcomePublishedProducts.has("plan")
@@ -1619,76 +1699,48 @@ export class LlmFlowBuilder<
1619
1699
 
1620
1700
  if (published) {
1621
1701
  publishedProduct = published.productName;
1622
- if (published.productName === "plan") {
1623
- resultSemanticRef = "plan";
1624
- }
1625
- if (published.productName === "review") {
1626
- resultSemanticRef = "review";
1702
+ if (published.productName === "plan" || published.productName === "review") {
1703
+ resultSemanticRef = published.productName;
1627
1704
  }
1628
1705
  const publishHasRoute = published.builder.hasRoute();
1629
- if (publishHasRoute && hasOutcomeTools) {
1706
+ if (publishHasRoute === hasOutcomeTools) {
1630
1707
  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) {
1642
- throw new Error(
1643
- `LLM turn '${this.turnId}' publishes product '${published.productName}' but declares no route or outcome tool completion path`,
1708
+ hasOutcomeTools
1709
+ ? `LLM turn '${this.turnId}' cannot route published product '${published.productName}' and declare outcome tools in flow v1`
1710
+ : `LLM turn '${this.turnId}' publishes product '${published.productName}' but declares no route or outcome tool completion path`,
1644
1711
  );
1645
1712
  }
1713
+ turnResultMarkdown = publishHasRoute
1714
+ ? ASSISTANT_OUTPUT_TURN_RESULT
1715
+ : OUTCOME_TOOL_ARGUMENT_TURN_RESULT;
1716
+ if (publishHasRoute) turnEnd = published.builder.buildTurnEnd();
1646
1717
  } else if (hasOutcomeTools && !hasOutcomePublishedProduct) {
1647
1718
  turnResultMarkdown = OUTCOME_TOOL_ARGUMENT_TURN_RESULT;
1648
1719
  } else if (explicitTurnEnd) {
1649
1720
  turnResultMarkdown = ASSISTANT_OUTPUT_TURN_RESULT;
1650
1721
  }
1651
1722
 
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
- }
1723
+ assertLlmOutcomeParameters(this.turnId, outcomes);
1661
1724
 
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();
1725
+ if (explicitTurnEnd && hasOutcomeTools) {
1726
+ throw new Error(`LLM turn '${this.turnId}' cannot declare multiple completion paths`);
1667
1727
  }
1668
- if (Object.keys(outcomes).length === 0 && !turnEnd) {
1728
+ if (!hasOutcomeTools && !turnEnd) {
1669
1729
  throw new Error(`LLM turn '${this.turnId}' must declare a completion path`);
1670
1730
  }
1671
- const forEach = this.buildMappedSpec();
1672
1731
 
1673
1732
  return {
1674
1733
  ...definition,
1675
- ...(forEach ? { forEach } : {}),
1676
- ...(Object.keys(outcomes).length > 0 ? { outcomes } : {}),
1734
+ ...(hasOutcomeTools ? { outcomes } : {}),
1677
1735
  ...(turnEnd ? { turnEnd } : {}),
1678
1736
  ...(turnResultMarkdown ? { turnResultMarkdown } : {}),
1679
1737
  ...(resultSemanticRef ? { resultSemanticRef } : {}),
1680
1738
  ...(publishedProduct ? { publishedProduct } : {}),
1681
- ...(this.consumedProductNames.size > 0
1682
- ? { consumedProducts: [...this.consumedProductNames] }
1683
- : {}),
1684
- ...(this.optionalConsumedProductNames.size > 0
1685
- ? { optionalConsumedProducts: [...this.optionalConsumedProductNames] }
1686
- : {}),
1687
1739
  };
1688
1740
  }
1689
1741
  }
1690
1742
 
1691
- /** Item selection for `flow.llm(...).forEach(...)`. @public */
1743
+ /** Item selection for `flow.mappedLlm(...)`. @public */
1692
1744
  export type FlowForEachOptions<TParams, TState, TItem, TResult> = Pick<
1693
1745
  MappedLlmTurnSpec<TParams, TState, TItem, TResult>,
1694
1746
  "items" | "itemCodec" | "resultCodec" | "key" | "label" | "stateAfterSnapshot"
@@ -1720,63 +1772,18 @@ export class MappedOutcomeBuilder<
1720
1772
  TState = unknown,
1721
1773
  TItem = unknown,
1722
1774
  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);
1775
+ > extends OutcomeParametersBuilder<TParams, TState> {
1776
+ /** Resolve parameters from captured state and the frozen mapped item. @public */
1777
+ resolveParameters(
1778
+ fn: (
1779
+ ctx: OutcomeParameterContext<TParams, TState> & MappedTurnItemContext<TItem>,
1780
+ ) => Record<string, OutcomeToolParameterSpec>,
1781
+ ): this {
1782
+ this.parameterResolver = (ctx) =>
1783
+ fn(ctx as OutcomeParameterContext<TParams, TState> & MappedTurnItemContext<TItem>);
1778
1784
  return this;
1779
1785
  }
1786
+ private yieldResult: MappedItemYield<TParams, TState, TItem, TResult> | null = null;
1780
1787
 
1781
1788
  /** Map this outcome to the item's typed result. @public */
1782
1789
  yield(fn: MappedItemYield<TParams, TState, TItem, TResult>): this {
@@ -1787,59 +1794,52 @@ export class MappedOutcomeBuilder<
1787
1794
  /** @internal */
1788
1795
  build(): {
1789
1796
  /** @internal */
1790
- tool: OutcomeToolBuilder<TParams, TState>;
1797
+ tool: ProcessToolOutcomeSpec<TParams, TState>;
1791
1798
  /** @internal */
1792
1799
  yieldResult: MappedItemYield<TParams, TState, TItem, TResult>;
1793
1800
  } {
1794
1801
  if (!this.yieldResult) {
1795
1802
  throw new Error("Mapped outcome must declare .yield(...)");
1796
1803
  }
1797
- return { tool: this.tool, yieldResult: this.yieldResult };
1804
+ return { tool: this.buildParameterSpec("Mapped outcome tool"), yieldResult: this.yieldResult };
1798
1805
  }
1799
1806
  }
1800
1807
 
1801
- /** @public */
1802
- abstract class MappedTurnFacade<TParams, TState> implements FlowLlmTurn<TParams, TState, string> {
1808
+ /** Routes a mapped turn once, after all item results are collected. @public */
1809
+ export class MappedCollectBuilder<TParams = unknown, TState = unknown>
1810
+ implements FlowLlmTurn<TParams, TState, string>
1811
+ {
1803
1812
  /** @internal */
1804
1813
  constructor(
1805
- /** @internal */
1806
- protected readonly base: LlmFlowBuilder<TParams, TState, string, unknown>,
1814
+ private readonly turn: FlowLlmTurn<TParams, TState, string>,
1815
+ private readonly setRouting: (routing: MappedCollectRouting<TParams, TState>) => void,
1807
1816
  ) {}
1808
1817
 
1809
1818
  /** @internal */
1810
1819
  get id(): TurnId {
1811
- return this.base.id;
1820
+ return this.turn.id;
1812
1821
  }
1813
1822
 
1814
1823
  /** @internal */
1815
1824
  get definition(): LlmTurnDefinition<string, TParams, TState> {
1816
- return this.base.definition;
1825
+ return this.turn.definition;
1817
1826
  }
1818
- }
1819
1827
 
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
1828
  /** @public */
1829
1829
  to(turnId: TurnId): this {
1830
- this.base.setMappedRouting({ kind: "static", to: turnId });
1830
+ this.setRouting({ kind: "static", to: turnId });
1831
1831
  return this;
1832
1832
  }
1833
1833
 
1834
1834
  /** @public */
1835
1835
  complete(): this {
1836
- this.base.setMappedRouting({ kind: "static", lifecycleStatus: "completed" });
1836
+ this.setRouting({ kind: "static", lifecycleStatus: "completed" });
1837
1837
  return this;
1838
1838
  }
1839
1839
 
1840
1840
  /** @public */
1841
1841
  lifecycleStatus(status: ProcessTurnTerminalLifecycleStatus): this {
1842
- this.base.setMappedRouting({ kind: "static", lifecycleStatus: status });
1842
+ this.setRouting({ kind: "static", lifecycleStatus: status });
1843
1843
  return this;
1844
1844
  }
1845
1845
 
@@ -1851,7 +1851,7 @@ export class MappedCollectBuilder<TParams = unknown, TState = unknown> extends M
1851
1851
  if (Object.keys(branches).length === 0) {
1852
1852
  throw new Error("Mapped collection routing must declare at least one branch");
1853
1853
  }
1854
- this.base.setMappedRouting({ kind: "branches", branches: { ...branches }, choose });
1854
+ this.setRouting({ kind: "branches", branches: { ...branches }, choose });
1855
1855
  return this;
1856
1856
  }
1857
1857
  }
@@ -1862,97 +1862,52 @@ export class MappedCollectBuilder<TParams = unknown, TState = unknown> extends M
1862
1862
  * @public
1863
1863
  */
1864
1864
  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<
1865
+ TParams = unknown,
1866
+ TState = unknown,
1867
+ TItem = unknown,
1868
+ TResult = unknown,
1869
+ TConsumedProducts extends string = never,
1870
+ TPrepared = undefined,
1871
+ >
1872
+ extends LlmConfigurationBuilder<
1905
1873
  TParams,
1906
1874
  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
- }
1875
+ TConsumedProducts,
1876
+ TPrepared,
1877
+ { kind: "mapped"; item: TItem; result: TResult }
1878
+ >
1879
+ implements FlowLlmTurn<TParams, TState, string>
1880
+ {
1881
+ private readonly outcomes = new Map<
1882
+ string,
1883
+ MappedOutcomeBuilder<TParams, TState, TItem, TResult>
1884
+ >();
1885
+ private collection: MappedCollect<TParams, TState, TResult> | undefined;
1886
+ private routing: MappedCollectRouting<TParams, TState> | undefined;
1922
1887
 
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
- >;
1888
+ /** @internal */
1889
+ constructor(
1890
+ turnId: TurnId,
1891
+ private readonly items: FlowForEachOptions<TParams, TState, TItem, TResult>,
1892
+ ) {
1893
+ super(turnId);
1936
1894
  }
1937
1895
 
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;
1896
+ /** @internal */
1897
+ protected itemContext(
1898
+ ctx: ProcessRuntimeTurnContext<TParams, TState>,
1899
+ ): MappedTurnItemContext<TItem> {
1900
+ const iteration = ctx.iteration;
1901
+ if (!iteration) {
1902
+ throw new Error(`Mapped turn '${this.turnId}' requires an active item`);
1903
+ }
1904
+ return {
1905
+ item: this.items.itemCodec.parse(iteration.item),
1906
+ itemKey: iteration.itemKey,
1907
+ itemLabel: iteration.itemLabel,
1908
+ itemIndex: iteration.itemIndex,
1909
+ itemCount: iteration.itemCount,
1910
+ };
1956
1911
  }
1957
1912
 
1958
1913
  /** @public */
@@ -1962,71 +1917,66 @@ export class MappedLlmFlowBuilder<
1962
1917
  outcome: MappedOutcomeBuilder<TParams, TState, TItem, TResult>,
1963
1918
  ) => MappedOutcomeBuilder<TParams, TState, TItem, TResult> | undefined,
1964
1919
  ): this {
1920
+ if (id.trim() === "") {
1921
+ throw new Error(`LLM turn '${this.turnId}' declares an empty outcome tool id`);
1922
+ }
1923
+ if (this.outcomes.has(id)) {
1924
+ throw new Error(`LLM turn '${this.turnId}' declares duplicate outcome tool '${id}'`);
1925
+ }
1965
1926
  const outcome = new MappedOutcomeBuilder<TParams, TState, TItem, TResult>();
1966
1927
  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
- );
1928
+ outcome.build();
1929
+ this.outcomes.set(id, outcome);
1973
1930
  return this;
1974
1931
  }
1975
1932
 
1976
1933
  /** Combine ordered item results into process state, once. @public */
1977
1934
  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
- );
1935
+ if (this.collection) {
1936
+ throw new Error(`Mapped turn '${this.turnId}' declares .collect(...) more than once`);
2011
1937
  }
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;
1938
+ this.collection = fn;
1939
+ return new MappedCollectBuilder(this, (routing) => {
1940
+ if (this.routing) {
1941
+ throw new Error(`Mapped turn '${this.turnId}' collection already declares a route`);
1942
+ }
1943
+ this.routing = routing;
1944
+ });
2019
1945
  }
2020
1946
 
2021
1947
  /** @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;
1948
+ get definition(): LlmTurnDefinition<string, TParams, TState> {
1949
+ const definition = this.buildBaseDefinition();
1950
+ if (this.outcomes.size === 0) {
1951
+ throw new Error(`Mapped turn '${this.turnId}' must declare an item outcome tool`);
1952
+ }
1953
+ if (!this.collection) {
1954
+ throw new Error(`Mapped turn '${this.turnId}' must declare .collect(...)`);
1955
+ }
1956
+ if (!this.routing) {
1957
+ throw new Error(`Mapped turn '${this.turnId}' must declare a collection route`);
1958
+ }
1959
+ const outcomes: Record<string, ProcessToolOutcomeSpec<TParams, TState>> = {};
1960
+ const yields: Record<string, MappedItemYield<TParams, TState, TItem, TResult>> = {};
1961
+ for (const [id, builder] of this.outcomes) {
1962
+ const built = builder.build();
1963
+ outcomes[id] = built.tool;
1964
+ yields[id] = built.yieldResult;
1965
+ }
1966
+ assertLlmOutcomeParameters(this.turnId, outcomes);
1967
+ const forEach: MappedLlmTurnSpec<TParams, TState, TItem, TResult> = {
1968
+ ...this.items,
1969
+ yields,
1970
+ collect: this.collection,
1971
+ routing: this.routing,
1972
+ };
1973
+ return {
1974
+ ...definition,
1975
+ outcomes,
1976
+ turnResultMarkdown: OUTCOME_TOOL_ARGUMENT_TURN_RESULT,
1977
+ // The codecs preserve item/result types across the erased runtime definition boundary.
1978
+ forEach: forEach as MappedLlmTurnSpec<TParams, TState>,
1979
+ };
2030
1980
  }
2031
1981
  }
2032
1982
 
@@ -2042,10 +1992,12 @@ export class AutomaticFlowBuilder<TParams = unknown, TState = unknown>
2042
1992
  | null = null;
2043
1993
  private outcomeBuilders = new Map<string, AutomaticOutcomeBuilder<TParams, TState>>();
2044
1994
  private availableIntegrationTools: readonly string[] = [];
2045
-
2046
- /** @internal */
2047
- get definition(): AutomaticTurnDefinition<string, TParams, TState> {
2048
- return this.buildDefinition();
1995
+ private waitPredicate: TurnWaitPredicate<TParams, TState> | undefined;
1996
+ /** Wait on the server before this turn may allocate a worker. @public */
1997
+ waitFor(predicate: TurnWaitPredicate<TParams, TState>): this {
1998
+ if (this.waitPredicate) throw new Error(`Turn '${this.turnId}' already declares .waitFor(...)`);
1999
+ this.waitPredicate = predicate;
2000
+ return this;
2049
2001
  }
2050
2002
 
2051
2003
  /** @public */
@@ -2083,7 +2035,8 @@ export class AutomaticFlowBuilder<TParams = unknown, TState = unknown>
2083
2035
  return this;
2084
2036
  }
2085
2037
 
2086
- private buildDefinition(): AutomaticTurnDefinition<string, TParams, TState> {
2038
+ /** @internal */
2039
+ get definition(): AutomaticTurnDefinition<string, TParams, TState> {
2087
2040
  if (!this.turnDescription) {
2088
2041
  throw new Error(`Automatic turn '${this.turnId}' must declare .description(...)`);
2089
2042
  }
@@ -2093,15 +2046,13 @@ export class AutomaticFlowBuilder<TParams = unknown, TState = unknown>
2093
2046
  if (this.outcomeBuilders.size === 0) {
2094
2047
  throw new Error(`Automatic turn '${this.turnId}' must declare at least one outcome`);
2095
2048
  }
2096
- const outcomes: Record<string, ProcessToolOutcomeSpec<TParams, TState>> = {};
2097
- for (const [outcomeId, builder] of this.outcomeBuilders) {
2098
- outcomes[outcomeId] = builder.build();
2099
- }
2049
+ const outcomes = buildSpecs(this.outcomeBuilders);
2100
2050
  const runFn = this.runFn;
2101
2051
  const externalActions = this.buildExternalActions();
2102
2052
  return {
2103
2053
  kind: "automatic",
2104
2054
  description: this.turnDescription,
2055
+ ...(this.waitPredicate ? { waitFor: this.waitPredicate } : {}),
2105
2056
  ...(this.availableIntegrationTools.length > 0
2106
2057
  ? { integrationTools: this.availableIntegrationTools }
2107
2058
  : {}),
@@ -2288,11 +2239,10 @@ export class HumanFlowBuilder<TParams = unknown, TState = unknown>
2288
2239
  {
2289
2240
  /** @internal */
2290
2241
  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;
2242
+ private readonly metadata: Omit<
2243
+ HumanTurnDefinition<TParams, TState>,
2244
+ "kind" | "description" | "actions" | "externalActions"
2245
+ > = {};
2296
2246
  private actions = new Map<string, HumanActionBuilder<TParams, TState>>();
2297
2247
 
2298
2248
  /** @public */
@@ -2304,42 +2254,38 @@ export class HumanFlowBuilder<TParams = unknown, TState = unknown>
2304
2254
  return {
2305
2255
  kind: "human",
2306
2256
  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
- ),
2257
+ ...this.metadata,
2258
+ actions: buildSpecs(this.actions),
2315
2259
  ...(externalActions ? { externalActions } : {}),
2316
2260
  };
2317
2261
  }
2318
2262
 
2319
2263
  /** @public */
2320
2264
  reviewProduct(productName: string): this {
2321
- const normalized = normalizeProductName(productName);
2322
- this.reviewProductName = normalized;
2323
- this.reviewSemanticRef =
2324
- normalized === "plan" ? "plan" : normalized === "review" ? "review" : undefined;
2265
+ this.metadata.reviewProduct = normalizeProductName(productName);
2266
+ if (productName === "plan" || productName === "review")
2267
+ this.metadata.reviewSemanticRef = productName;
2268
+ else delete this.metadata.reviewSemanticRef;
2325
2269
  return this;
2326
2270
  }
2327
2271
 
2328
2272
  /** @public */
2329
2273
  operatorAttention(attention: HumanTurnOperatorAttention): this {
2330
- this.operatorAttentionValue = attention;
2274
+ this.metadata.operatorAttention = attention;
2331
2275
  return this;
2332
2276
  }
2333
2277
 
2334
2278
  /** @internal */
2335
2279
  commentary(commentary: string): this {
2336
- this.turnCommentary = commentary;
2280
+ if (commentary) this.metadata.commentary = commentary;
2281
+ else delete this.metadata.commentary;
2337
2282
  return this;
2338
2283
  }
2339
2284
 
2340
2285
  /** @internal */
2341
2286
  notesFields(notes: HumanTurnDefinition<TParams, TState>["notesFields"]): this {
2342
- this.notes = notes;
2287
+ if (notes) this.metadata.notesFields = notes;
2288
+ else delete this.metadata.notesFields;
2343
2289
  return this;
2344
2290
  }
2345
2291
 
@@ -2396,17 +2342,17 @@ export class ExternalRouteBuilder<
2396
2342
 
2397
2343
  /** @public */
2398
2344
  to(turnId: TurnId): this {
2399
- return this.setTarget({ kind: "to", turnId });
2345
+ return this.setTarget({ to: turnId });
2400
2346
  }
2401
2347
 
2402
2348
  /** @internal */
2403
2349
  complete(): this {
2404
- return this.setTarget({ kind: "complete" });
2350
+ return this.setTarget({ complete: true });
2405
2351
  }
2406
2352
 
2407
2353
  /** @internal */
2408
2354
  lifecycleStatus(status: ProcessTurnTerminalLifecycleStatus): this {
2409
- return this.setTarget({ kind: "lifecycleStatus", status });
2355
+ return this.setTarget({ lifecycleStatus: status });
2410
2356
  }
2411
2357
 
2412
2358
  /** @internal */
@@ -2446,7 +2392,7 @@ export class ExternalRouteBuilder<
2446
2392
  return {
2447
2393
  /** @internal */
2448
2394
  source: this.source,
2449
- ...buildRouteTargetSpec(this.target),
2395
+ ...this.target,
2450
2396
  ...(this.externalEffect
2451
2397
  ? {
2452
2398
  /** @internal */
@@ -2590,21 +2536,8 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2590
2536
  TState
2591
2537
  > {
2592
2538
  private readonly processId: string;
2593
- private processDisplayName: string | null = null;
2594
- private entryTurnId: TurnId | null = null;
2539
+ private readonly configuration: Partial<DefinedProcessInput<TParams, TState>> = {};
2595
2540
  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
2541
 
2609
2542
  /** @internal */
2610
2543
  constructor(processId: string) {
@@ -2617,13 +2550,13 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2617
2550
 
2618
2551
  /** @public */
2619
2552
  displayName(displayName: string): this {
2620
- this.processDisplayName = displayName;
2553
+ this.configuration.displayName = displayName;
2621
2554
  return this;
2622
2555
  }
2623
2556
 
2624
2557
  /** @public */
2625
2558
  entry(turnId: TurnId): this {
2626
- this.entryTurnId = turnId;
2559
+ this.configuration.entry = turnId;
2627
2560
  return this;
2628
2561
  }
2629
2562
 
@@ -2640,7 +2573,7 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2640
2573
  */
2641
2574
  /** @public */
2642
2575
  happyPath(...turnIds: readonly TurnId[]): this {
2643
- this.happyPathTurnIds = turnIds;
2576
+ this.configuration.happyPath = turnIds;
2644
2577
  return this;
2645
2578
  }
2646
2579
 
@@ -2651,14 +2584,14 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2651
2584
  /** @public */
2652
2585
  state: Codec<TState>;
2653
2586
  }): this {
2654
- this.paramsCodec = input.params;
2655
- this.stateCodec = input.state;
2587
+ this.configuration.paramsCodec = input.params;
2588
+ this.configuration.stateCodec = input.state;
2656
2589
  return this;
2657
2590
  }
2658
2591
 
2659
2592
  /** @public */
2660
2593
  initialState(fn: (params: TParams) => TState): this {
2661
- this.initialStateFn = fn;
2594
+ this.configuration.initialState = fn;
2662
2595
  return this;
2663
2596
  }
2664
2597
 
@@ -2666,7 +2599,7 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2666
2599
  repositoryCredentials(
2667
2600
  fn: NonNullable<ExtensionProcessDefinition<TParams, TState>["repositoryCredentials"]>,
2668
2601
  ): this {
2669
- this.repositoryCredentialsFn = fn;
2602
+ this.configuration.repositoryCredentials = fn;
2670
2603
  return this;
2671
2604
  }
2672
2605
 
@@ -2674,13 +2607,13 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2674
2607
  resolveStorageSize(
2675
2608
  fn: NonNullable<ExtensionProcessDefinition<TParams, TState>["resolveStorageSize"]>,
2676
2609
  ): this {
2677
- this.storageSizeResolver = fn;
2610
+ this.configuration.resolveStorageSize = fn;
2678
2611
  return this;
2679
2612
  }
2680
2613
 
2681
2614
  /** @public */
2682
2615
  piConfig(config: ProcessPiConfig): this {
2683
- this.processPiConfig = config;
2616
+ this.configuration.piConfig = config;
2684
2617
  return this;
2685
2618
  }
2686
2619
 
@@ -2690,9 +2623,18 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2690
2623
  developmentTools?: boolean;
2691
2624
  /** @public */
2692
2625
  docker?: boolean;
2626
+ /** @internal */
2627
+ repositoryCheckout?: "eager" | "on_demand" | "none";
2693
2628
  }): this {
2694
- this.developmentTools = capabilities.developmentTools === true;
2695
- this.docker = capabilities.docker === true;
2629
+ const runtime = {
2630
+ ...(capabilities.developmentTools === true ? { developmentTools: true } : {}),
2631
+ ...(capabilities.docker === true ? { docker: true } : {}),
2632
+ ...(capabilities.repositoryCheckout
2633
+ ? { repositoryCheckout: capabilities.repositoryCheckout }
2634
+ : {}),
2635
+ };
2636
+ if (Object.keys(runtime).length) this.configuration.runtime = runtime;
2637
+ else delete this.configuration.runtime;
2696
2638
  return this;
2697
2639
  }
2698
2640
 
@@ -2708,16 +2650,17 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2708
2650
 
2709
2651
  /** @public */
2710
2652
  define(): ExtensionProcessDefinition<TParams, TState> {
2711
- if (!this.processDisplayName) {
2653
+ const { displayName, entry, paramsCodec, stateCodec, initialState } = this.configuration;
2654
+ if (!displayName) {
2712
2655
  throw new Error(`Flow process '${this.processId}' must declare .displayName(...)`);
2713
2656
  }
2714
- if (!this.entryTurnId) {
2657
+ if (!entry) {
2715
2658
  throw new Error(`Flow process '${this.processId}' must declare .entry(turnId)`);
2716
2659
  }
2717
- if (!this.paramsCodec || !this.stateCodec) {
2660
+ if (!paramsCodec || !stateCodec) {
2718
2661
  throw new Error(`Flow process '${this.processId}' must declare .codecs(...)`);
2719
2662
  }
2720
- if (!this.initialStateFn) {
2663
+ if (!initialState) {
2721
2664
  throw new Error(`Flow process '${this.processId}' must declare .initialState(...)`);
2722
2665
  }
2723
2666
 
@@ -2730,42 +2673,23 @@ export class FlowProcessBuilder<TParams = unknown, TState = unknown> extends Flo
2730
2673
  }
2731
2674
 
2732
2675
  const input: DefinedProcessInput<TParams, TState> = {
2676
+ ...this.configuration,
2733
2677
  id: this.processId,
2734
- displayName: this.processDisplayName,
2735
- entry: this.entryTurnId,
2678
+ displayName,
2679
+ entry,
2736
2680
  ...(this.alternateEntryTurnIds.length > 0
2737
2681
  ? { alternateEntries: [...this.alternateEntryTurnIds] }
2738
2682
  : {}),
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 } : {}),
2683
+ paramsCodec,
2684
+ stateCodec,
2685
+ initialState,
2756
2686
  turns,
2757
2687
  ...(this.serverHooks.length > 0 ? { server: chainHooks(this.serverHooks) } : {}),
2758
2688
  ...(this.uiHooks.length > 0 ? { ui: chainHooks(this.uiHooks) } : {}),
2759
2689
  ...(this.launcherHooks.length > 0 ? { launchers: chainHooks(this.launcherHooks) } : {}),
2760
2690
  ...(this.watcherHooks.length > 0 ? { watchers: chainHooks(this.watcherHooks) } : {}),
2761
2691
  };
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;
2692
+ return defineProcess(input);
2769
2693
  }
2770
2694
  }
2771
2695
 
@@ -2775,6 +2699,13 @@ export const flow = {
2775
2699
  llm<TParams = unknown, TState = unknown>(turnId: TurnId): LlmFlowBuilder<TParams, TState> {
2776
2700
  return new LlmFlowBuilder<TParams, TState>(turnId);
2777
2701
  },
2702
+ /** Run an LLM turn sequentially over frozen items, then collect and route once. @public */
2703
+ mappedLlm<TParams = unknown, TState = unknown, TItem = unknown, TResult = unknown>(
2704
+ turnId: TurnId,
2705
+ items: FlowForEachOptions<TParams, TState, TItem, TResult>,
2706
+ ): MappedLlmFlowBuilder<TParams, TState, TItem, TResult> {
2707
+ return new MappedLlmFlowBuilder<TParams, TState, TItem, TResult>(turnId, items);
2708
+ },
2778
2709
  /** @public */
2779
2710
  automatic<TParams = unknown, TState = unknown>(
2780
2711
  turnId: TurnId,