@leitwerk-dev/process-sdk 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/{chunk-I7U6HCLN.js → chunk-HT2AXXLH.js} +2 -1
  2. package/dist/chunk-HT2AXXLH.js.map +1 -0
  3. package/dist/core-capabilities.d.ts +57 -1
  4. package/dist/core-capabilities.d.ts.map +1 -1
  5. package/dist/define-process.d.ts +43 -26
  6. package/dist/define-process.d.ts.map +1 -1
  7. package/dist/{extension-api-3Vr3RE8S.d.ts → extension-api-Ljc4UTZ0.d.ts} +440 -49
  8. package/dist/extension-api.d.ts +66 -0
  9. package/dist/extension-api.d.ts.map +1 -1
  10. package/dist/external-source-poll.d.ts +1 -1
  11. package/dist/external-source-poll.d.ts.map +1 -1
  12. package/dist/file-external-source.d.ts +32 -0
  13. package/dist/file-external-source.d.ts.map +1 -0
  14. package/dist/flow-mapped.typecheck.d.ts +2 -0
  15. package/dist/flow-mapped.typecheck.d.ts.map +1 -0
  16. package/dist/flow.d.ts +234 -118
  17. package/dist/flow.d.ts.map +1 -1
  18. package/dist/index.d.ts +15 -7
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +4189 -3534
  21. package/dist/index.js.map +1 -1
  22. package/dist/mapped-turn.d.ts +169 -0
  23. package/dist/mapped-turn.d.ts.map +1 -0
  24. package/dist/outcome-contract.d.ts +19 -0
  25. package/dist/outcome-contract.d.ts.map +1 -0
  26. package/dist/outcome-schema.d.ts +23 -0
  27. package/dist/outcome-schema.d.ts.map +1 -0
  28. package/dist/pi-config-public.js +1 -1
  29. package/dist/pi-config.js +1 -1
  30. package/dist/process-flow-view.d.ts +3 -14
  31. package/dist/process-flow-view.d.ts.map +1 -1
  32. package/dist/process-graph.d.ts +10 -4
  33. package/dist/process-graph.d.ts.map +1 -1
  34. package/dist/scoped-settings.d.ts +87 -0
  35. package/dist/scoped-settings.d.ts.map +1 -0
  36. package/dist/ticket-creation.d.ts +24 -0
  37. package/dist/ticket-creation.d.ts.map +1 -0
  38. package/dist/turn-semantics.d.ts +3 -3
  39. package/dist/turn-semantics.d.ts.map +1 -1
  40. package/dist/turn-wait.d.ts +53 -0
  41. package/dist/turn-wait.d.ts.map +1 -0
  42. package/dist/types.d.ts +45 -24
  43. package/dist/types.d.ts.map +1 -1
  44. package/package.json +6 -6
  45. package/src/core-capabilities.ts +76 -1
  46. package/src/define-process.ts +447 -540
  47. package/src/extension-api.ts +78 -0
  48. package/src/external-source-poll.ts +6 -24
  49. package/src/file-external-source.ts +135 -0
  50. package/src/flow-mapped.typecheck.ts +136 -0
  51. package/src/flow.ts +888 -532
  52. package/src/index.ts +77 -2
  53. package/src/mapped-turn.ts +437 -0
  54. package/src/outcome-contract.ts +126 -0
  55. package/src/outcome-schema.ts +314 -0
  56. package/src/process-flow-view.ts +84 -346
  57. package/src/process-graph.ts +95 -45
  58. package/src/scoped-settings.ts +113 -0
  59. package/src/ticket-creation.ts +113 -0
  60. package/src/turn-semantics.ts +102 -116
  61. package/src/turn-wait.ts +76 -0
  62. package/src/types.ts +44 -22
  63. package/dist/chunk-I7U6HCLN.js.map +0 -1
@@ -17,6 +17,7 @@ import type { ExternalWrites } from "@leitwerk-dev/external-writes";
17
17
  import type { WatcherPresentationField } from "@leitwerk-dev/protocol";
18
18
  import type { CapabilityToken } from "./capabilities.js";
