@leitwerk-dev/process-sdk 0.3.0 → 0.3.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.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  RESERVED_INTEGRATION_TOOL_NAMES,
3
3
  validatePiBuiltInToolArray
4
- } from "./chunk-I7U6HCLN.js";
4
+ } from "./chunk-GVBLXKSR.js";
5
5
  import {
6
6
  cloneArrayValueMap,
7
7
  cloneMap,
@@ -49,6 +49,191 @@ import {
49
49
  trimString as normalizeEffectString,
50
50
  normalizeStringArray as normalizeEffectStringArray
51
51
  } from "@leitwerk-dev/domain";
52
+
53
+ // src/extension-api.ts
54
+ var SafeLaunchPreparationError = class extends Error {
55
+ /** @public */
56
+ constructor(message, safeSummary) {
57
+ super(message);
58
+ this.safeSummary = safeSummary;
59
+ this.name = "SafeLaunchPreparationError";
60
+ }
61
+ safeSummary;
62
+ };
63
+ function findUiLauncherById(launcherService, launcherId) {
64
+ return launcherService.listUiLaunchers().find((launcher) => launcher.id === launcherId) ?? null;
65
+ }
66
+ var SafeOutcomePlanningError = class extends Error {
67
+ /** @public */
68
+ constructor(code, message) {
69
+ super(message);
70
+ this.code = code;
71
+ this.name = "SafeOutcomePlanningError";
72
+ }
73
+ code;
74
+ };
75
+
76
+ // src/mapped-turn.ts
77
+ var MAPPED_ITEM_KEY_MAX_LENGTH = 200;
78
+ var MAPPED_ITEM_LABEL_MAX_LENGTH = 200;
79
+ var MAPPED_ITEM_MAX_COUNT = 500;
80
+ var MAPPED_COLLECT_TRIGGER = "collect";
81
+ function mappedCollectTrigger(branchId) {
82
+ return branchId === void 0 ? MAPPED_COLLECT_TRIGGER : `${MAPPED_COLLECT_TRIGGER}:${branchId}`;
83
+ }
84
+ function toJsonValue(value, context) {
85
+ let json;
86
+ try {
87
+ json = JSON.stringify(value);
88
+ } catch {
89
+ json = void 0;
90
+ }
91
+ if (json === void 0) {
92
+ throw new SafeOutcomePlanningError("invalid_mapped_value", `${context} is not JSON`);
93
+ }
94
+ return json;
95
+ }
96
+ function plainText(value) {
97
+ return value.replace(/\s+/g, " ").trim();
98
+ }
99
+ function errorMessage(error) {
100
+ return error instanceof Error ? error.message : String(error);
101
+ }
102
+ function freezeMappedItems(turnId, spec, ctx) {
103
+ const raw = spec.items(ctx) ?? [];
104
+ if (!Array.isArray(raw)) {
105
+ throw new SafeOutcomePlanningError(
106
+ "invalid_mapped_items",
107
+ `Mapped turn '${turnId}' items must be an array`
108
+ );
109
+ }
110
+ if (raw.length > MAPPED_ITEM_MAX_COUNT) {
111
+ throw new SafeOutcomePlanningError(
112
+ "invalid_mapped_items",
113
+ `Mapped turn '${turnId}' may freeze at most ${MAPPED_ITEM_MAX_COUNT} items`
114
+ );
115
+ }
116
+ const parsed = [];
117
+ const items = [];
118
+ const keys = /* @__PURE__ */ new Set();
119
+ for (const [index, value] of raw.entries()) {
120
+ let item;
121
+ try {
122
+ item = spec.itemCodec.parse(value);
123
+ } catch (error) {
124
+ throw new SafeOutcomePlanningError(
125
+ "invalid_mapped_item",
126
+ `Mapped turn '${turnId}' item ${index} is invalid: ${errorMessage(error)}`
127
+ );
128
+ }
129
+ const key = spec.key({ item, index });
130
+ if (typeof key !== "string" || key.trim() === "" || key.length > MAPPED_ITEM_KEY_MAX_LENGTH) {
131
+ throw new SafeOutcomePlanningError(
132
+ "invalid_mapped_item_key",
133
+ `Mapped turn '${turnId}' item ${index} needs a non-empty key of at most ${MAPPED_ITEM_KEY_MAX_LENGTH} characters`
134
+ );
135
+ }
136
+ if (keys.has(key)) {
137
+ throw new SafeOutcomePlanningError(
138
+ "duplicate_mapped_item_key",
139
+ `Mapped turn '${turnId}' repeats item key '${key}'`
140
+ );
141
+ }
142
+ keys.add(key);
143
+ const rawLabel = spec.label ? spec.label({ item, index }) : key;
144
+ const label = plainText(typeof rawLabel === "string" ? rawLabel : "") || key;
145
+ parsed.push(item);
146
+ items.push({
147
+ index,
148
+ key,
149
+ label: label.slice(0, MAPPED_ITEM_LABEL_MAX_LENGTH),
150
+ itemJson: toJsonValue(
151
+ spec.itemCodec.serialize(item),
152
+ `Mapped turn '${turnId}' item '${key}'`
153
+ )
154
+ });
155
+ }
156
+ return {
157
+ items,
158
+ ...spec.stateAfterSnapshot ? {
159
+ state: spec.stateAfterSnapshot({
160
+ params: ctx.params,
161
+ state: ctx.state,
162
+ items: parsed
163
+ })
164
+ } : {}
165
+ };
166
+ }
167
+ async function yieldMappedItemResult(input) {
168
+ const yieldResult = input.spec.yields[input.event.outcome];
169
+ if (!yieldResult) {
170
+ throw new SafeOutcomePlanningError(
171
+ "unknown_mapped_outcome",
172
+ `Mapped turn '${input.turnId}' has no result for outcome '${input.event.outcome}'`
173
+ );
174
+ }
175
+ const item = input.spec.itemCodec.parse(input.iteration.item);
176
+ const value = await yieldResult({
177
+ ctx: {
178
+ ...input.ctx,
179
+ item,
180
+ itemKey: input.iteration.itemKey,
181
+ itemLabel: input.iteration.itemLabel,
182
+ itemIndex: input.iteration.itemIndex,
183
+ itemCount: input.iteration.itemCount
184
+ },
185
+ event: input.event
186
+ });
187
+ let result;
188
+ try {
189
+ result = input.spec.resultCodec.parse(value);
190
+ } catch (error) {
191
+ throw new SafeOutcomePlanningError(
192
+ "invalid_mapped_result",
193
+ `Mapped turn '${input.turnId}' produced an invalid result for item '${input.iteration.itemKey}': ${errorMessage(error)}`
194
+ );
195
+ }
196
+ return toJsonValue(
197
+ input.spec.resultCodec.serialize(result),
198
+ `Mapped turn '${input.turnId}' result for item '${input.iteration.itemKey}'`
199
+ );
200
+ }
201
+ async function collectMappedResults(input) {
202
+ const results = input.resultJsons.map((json, index) => {
203
+ try {
204
+ return input.spec.resultCodec.parse(JSON.parse(json));
205
+ } catch (error) {
206
+ throw new SafeOutcomePlanningError(
207
+ "invalid_mapped_result",
208
+ `Mapped turn '${input.turnId}' stored an invalid result at item ${index}: ${errorMessage(error)}`
209
+ );
210
+ }
211
+ });
212
+ const state = await input.spec.collect(input.ctx, results);
213
+ const routing = input.spec.routing;
214
+ if (routing.kind === "static") {
215
+ return {
216
+ state,
217
+ route: {
218
+ trigger: mappedCollectTrigger(),
219
+ ...routing.to !== void 0 ? { nextTurnId: routing.to } : {},
220
+ ...routing.lifecycleStatus !== void 0 ? { lifecycleStatus: routing.lifecycleStatus } : {}
221
+ }
222
+ };
223
+ }
224
+ const branchId = await routing.choose({ ...input.ctx, state });
225
+ if (!Object.hasOwn(routing.branches, branchId)) {
226
+ throw new Error(
227
+ `Mapped turn '${input.turnId}' collection selected unknown branch '${branchId}'`
228
+ );
229
+ }
230
+ return {
231
+ state,
232
+ route: { trigger: mappedCollectTrigger(branchId), nextTurnId: routing.branches[branchId] }
233
+ };
234
+ }
235
+
236
+ // src/define-process.ts
52
237
  function createProcessTurnBinding(definition, transitions) {
53
238
  const binding = { definition };
54
239
  if (transitions && transitions.length > 0) {
@@ -510,6 +695,56 @@ function compileTurnOutcomeDefinitions(input) {
510
695
  routings
511
696
  };
512
697
  }
698
+ function compileMappedTurnTransitions(input) {
699
+ const mapped = input.spec.forEach;
700
+ if (!mapped) return [];
701
+ const outcomes = Object.entries(input.spec.outcomes ?? {});
702
+ if (outcomes.length === 0) {
703
+ throw new Error(`Mapped turn '${input.turnId}' must declare at least one outcome tool`);
704
+ }
705
+ if (input.spec.turnEnd) {
706
+ throw new Error(`Mapped turn '${input.turnId}' cannot declare a turnEnd result`);
707
+ }
708
+ for (const [outcome, spec] of outcomes) {
709
+ if ("branches" in spec || hasDeclaredStaticRouteTarget(spec) || spec.effect || spec.lifecycleIntent || spec.publishedProduct) {
710
+ throw new Error(
711
+ `Mapped turn '${input.turnId}' outcome '${outcome}' cannot route, change state, or publish; collect results instead`
712
+ );
713
+ }
714
+ if (!Object.hasOwn(mapped.yields, outcome)) {
715
+ throw new Error(
716
+ `Mapped turn '${input.turnId}' outcome '${outcome}' must declare .yield(...)`
717
+ );
718
+ }
719
+ }
720
+ const routing = mapped.routing;
721
+ if (routing.kind === "static") {
722
+ const target = normalizeStaticRouteTarget(
723
+ `Mapped turn '${input.turnId}' collection`,
724
+ {
725
+ ...routing.to !== void 0 ? { to: routing.to } : {},
726
+ ...routing.lifecycleStatus !== void 0 ? { lifecycleStatus: routing.lifecycleStatus } : {}
727
+ },
728
+ input.knownTurnIds
729
+ );
730
+ return [{ ...target, trigger: mappedCollectTrigger() }];
731
+ }
732
+ const branches = Object.entries(routing.branches);
733
+ if (branches.length === 0) {
734
+ throw new Error(`Mapped turn '${input.turnId}' collection must declare at least one branch`);
735
+ }
736
+ return branches.map(([branchId, to]) => {
737
+ if (branchId.trim() === "") {
738
+ throw new Error(`Mapped turn '${input.turnId}' collection contains an empty branch id`);
739
+ }
740
+ const target = normalizeStaticRouteTarget(
741
+ `Mapped turn '${input.turnId}' collection branch '${branchId}'`,
742
+ { to },
743
+ input.knownTurnIds
744
+ );
745
+ return { ...target, trigger: mappedCollectTrigger(branchId) };
746
+ });
747
+ }
513
748
  function addActionUse(input) {
514
749
  const existing = input.actionUses.get(input.actionId) ?? [];
515
750
  if (existing.some((candidate) => candidate.turnId === input.use.turnId)) {
@@ -891,6 +1126,21 @@ function buildDefinedProcess(input) {
891
1126
  const actionUses = /* @__PURE__ */ new Map();
892
1127
  const executableTurns = /* @__PURE__ */ new Map();
893
1128
  for (const [turnId, turnSpec] of turnEntries) {
1129
+ if (turnSpec.kind === "llm" && turnSpec.forEach) {
1130
+ turns.set(
1131
+ turnId,
1132
+ createProcessTurnBinding(
1133
+ turnSpec,
1134
+ compileMappedTurnTransitions({ turnId, spec: turnSpec, knownTurnIds })
1135
+ )
1136
+ );
1137
+ executableTurns.set(turnId, {
1138
+ spec: turnSpec,
1139
+ effects: /* @__PURE__ */ new Map(),
1140
+ routings: /* @__PURE__ */ new Map()
1141
+ });
1142
+ continue;
1143
+ }
894
1144
  if (turnSpec.kind === "llm" || turnSpec.kind === "automatic") {
895
1145
  const { transitions, effects, routings } = compileTurnOutcomeDefinitions({
896
1146
  turnId,
@@ -1151,20 +1401,6 @@ function createEventBus() {
1151
1401
  };
1152
1402
  }
1153
1403
 
1154
- // src/extension-api.ts
1155
- var SafeLaunchPreparationError = class extends Error {
1156
- /** @public */
1157
- constructor(message, safeSummary) {
1158
- super(message);
1159
- this.safeSummary = safeSummary;
1160
- this.name = "SafeLaunchPreparationError";
1161
- }
1162
- safeSummary;
1163
- };
1164
- function findUiLauncherById(launcherService, launcherId) {
1165
- return launcherService.listUiLaunchers().find((launcher) => launcher.id === launcherId) ?? null;
1166
- }
1167
-
1168
1404
  // src/external-action-source.ts
1169
1405
  function defineExternalActionSource(metadata) {
1170
1406
  return function source(resolve) {
@@ -1701,13 +1937,17 @@ var ParameterizedOutcomeBuilder = class extends RouteAndEffectBuilder {
1701
1937
  });
1702
1938
  }
1703
1939
  /** @internal */
1704
- publishedMarkdownFields() {
1705
- return this.publishedMarkdownParameter ? {
1706
- /** @internal */
1707
- publishedProduct: this.publishedMarkdownParameter,
1708
- /** @internal */
1709
- turnResultMarkdownParameter: this.publishedMarkdownParameter
1710
- } : {};
1940
+ buildParameterSpec(kind) {
1941
+ if (!this.outcomeDescription) throw new Error(`${kind} must declare .description(...)`);
1942
+ return {
1943
+ description: this.outcomeDescription,
1944
+ parameters: this.parameters,
1945
+ ...this.summaryParameter ? { resultSummaryParameter: this.summaryParameter } : {},
1946
+ ...this.publishedMarkdownParameter ? {
1947
+ publishedProduct: this.publishedMarkdownParameter,
1948
+ turnResultMarkdownParameter: this.publishedMarkdownParameter
1949
+ } : {}
1950
+ };
1711
1951
  }
1712
1952
  /** @public */
1713
1953
  description(text) {
@@ -1810,6 +2050,10 @@ var ParameterizedOutcomeBuilder = class extends RouteAndEffectBuilder {
1810
2050
  array(name, options = {}) {
1811
2051
  return this.typedParameter(name, "array", options);
1812
2052
  }
2053
+ /** @public */
2054
+ requiredArray(name, options = {}) {
2055
+ return this.typedParameter(name, "array", this.withRequired(name, options));
2056
+ }
1813
2057
  };
1814
2058
  var OutcomeToolBuilder = class extends ParameterizedOutcomeBuilder {
1815
2059
  stateRouting;
@@ -1826,18 +2070,13 @@ var OutcomeToolBuilder = class extends ParameterizedOutcomeBuilder {
1826
2070
  }
1827
2071
  /** @internal */
1828
2072
  build() {
1829
- if (!this.outcomeDescription) {
1830
- throw new Error("LLM outcome tool must declare .description(...)");
1831
- }
2073
+ const parameters = this.buildParameterSpec("LLM outcome tool");
1832
2074
  if (this.stateRouting && this.hasRoute()) {
1833
2075
  throw new Error("State-routed outcome cannot declare another route");
1834
2076
  }
1835
2077
  const stateRouting = this.stateRouting;
1836
2078
  return {
1837
- description: this.outcomeDescription,
1838
- parameters: this.parameters,
1839
- ...this.summaryParameter ? { resultSummaryParameter: this.summaryParameter } : {},
1840
- ...this.publishedMarkdownFields(),
2079
+ ...parameters,
1841
2080
  ...stateRouting ? {
1842
2081
  branches: Object.fromEntries(
1843
2082
  Object.entries(stateRouting.branches).map(([branchId, turnId]) => [
@@ -1861,9 +2100,7 @@ var AutomaticOutcomeBuilder = class extends ParameterizedOutcomeBuilder {
1861
2100
  }
1862
2101
  /** @internal */
1863
2102
  build() {
1864
- if (!this.outcomeDescription) {
1865
- throw new Error("Automatic outcome must declare .description(...)");
1866
- }
2103
+ const parameters = this.buildParameterSpec("Automatic outcome");
1867
2104
  const configuredEffect = this.flowEffect ? wrapOutcomeCallback(this.flowEffect) : void 0;
1868
2105
  const effect = this.waits ? async (execution) => {
1869
2106
  const result = configuredEffect ? await configuredEffect(execution) : void 0;
@@ -1873,10 +2110,7 @@ var AutomaticOutcomeBuilder = class extends ParameterizedOutcomeBuilder {
1873
2110
  };
1874
2111
  } : configuredEffect;
1875
2112
  return {
1876
- description: this.outcomeDescription,
1877
- parameters: this.parameters,
1878
- ...this.summaryParameter ? { resultSummaryParameter: this.summaryParameter } : {},
1879
- ...this.publishedMarkdownFields(),
2113
+ ...parameters,
1880
2114
  ...this.buildRouteTarget(),
1881
2115
  ...effect ? { effect } : {}
1882
2116
  };
@@ -2035,10 +2269,90 @@ var LlmFlowBuilder = class extends DescribedTurnBuilder {
2035
2269
  publishedResult = null;
2036
2270
  endResult = null;
2037
2271
  outcomeToolBuilders = /* @__PURE__ */ new Map();
2272
+ mapped = null;
2038
2273
  /** @internal */
2039
2274
  get definition() {
2040
2275
  return this.buildDefinition();
2041
2276
  }
2277
+ /**
2278
+ * Run this turn once per frozen item. Items run sequentially; each item's
2279
+ * outcome yields a typed result, and `collect` updates state and routes once.
2280
+ * @public
2281
+ */
2282
+ forEach(options) {
2283
+ if (this.mapped) {
2284
+ throw new Error(`LLM turn '${this.turnId}' declares .forEach(...) more than once`);
2285
+ }
2286
+ if (this.outcomeToolBuilders.size > 0 || this.publishedResult || this.endResult) {
2287
+ throw new Error(
2288
+ `LLM turn '${this.turnId}' must declare .forEach(...) before its completion path`
2289
+ );
2290
+ }
2291
+ this.mapped = {
2292
+ options,
2293
+ yields: /* @__PURE__ */ new Map()
2294
+ };
2295
+ return new MappedLlmFlowBuilder(
2296
+ this
2297
+ );
2298
+ }
2299
+ /** @internal */
2300
+ addMappedOutcome(id, builder, yieldResult) {
2301
+ if (!this.mapped) throw new Error(`LLM turn '${this.turnId}' is not mapped`);
2302
+ if (id.trim() === "") {
2303
+ throw new Error(`LLM turn '${this.turnId}' declares an empty outcome tool id`);
2304
+ }
2305
+ if (this.outcomeToolBuilders.has(id)) {
2306
+ throw new Error(`LLM turn '${this.turnId}' declares duplicate outcome tool '${id}'`);
2307
+ }
2308
+ this.outcomeToolBuilders.set(id, builder);
2309
+ this.mapped.yields.set(id, yieldResult);
2310
+ }
2311
+ /** @internal */
2312
+ setMappedCollect(collect) {
2313
+ if (!this.mapped) throw new Error(`LLM turn '${this.turnId}' is not mapped`);
2314
+ if (this.mapped.collect) {
2315
+ throw new Error(`Mapped turn '${this.turnId}' declares .collect(...) more than once`);
2316
+ }
2317
+ this.mapped.collect = collect;
2318
+ }
2319
+ /** @internal */
2320
+ setMappedRouting(routing) {
2321
+ if (!this.mapped) throw new Error(`LLM turn '${this.turnId}' is not mapped`);
2322
+ if (this.mapped.routing) {
2323
+ throw new Error(`Mapped turn '${this.turnId}' collection already declares a route`);
2324
+ }
2325
+ this.mapped.routing = routing;
2326
+ }
2327
+ mappedItemContext(ctx) {
2328
+ if (!this.mapped) return {};
2329
+ const iteration = ctx.iteration;
2330
+ if (!iteration) {
2331
+ throw new Error(`Mapped turn '${this.turnId}' requires an active item`);
2332
+ }
2333
+ return {
2334
+ item: this.mapped.options.itemCodec.parse(iteration.item),
2335
+ itemKey: iteration.itemKey,
2336
+ itemLabel: iteration.itemLabel,
2337
+ itemIndex: iteration.itemIndex,
2338
+ itemCount: iteration.itemCount
2339
+ };
2340
+ }
2341
+ buildMappedSpec() {
2342
+ if (!this.mapped) return void 0;
2343
+ if (!this.mapped.collect) {
2344
+ throw new Error(`Mapped turn '${this.turnId}' must declare .collect(...)`);
2345
+ }
2346
+ if (!this.mapped.routing) {
2347
+ throw new Error(`Mapped turn '${this.turnId}' must declare a collection route`);
2348
+ }
2349
+ return {
2350
+ ...this.mapped.options,
2351
+ yields: Object.fromEntries(this.mapped.yields),
2352
+ collect: this.mapped.collect,
2353
+ routing: this.mapped.routing
2354
+ };
2355
+ }
2042
2356
  /** @internal */
2043
2357
  modelPurpose(purpose) {
2044
2358
  this.modelPurposeValue = purpose;
@@ -2155,6 +2469,7 @@ var LlmFlowBuilder = class extends DescribedTurnBuilder {
2155
2469
  }
2156
2470
  /** @public */
2157
2471
  publish(productName) {
2472
+ this.assertNotMapped(".publish(...)");
2158
2473
  const normalized = normalizeProductName(productName);
2159
2474
  if (this.publishedResult) {
2160
2475
  throw new Error(`LLM turn '${this.turnId}' can publish only one product in flow v1`);
@@ -2168,6 +2483,7 @@ var LlmFlowBuilder = class extends DescribedTurnBuilder {
2168
2483
  }
2169
2484
  /** @public */
2170
2485
  end(outcomeId) {
2486
+ this.assertNotMapped(".end(...)");
2171
2487
  if (this.endResult) {
2172
2488
  throw new Error(`LLM turn '${this.turnId}' declares duplicate .end(...) completion`);
2173
2489
  }
@@ -2182,13 +2498,23 @@ var LlmFlowBuilder = class extends DescribedTurnBuilder {
2182
2498
  }
2183
2499
  /** @public */
2184
2500
  buildPrompt(fn) {
2185
- this.promptBuilder = (ctx) => fn(
2186
- createFlowPromptContext(ctx, [...this.consumedProductNames], [
2187
- ...this.optionalConsumedProductNames
2188
- ])
2189
- );
2501
+ this.promptBuilder = (ctx) => fn({
2502
+ ...createFlowPromptContext(
2503
+ ctx,
2504
+ [...this.consumedProductNames],
2505
+ [...this.optionalConsumedProductNames]
2506
+ ),
2507
+ ...this.mappedItemContext(ctx)
2508
+ });
2190
2509
  return this;
2191
2510
  }
2511
+ assertNotMapped(feature) {
2512
+ if (this.mapped) {
2513
+ throw new Error(
2514
+ `Mapped turn '${this.turnId}' cannot declare ${feature}; items yield results and .collect(...) routes`
2515
+ );
2516
+ }
2517
+ }
2192
2518
  /** @public */
2193
2519
  prompt(prompt) {
2194
2520
  this.promptBuilder = prompt;
@@ -2196,6 +2522,7 @@ var LlmFlowBuilder = class extends DescribedTurnBuilder {
2196
2522
  }
2197
2523
  /** @public */
2198
2524
  outcomeTool(id, configure) {
2525
+ this.assertNotMapped("routed outcome tools");
2199
2526
  if (id.trim() === "") {
2200
2527
  throw new Error(`LLM turn '${this.turnId}' declares an empty outcome tool id`);
2201
2528
  }
@@ -2231,7 +2558,10 @@ var LlmFlowBuilder = class extends DescribedTurnBuilder {
2231
2558
  ...this.integrationToolResolver ? { resolveIntegrationTools: this.integrationToolResolver } : {},
2232
2559
  ...this.questionsEnabled ? { askQuestions: true } : {},
2233
2560
  ...preparation ? {
2234
- prepare: (ctx) => preparation(createFlowAutomaticRunContext(ctx))
2561
+ prepare: (ctx) => preparation({
2562
+ ...createFlowAutomaticRunContext(ctx),
2563
+ ...this.mappedItemContext(ctx)
2564
+ })
2235
2565
  } : {},
2236
2566
  completionMode: "turn_end",
2237
2567
  branchType: this.branchType,
@@ -2325,8 +2655,10 @@ var LlmFlowBuilder = class extends DescribedTurnBuilder {
2325
2655
  if (Object.keys(outcomes).length === 0 && !turnEnd) {
2326
2656
  throw new Error(`LLM turn '${this.turnId}' must declare a completion path`);
2327
2657
  }
2658
+ const forEach = this.buildMappedSpec();
2328
2659
  return {
2329
2660
  ...definition,
2661
+ ...forEach ? { forEach } : {},
2330
2662
  ...Object.keys(outcomes).length > 0 ? { outcomes } : {},
2331
2663
  ...turnEnd ? { turnEnd } : {},
2332
2664
  ...turnResultMarkdown ? { turnResultMarkdown } : {},
@@ -2337,6 +2669,169 @@ var LlmFlowBuilder = class extends DescribedTurnBuilder {
2337
2669
  };
2338
2670
  }
2339
2671
  };
2672
+ var MappedOutcomeBuilder = class {
2673
+ tool = new OutcomeToolBuilder();
2674
+ yieldResult = null;
2675
+ /** @public */
2676
+ description(text) {
2677
+ this.tool.description(text);
2678
+ return this;
2679
+ }
2680
+ /** @public */
2681
+ resultSummary(name) {
2682
+ this.tool.resultSummary(name);
2683
+ return this;
2684
+ }
2685
+ /** @public */
2686
+ requiredString(name, options = {}) {
2687
+ this.tool.requiredString(name, options);
2688
+ return this;
2689
+ }
2690
+ /** @public */
2691
+ string(name, options = {}) {
2692
+ this.tool.string(name, options);
2693
+ return this;
2694
+ }
2695
+ /** @public */
2696
+ requiredNumber(name, options = {}) {
2697
+ this.tool.requiredNumber(name, options);
2698
+ return this;
2699
+ }
2700
+ /** @public */
2701
+ requiredBoolean(name, options = {}) {
2702
+ this.tool.requiredBoolean(name, options);
2703
+ return this;
2704
+ }
2705
+ /** @public */
2706
+ requiredStringArray(name, options = {}) {
2707
+ this.tool.requiredStringArray(name, options);
2708
+ return this;
2709
+ }
2710
+ /** @public */
2711
+ object(name, options = {}) {
2712
+ this.tool.object(name, options);
2713
+ return this;
2714
+ }
2715
+ /** @public */
2716
+ requiredArray(name, options = {}) {
2717
+ this.tool.requiredArray(name, options);
2718
+ return this;
2719
+ }
2720
+ /** Map this outcome to the item's typed result. @public */
2721
+ yield(fn) {
2722
+ this.yieldResult = fn;
2723
+ return this;
2724
+ }
2725
+ /** @internal */
2726
+ build() {
2727
+ if (!this.yieldResult) {
2728
+ throw new Error("Mapped outcome must declare .yield(...)");
2729
+ }
2730
+ return { tool: this.tool, yieldResult: this.yieldResult };
2731
+ }
2732
+ };
2733
+ var MappedTurnFacade = class {
2734
+ /** @internal */
2735
+ constructor(base) {
2736
+ this.base = base;
2737
+ }
2738
+ base;
2739
+ /** @internal */
2740
+ get id() {
2741
+ return this.base.id;
2742
+ }
2743
+ /** @internal */
2744
+ get definition() {
2745
+ return this.base.definition;
2746
+ }
2747
+ };
2748
+ var MappedCollectBuilder = class extends MappedTurnFacade {
2749
+ /** @public */
2750
+ to(turnId) {
2751
+ this.base.setMappedRouting({ kind: "static", to: turnId });
2752
+ return this;
2753
+ }
2754
+ /** @public */
2755
+ complete() {
2756
+ this.base.setMappedRouting({ kind: "static", lifecycleStatus: "completed" });
2757
+ return this;
2758
+ }
2759
+ /** @public */
2760
+ lifecycleStatus(status) {
2761
+ this.base.setMappedRouting({ kind: "static", lifecycleStatus: status });
2762
+ return this;
2763
+ }
2764
+ /** Choose the next turn from the collected state. @public */
2765
+ routeByState(branches, choose) {
2766
+ if (Object.keys(branches).length === 0) {
2767
+ throw new Error("Mapped collection routing must declare at least one branch");
2768
+ }
2769
+ this.base.setMappedRouting({ kind: "branches", branches: { ...branches }, choose });
2770
+ return this;
2771
+ }
2772
+ };
2773
+ var MappedLlmFlowBuilder = class extends MappedTurnFacade {
2774
+ /** @internal */
2775
+ constructor(base) {
2776
+ super(base);
2777
+ }
2778
+ /** @public */
2779
+ description(description) {
2780
+ this.base.description(description);
2781
+ return this;
2782
+ }
2783
+ /** @public */
2784
+ tools(...tools) {
2785
+ this.base.tools(...tools);
2786
+ return this;
2787
+ }
2788
+ /** @public */
2789
+ integrationTools(...tools) {
2790
+ this.base.integrationTools(...tools);
2791
+ return this;
2792
+ }
2793
+ /** @public */
2794
+ freshPrimary() {
2795
+ this.base.freshPrimary();
2796
+ return this;
2797
+ }
2798
+ /** @public */
2799
+ consume(productName) {
2800
+ this.base.consume(productName);
2801
+ return this;
2802
+ }
2803
+ /** Deterministic worker preparation for the active item. @public */
2804
+ prepare(fn) {
2805
+ this.base.prepare((ctx) => fn(ctx));
2806
+ return this;
2807
+ }
2808
+ /** Build the prompt for the active item. @public */
2809
+ buildPrompt(fn) {
2810
+ this.base.buildPrompt(
2811
+ (ctx) => fn(
2812
+ ctx
2813
+ )
2814
+ );
2815
+ return this;
2816
+ }
2817
+ /** @public */
2818
+ outcomeTool(id, configure) {
2819
+ const outcome = new MappedOutcomeBuilder();
2820
+ configure(outcome);
2821
+ const built = outcome.build();
2822
+ this.base.addMappedOutcome(
2823
+ id,
2824
+ built.tool,
2825
+ built.yieldResult
2826
+ );
2827
+ return this;
2828
+ }
2829
+ /** Combine ordered item results into process state, once. @public */
2830
+ collect(fn) {
2831
+ this.base.setMappedCollect(fn);
2832
+ return new MappedCollectBuilder(this.base);
2833
+ }
2834
+ };
2340
2835
  var ExternalActionTurnBuilder = class extends DescribedTurnBuilder {
2341
2836
  externalActionBuilders = /* @__PURE__ */ new Map();
2342
2837
  /** @public */
@@ -4318,7 +4813,7 @@ function validateOutcomeTurnResultContract(turnKindLabel, turnId, outcomes, turn
4318
4813
  return errors;
4319
4814
  }
4320
4815
  function isValidOutcomeToolArrayItemType(type) {
4321
- return type === "string" || type === "number" || type === "boolean" || type === "object";
4816
+ return type === "string" || type === "number" || type === "boolean" || type === "object" || type === "array";
4322
4817
  }
4323
4818
  function validateOutcomeToolParameters(turnKindLabel, turnId, outcomes) {
4324
4819
  const errors = [];
@@ -4475,6 +4970,61 @@ function validateLlmTurnDefinition(turnId, turnDef) {
4475
4970
  }
4476
4971
  }
4477
4972
  errors.push(...validateOutcomeToolParameters("LLM", turnId, declaredOutcomes));
4973
+ errors.push(...validateMappedTurn(turnId, turnDef));
4974
+ return errors;
4975
+ }
4976
+ function validateMappedTurn(turnId, turnDef) {
4977
+ const mapped = turnDef.forEach;
4978
+ if (mapped === void 0) return [];
4979
+ const errors = [];
4980
+ for (const name of ["items", "key", "collect"]) {
4981
+ if (typeof mapped[name] !== "function") {
4982
+ errors.push(`Mapped turn '${turnId}' must declare ${name}`);
4983
+ }
4984
+ }
4985
+ for (const name of ["itemCodec", "resultCodec"]) {
4986
+ const codec = mapped[name];
4987
+ if (typeof codec?.parse !== "function" || typeof codec?.serialize !== "function") {
4988
+ errors.push(`Mapped turn '${turnId}' must declare ${name}`);
4989
+ }
4990
+ }
4991
+ if (turnDef.turnEnd) {
4992
+ errors.push(`Mapped turn '${turnId}' must finish items through outcome tools`);
4993
+ }
4994
+ if (turnDef.publishedProduct) {
4995
+ errors.push(`Mapped turn '${turnId}' cannot publish a product from item turns`);
4996
+ }
4997
+ const outcomes = Object.entries(turnDef.outcomes ?? {});
4998
+ if (outcomes.length === 0) {
4999
+ errors.push(`Mapped turn '${turnId}' must declare at least one outcome tool`);
5000
+ }
5001
+ for (const [outcomeId, spec] of outcomes) {
5002
+ if ("branches" in spec || spec.to !== void 0 || spec.complete !== void 0 || spec.lifecycleStatus !== void 0 || spec.effect !== void 0 || spec.lifecycleIntent !== void 0 || spec.publishedProduct !== void 0) {
5003
+ errors.push(
5004
+ `Mapped turn '${turnId}' outcome '${outcomeId}' cannot route, change state, or publish`
5005
+ );
5006
+ }
5007
+ if (typeof mapped.yields?.[outcomeId] !== "function") {
5008
+ errors.push(`Mapped turn '${turnId}' outcome '${outcomeId}' must declare a yield`);
5009
+ }
5010
+ }
5011
+ for (const outcomeId of Object.keys(mapped.yields ?? {})) {
5012
+ if (!Object.hasOwn(turnDef.outcomes ?? {}, outcomeId)) {
5013
+ errors.push(`Mapped turn '${turnId}' yields undeclared outcome '${outcomeId}'`);
5014
+ }
5015
+ }
5016
+ const routing = mapped.routing;
5017
+ if (routing?.kind === "static") {
5018
+ if (routing.to === void 0 === (routing.lifecycleStatus === void 0)) {
5019
+ errors.push(`Mapped turn '${turnId}' collection must declare exactly one target`);
5020
+ }
5021
+ } else if (routing?.kind === "branches") {
5022
+ if (Object.keys(routing.branches).length === 0 || typeof routing.choose !== "function") {
5023
+ errors.push(`Mapped turn '${turnId}' collection routing needs branches and a chooser`);
5024
+ }
5025
+ } else {
5026
+ errors.push(`Mapped turn '${turnId}' must declare a collection route`);
5027
+ }
4478
5028
  return errors;
4479
5029
  }
4480
5030
  function validateAutomaticTurnDefinition(turnId, turnDef) {
@@ -4777,11 +5327,16 @@ export {
4777
5327
  HumanFlowBuilder,
4778
5328
  IntegrationHttpClient,
4779
5329
  IntegrationHttpError,
5330
+ MAPPED_COLLECT_TRIGGER,
4780
5331
  MARKDOWN_RESULT_TOOL_NAME,
5332
+ MappedCollectBuilder,
5333
+ MappedLlmFlowBuilder,
5334
+ MappedOutcomeBuilder,
4781
5335
  REQUIRED_MARKDOWN_RESULT_TURN_RESULT,
4782
5336
  RESERVED_INTEGRATION_TOOL_NAMES,
4783
5337
  RepositoryHttpClient,
4784
5338
  SafeLaunchPreparationError,
5339
+ SafeOutcomePlanningError,
4785
5340
  acceptedReviewHandoffAction,
4786
5341
  assertValidLlmTurnDefinition,
4787
5342
  atomicWriteUtf8,
@@ -4793,6 +5348,7 @@ export {
4793
5348
  builtinPiProvider,
4794
5349
  clearRepositoryGitHttpsHelpers,
4795
5350
  clearRepositoryGitSshWrappers,
5351
+ collectMappedResults,
4796
5352
  configuredPiProvider,
4797
5353
  coreHostCapabilities,
4798
5354
  createCapabilityAccessor,
@@ -4822,6 +5378,7 @@ export {
4822
5378
  filterProviderOptionsForDefinition,
4823
5379
  findUiLauncherById,
4824
5380
  flow,
5381
+ freezeMappedItems,
4825
5382
  getExternalActionArmingId,
4826
5383
  getExternalActionTransitionTrigger,
4827
5384
  getExternalSourceTransitionId,
@@ -4879,6 +5436,7 @@ export {
4879
5436
  validateProcessGraphProducts,
4880
5437
  validateProcessGraphTurnTransitions,
4881
5438
  validateToolCallRendererDefinition,
4882
- validateTurnDefinition
5439
+ validateTurnDefinition,
5440
+ yieldMappedItemResult
4883
5441
  };
4884
5442
  //# sourceMappingURL=index.js.map