19
19
  import type { FormDefinition } from "./form-contract.js";
20
+ import type { ScopedSettingsDeclaration } from "./scoped-settings.js";
20
21
 
21
22
  export type { FormDefinition, FormFieldDefinition } from "./form-contract.js";
22
23
 
@@ -33,6 +34,7 @@ import type {
33
34
  LauncherValidationError,
34
35
  UiLauncherSummaryBase,
35
36
  } from "./launcher-contract.js";
37
+ import type { MappedTurnIteration } from "./mapped-turn.js";
36
38
  import type { ModelProviderSet } from "./model-provider.js";
37
39
  import type {
38
40
  ServerExtensionEventMap,
@@ -88,6 +90,15 @@ export type LauncherVisibility = "ui";
88
90
 
89
91
  /** @public */
90
92
  export interface ProcessLaunchProjectConfig {
93
+ /** Provider-verified identity and clone aliases from launcher discovery. @public */
94
+ settingsRepository?: {
95
+ /** @public */
96
+ origin: string;
97
+ /** @public */
98
+ repositoryId: string | number;
99
+ /** @public */
100
+ aliases?: readonly string[];
101
+ };
91
102
  /** @public */
92
103
  key: string;
93
104
  /** @public */
@@ -114,6 +125,10 @@ export interface ProcessTitleSourceField {
114
125
 
115
126
  /** @public */
116
127
  export interface ProcessLaunchConfig<TParams = unknown> {
128
+ /** Repository key used for process-wide scoped model defaults. @public */
129
+ primaryRepositoryKey?: string;
130
+ /** Trusted integration scope bindings, retained with the process. @public */
131
+ settingsContext?: import("@leitwerk-dev/domain").SettingsContext;
117
132
  /** @public */
118
133
  processId: string;
119
134
  /** @public */
@@ -230,6 +245,16 @@ export interface UiLauncherDefinition<TParams = unknown> {
230
245
  input: Record<string, unknown>,
231
246
  launchConfig: ProcessLaunchConfig<TParams>,
232
247
  ): readonly LaunchPreparationCheck<TParams>[];
248
+ /**
249
+ * Resolve form validation and model settings without preparing execution resources.
250
+ * May omit projects that do not affect model/settings resolution. Params must pass
251
+ * the process codec. Never used for submission; falls back to resolveLaunchConfig.
252
+ * @public
253
+ */
254
+ resolvePreviewConfig?(
255
+ input: Record<string, unknown>,
256
+ ctx: LauncherContext,
257
+ ): UiLauncherConfigResolution<TParams> | Promise<UiLauncherConfigResolution<TParams>>;
233
258
  /** @public */
234
259
  resolveLaunchConfig(
235
260
  input: Record<string, unknown>,
@@ -323,6 +348,8 @@ export interface ProcessLaunchPlanProcessInput extends ProcessCustomizableFields
323
348
 
324
349
  /** @internal */
325
350
  export interface ProcessLaunchPlan {
351
+ /** A form/model preview; execution resources may be omitted and this plan must not be committed. @internal */
352
+ preview?: true;
326
353
  /** @internal */
327
354
  launcherId: string;
328
355
  /** @internal */
@@ -403,6 +430,12 @@ export interface ProcessLauncherService {
403
430
  input: Record<string, unknown>,
404
431
  ctx?: LauncherContext,
405
432
  ): Promise<UiLauncherResolutionResult>;
433
+ /** Resolve only for form validation/defaults/model preview; never commit this result. @internal */
434
+ resolveUiLauncherPreview(
435
+ launcherId: string,
436
+ input: Record<string, unknown>,
437
+ ctx?: LauncherContext,
438
+ ): Promise<UiLauncherResolutionResult>;
406
439
  }
407
440
 
408
441
  /** Resolve a UI launcher summary by id, returning `null` when it is unknown. @internal */
@@ -425,6 +458,21 @@ export interface ProcessTurnOutcomeEvent {
425
458
  params: Record<string, unknown>;
426
459
  /** @internal */
427
460
  turnResultMarkdown?: string | null;
461
+ /** Durable output produced by this turn's preparation phase. @public */
462
+ prepared?: unknown;
463
+ }
464
+
465
+ /** Expected outcome-planning rejection safe to persist and show to operators. @public */
466
+ export class SafeOutcomePlanningError extends Error {
467
+ /** @public */
468
+ constructor(
469
+ /** Stable machine-readable failure code. @public */
470
+ readonly code: string,
471
+ message: string,
472
+ ) {
473
+ super(message);
474
+ this.name = "SafeOutcomePlanningError";
475
+ }
428
476
  }
429
477
 
430
478
  /** @internal */
@@ -460,6 +508,8 @@ export interface LeafOutcomeCaptureContext<TParams = unknown, TState = unknown>
460
508
  };
461
509
  /** @internal */
462
510
  readonly turnRecord: ProcessTurnRecord | null;
511
+ /** Accepted result of this mapped item, when available. @internal */
512
+ readonly mappedResult?: unknown;
463
513
  /** @internal */
464
514
  readTreeEntry(entryId: string): PiTreeEntry | null;
465
515
  /** @internal */
@@ -689,9 +739,23 @@ export interface ServerProcessContext<TParams = unknown, TState = unknown>
689
739
  applyLifecycleEffects?(effects: ProcessLifecycleEffects): void;
690
740
  }
691
741
 
742
+ /** @internal */
743
+ export interface TurnDiagnosticReport {
744
+ /** @internal */
745
+ level: "debug" | "info" | "warn" | "error";
746
+ /** @internal */
747
+ code: string;
748
+ /** @internal */
749
+ message: string;
750
+ /** Non-secret diagnostic metadata. @internal */
751
+ details?: Record<string, unknown>;
752
+ }
753
+
692
754
  /** @public */
693
755
  export interface WorkerProcessContext<TParams = unknown, TState = unknown>
694
756
  extends ProcessSnapshotContext<TParams, TState> {
757
+ /** Immutable non-secret values captured for this turn. @public */
758
+ readonly scopedSettings?: import("@leitwerk-dev/domain").ScopedSettingsSnapshot;
695
759
  /** @internal */
696
760
  readonly turnResultMarkdownBySemanticRef?: Partial<Record<ProcessSemanticEntryRefKey, string>>;
697
761
  /** @internal */
@@ -700,10 +764,14 @@ export interface WorkerProcessContext<TParams = unknown, TState = unknown>
700
764
  readonly workspaceRoot?: string;
701
765
  /** Durable output produced by this LLM turn's preparation phase, when declared. @internal */
702
766
  readonly prepared?: unknown;
767
+ /** Active frozen item of a mapped LLM turn. @internal */
768
+ readonly iteration?: MappedTurnIteration;
703
769
  /** Invoke a server-owned integration tool authorized for this automatic turn or LLM preparation. @internal */
704
770
  callIntegrationTool?(name: string, args: Record<string, unknown>): Promise<unknown>;
705
771
  /** Replace the durable operator-facing progress report for this turn attempt. @internal */
706
772
  reportProgress?(report: TurnProgressReport): void;
773
+ /** Append a non-secret worker diagnostic correlated with this turn attempt. @internal */
774
+ reportDiagnostic?(report: TurnDiagnosticReport): void;
707
775
  }
708
776
 
709
777
  /** @public */
@@ -859,6 +927,8 @@ export interface RepositoryCredentialRegistrar {
859
927
 
860
928
  /** @public */
861
929
  export interface ProcessRuntimeCapabilities {
930
+ /** Choose eager clones, on-demand checkout, or no local checkout. @public */
931
+ readonly repositoryCheckout?: "eager" | "on_demand" | "none";
862
932
  /** Install repository-declared development tools with mise before accepting work. @internal */
863
933
  readonly developmentTools?: boolean;
864
934
  /** Require a Docker CLI connected to a private or explicitly acknowledged daemon. @public */
@@ -1023,6 +1093,8 @@ export interface TicketCreationCapability {
1023
1093
  readonly titlePath?: string;
1024
1094
  /** RFC 6901 JSON Pointer into the tool arguments. @public */
1025
1095
  readonly descriptionPath?: string;
1096
+ /** Read-only issue preview format; defaults to plain text. @public */
1097
+ readonly descriptionFormat?: "plain" | "markdown";
1026
1098
  /** @public */
1027
1099
  readonly destinations?: TicketCreationDestinationProvider;
1028
1100
  }
@@ -1039,6 +1111,8 @@ export interface TicketCreationReceipt {
1039
1111
 
1040
1112
  /** @public */
1041
1113
  export interface IntegrationToolExecutionContext {
1114
+ /** Replace the current running attempt's operator-facing progress. Late updates are ignored. @public */
1115
+ reportProgress(report: TurnProgressReport): void;
1042
1116
  /** Process-bound coordination; storage remains server-owned. */
1043
1117
  /** @public */
1044
1118
  readonly externalWrites: ExternalWrites;
@@ -1060,6 +1134,8 @@ export interface IntegrationToolExecutionContext {
1060
1134
 
1061
1135
  /** @public */
1062
1136
  export interface IntegrationToolDefinition<TArgs = Record<string, unknown>> {
1137
+ /** Omit from model tools while retaining runtime authorization; defaults to true. @public */
1138
+ modelVisible?: boolean;
1063
1139
  /** @public */
1064
1140
  readonly name: string;
1065
1141
  /** @public */
@@ -1106,6 +1182,8 @@ export interface WorkerExtensionAPI {
1106
1182
 
1107
1183
  /** @public */
1108
1184
  export interface LeitwerkExtensionModule {
1185
+ /** Non-secret scoped settings and execution purposes. @public */
1186
+ scopedSettings?: ScopedSettingsDeclaration;
1109
1187
  /** @public */
1110
1188
  manifest: {
1111
1189
  /** @public */
@@ -57,7 +57,10 @@ export function createExternalSourcePollReporter(
57
57
  return fired.ok;
58
58
  },
59
59
  /** @public */
60
- observe(armed: Arming, input: Pick<ExternalObservationInput, "observation" | "refreshError">) {
60
+ observe(
61
+ armed: Arming,
62
+ input: Pick<ExternalObservationInput, "observation" | "refreshError" | "state">,
63
+ ) {
61
64
  if (current(armed) && sources.observe && armed.generation)
62
65
  return sources.observe({
63
66
  instanceId: armed.instanceId,
@@ -78,34 +81,13 @@ export interface ExternalSourcePollReporter {
78
81
  /** @public */
79
82
  observe(
80
83
  armed: Arming,
81
- input: Pick<ExternalObservationInput, "observation" | "refreshError">,
84
+ input: Pick<ExternalObservationInput, "observation" | "refreshError" | "state">,
82
85
  ): ReturnType<NonNullable<ExternalSourceServiceLike["observe"]>> | undefined;
83
86
  /** Compare the captured identity, generation and resolved value with a live subscription. @public */
84
87
  isCurrent(kind: string, armed: Arming): boolean;
85
88
  }
86
89
  /** A captured generation and resolved identity must still be armed after provider I/O. @internal */
87
- function sameSubscription(
88
- captured: {
89
- /** @internal */
90
- id: string;
91
- /** @internal */
92
- instanceId: string;
93
- /** @internal */
94
- generation?: string;
95
- /** @internal */
96
- resolved: unknown;
97
- },
98
- current: {
99
- /** @internal */
100
- id: string;
101
- /** @internal */
102
- instanceId: string;
103
- /** @internal */
104
- generation?: string;
105
- /** @internal */
106
- resolved: unknown;
107
- },
108
- ): boolean {
90
+ function sameSubscription(captured: Arming, current: Arming): boolean {
109
91
  return (
110
92
  current.id === captured.id &&
111
93
  current.instanceId === captured.instanceId &&
@@ -0,0 +1,135 @@
1
+ import { readFile, unlink } from "node:fs/promises";
2
+ import { emptyPollResult, parseDurationMs } from "@leitwerk-dev/watcher-utils";
3
+ import type { CoreServerSetupDeps } from "./core-capabilities.js";
4
+ import type { ExternalActionSource } from "./extension-api.js";
5
+ import { isEnoent } from "./fs-utils.js";
6
+
7
+ /** @internal */
8
+ export interface FileExternalInput {
9
+ /** @internal */
10
+ path: string;
11
+ /** @internal */
12
+ pollInterval: string;
13
+ /** @internal */
14
+ consume: "delete" | "keep";
15
+ }
16
+
17
+ /** @internal */
18
+ export function defineFileExternalSource(
19
+ input: FileExternalInput,
20
+ metadata: Pick<ExternalActionSource, "kind" | "label" | "description" | "inputMode">,
21
+ ): ExternalActionSource {
22
+ const config = { path: input.path, pollInterval: input.pollInterval, consume: input.consume };
23
+ return {
24
+ ...metadata,
25
+ config,
26
+ resolve: (ctx) => ({
27
+ ...config,
28
+ path: config.path.replaceAll("{instanceId}", ctx.process.id),
29
+ }),
30
+ };
31
+ }
32
+
33
+ function parseFileConfig(value: unknown): FileExternalInput | null {
34
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
35
+ const record = value as Record<string, unknown>;
36
+ if (typeof record.path !== "string" || record.path.trim() === "") return null;
37
+ return {
38
+ path: record.path,
39
+ pollInterval: typeof record.pollInterval === "string" ? record.pollInterval : "1s",
40
+ consume: record.consume === "keep" ? "keep" : "delete",
41
+ };
42
+ }
43
+
44
+ /** A missing file is distinct from an empty presence trigger. @internal */
45
+ export async function readTriggerFile(filePath: string): Promise<string | null> {
46
+ try {
47
+ return await readFile(filePath, "utf8");
48
+ } catch (error) {
49
+ if (isEnoent(error)) return null;
50
+ throw error;
51
+ }
52
+ }
53
+
54
+ /** @internal */
55
+ export async function consumeTriggerFile(filePath: string): Promise<void> {
56
+ try {
57
+ await unlink(filePath);
58
+ } catch (error) {
59
+ if (!isEnoent(error)) throw error;
60
+ }
61
+ }
62
+
63
+ function applyAlias(config: FileExternalInput, aliases: Partial<Record<string, string>>) {
64
+ const exact = aliases[config.path];
65
+ if (exact) return { ...config, path: exact };
66
+ for (const [template, replacement] of Object.entries(aliases)) {
67
+ if (!replacement || !template.includes("{instanceId}")) continue;
68
+ const [prefix, suffix = ""] = template.split("{instanceId}");
69
+ if (!prefix || !config.path.startsWith(prefix) || !config.path.endsWith(suffix)) continue;
70
+ const instanceId = config.path.slice(prefix.length, config.path.length - suffix.length);
71
+ return { ...config, path: replacement.replaceAll("{instanceId}", instanceId) };
72
+ }
73
+ return config;
74
+ }
75
+
76
+ /** Poll extension-owned file sources, consuming triggers only after successful admission. @internal */
77
+ export function createFileExternalSourceProvider(
78
+ deps: CoreServerSetupDeps,
79
+ options: {
80
+ /** @internal */
81
+ id: string;
82
+ /** @internal */
83
+ kind: string;
84
+ /** @internal */
85
+ inputMode: "none" | "instruction";
86
+ /** @internal */
87
+ aliases?: Partial<Record<string, string>>;
88
+ },
89
+ ) {
90
+ const nextDueAt = new Map<string, number>();
91
+ return deps.polling.create({
92
+ id: options.id,
93
+ pollInterval: () => "50ms",
94
+ isEnabled: () => true,
95
+ defaultIntervalMs: 50,
96
+ async pollOnce() {
97
+ const result = emptyPollResult();
98
+ const activeKeys = new Set<string>();
99
+ for (const armed of deps.externalSources.listArmed(options.kind)) {
100
+ const parsed = parseFileConfig(armed.resolved) ?? parseFileConfig(armed.source.config);
101
+ if (!parsed) {
102
+ result.errors.push(`${armed.id}:invalid_config`);
103
+ continue;
104
+ }
105
+ const config = applyAlias(parsed, options.aliases ?? {});
106
+ const key = `${armed.instanceId}:${armed.id}`;
107
+ activeKeys.add(key);
108
+ const now = Date.now();
109
+ if ((nextDueAt.get(key) ?? 0) > now) continue;
110
+ nextDueAt.set(key, now + parseDurationMs(config.pollInterval, 1_000));
111
+ const content = await readTriggerFile(config.path);
112
+ if (content === null || (options.inputMode === "instruction" && !content.trim())) continue;
113
+ const fired = await deps.externalSources.fire({
114
+ instanceId: armed.instanceId,
115
+ armingId: armed.id,
116
+ ...(options.inputMode === "instruction"
117
+ ? { input: { instruction: content.trim() } }
118
+ : {}),
119
+ event: { path: config.path, pollInterval: config.pollInterval },
120
+ mergeKey: config.path,
121
+ });
122
+ if (!fired.ok) {
123
+ result.errors.push(`${armed.id}:${fired.code ?? fired.error ?? "fire_failed"}`);
124
+ continue;
125
+ }
126
+ if (config.consume === "delete") await consumeTriggerFile(config.path);
127
+ result.created.push(armed.id);
128
+ }
129
+ for (const key of nextDueAt.keys()) {
130
+ if (!activeKeys.has(key)) nextDueAt.delete(key);
131
+ }
132
+ return result;
133
+ },
134
+ });
135
+ }
@@ -0,0 +1,136 @@
1
+ import { type Codec, type FlowForEachOptions, flow } from "./index.js";
2
+
3
+ interface Params {
4
+ prefix: string;
5
+ }
6
+ interface State {
7
+ kept: string[];
8
+ }
9
+ interface Item {
10
+ id: string;
11
+ }
12
+ interface Result {
13
+ id: string;
14
+ keep: boolean;
15
+ }
16
+
17
+ // Compiled but never called: check the supported authoring API and its forbidden capabilities.
18
+ function checkMappedAuthoring(itemCodec: Codec<Item>, resultCodec: Codec<Result>) {
19
+ const items: FlowForEachOptions<Params, State, Item, Result> = {
20
+ items: ({ state }) => state.kept.map((id) => ({ id })),
21
+ itemCodec,
22
+ resultCodec,
23
+ key: ({ item }) => item.id,
24
+ };
25
+ // Infer all four types from a typed item source.
26
+ const mapped = flow
27
+ .mappedLlm("assess", items)
28
+ .description("Assess one item")
29
+ .consume("plan")
30
+ .prepare(async (ctx) => {
31
+ const item: Item = ctx.item;
32
+ const state: State = ctx.state;
33
+ const params: Params = ctx.params;
34
+ // @ts-expect-error Preparation cannot route the item.
35
+ ctx.to("next");
36
+ return { label: `${params.prefix}${item.id}`, count: state.kept.length };
37
+ })
38
+ .optionalConsume("review")
39
+ .waitFor(({ params, state }) => {
40
+ const prefix: string = params.prefix;
41
+ const kept: string[] = state.kept;
42
+ return prefix.length > 0 && kept.length > 0;
43
+ })
44
+ .askQuestions()
45
+ .executionPurpose("assessment")
46
+ .resolveIntegrationTools((params, state) => [params.prefix, ...state.kept])
47
+ .fullPrimary()
48
+ .continueFromPrimaryLeaf()
49
+ .buildPrompt((ctx) => {
50
+ const label: string = ctx.prepared.label;
51
+ const count: number = ctx.prepared.count;
52
+ const item: Item = ctx.item;
53
+ const plan: string | undefined = ctx.input.plan;
54
+ const review: string | undefined = ctx.input.review;
55
+ // @ts-expect-error Prepared data preserves its inferred property types.
56
+ const invalid: string = ctx.prepared.count;
57
+ void invalid;
58
+ // @ts-expect-error Only declared products are available.
59
+ ctx.input.undeclared;
60
+ // @ts-expect-error Items retain the codec's type.
61
+ ctx.item.missing;
62
+ return `${label} ${count} ${item.id} ${plan} ${review}`;
63
+ })
64
+ .outcomeTool("assessed", (outcome) => {
65
+ // @ts-expect-error Item outcomes cannot route.
66
+ outcome.to("next");
67
+ // @ts-expect-error Item outcomes cannot change business state.
68
+ outcome.state(() => ({ kept: [] }));
69
+ // @ts-expect-error Item outcomes cannot publish products.
70
+ outcome.markdown("review", { publish: true });
71
+ // @ts-expect-error Item yields must match the result codec.
72
+ outcome.yield(() => ({ id: "a", keep: "yes" }));
73
+ return outcome
74
+ .description("Assessed")
75
+ .requiredBoolean("keep")
76
+ .yield(({ ctx, event }) => ({ id: ctx.item.id, keep: event.params.keep === true }));
77
+ });
78
+ // @ts-expect-error Mapped turns have no ordinary completion path after context refinement.
79
+ mapped.end("done");
80
+ // @ts-expect-error Mapped turns cannot publish products.
81
+ mapped.publish("review");
82
+ // @ts-expect-error Collection must return the process state.
83
+ mapped.collect(() => ({ wrong: true }));
84
+ const collected = mapped.collect(({ params, state }, results) => {
85
+ const typed: readonly Result[] = results;
86
+ // @ts-expect-error Collection receives ordered, read-only results.
87
+ results.push({ id: "a", keep: true });
88
+ // @ts-expect-error Result fields remain typed after all common configuration.
89
+ const invalid: string = results[0].keep;
90
+ void invalid;
91
+ return { ...state, kept: typed.filter((r) => r.keep).map((r) => `${params.prefix}${r.id}`) };
92
+ });
93
+ collected.routeByState({ again: "assess", done: "review" }, ({ state }) =>
94
+ state.kept.length ? "again" : "done",
95
+ );
96
+ // @ts-expect-error Item authoring ends at collection.
97
+ collected.outcomeTool("late", () => undefined);
98
+
99
+ // Explicit generic arguments remain available for inline sources.
100
+ flow.mappedLlm<Params, State, Item, Result>("explicit", {
101
+ ...items,
102
+ key: ({ item }) => item.id,
103
+ });
104
+ // Codecs infer item/result types when process types are unnecessary.
105
+ flow
106
+ .mappedLlm("inferred", { items: () => [], itemCodec, resultCodec, key: ({ item }) => item.id })
107
+ .prepare(({ item }) => ({ name: item.id }))
108
+ .consume("plan")
109
+ .buildPrompt(({ item, prepared, input }) => `${item.id}${prepared.name}${input.plan}`)
110
+ .outcomeTool("done", (outcome) =>
111
+ outcome.description("Done").yield(({ ctx }) => ({ id: ctx.item.id, keep: true })),
112
+ )
113
+ .collect((_ctx, results) => results.map((result) => result.keep));
114
+
115
+ const ordinary = flow
116
+ .llm<Params, State>("ordinary")
117
+ .optionalConsume("review")
118
+ .prepare(({ params }) => ({ label: params.prefix }))
119
+ .consume("plan")
120
+ .buildPrompt((ctx) => {
121
+ // @ts-expect-error Ordinary prompts do not receive mapped items.
122
+ ctx.item;
123
+ return `${ctx.prepared.label}${ctx.input.plan}${ctx.input.review}`;
124
+ });
125
+ ordinary.outcomeTool("done", (outcome) =>
126
+ outcome
127
+ .description("Done")
128
+ .state(({ ctx }) => ctx.state)
129
+ .complete(),
130
+ );
131
+ // @ts-expect-error Ordinary turns cannot be converted into mapped turns.
132
+ ordinary.forEach(items);
133
+ // @ts-expect-error Ordinary builders retain ordinary completion after context refinement.
134
+ ordinary.collect(() => ({ kept: [] }));
135
+ }
136
+ void checkMappedAuthoring;