@leitwerk-dev/process-sdk 0.2.1 → 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.
Files changed (60) hide show
  1. package/README.md +12 -0
  2. package/dist/{chunk-I7U6HCLN.js → chunk-GVBLXKSR.js} +1 -1
  3. package/dist/chunk-GVBLXKSR.js.map +1 -0
  4. package/dist/core-capabilities.d.ts +2 -0
  5. package/dist/core-capabilities.d.ts.map +1 -1
  6. package/dist/define-process.d.ts +3 -0
  7. package/dist/define-process.d.ts.map +1 -1
  8. package/dist/{extension-api-B4gG5w1K.d.ts → extension-api-DM-AvWOW.d.ts} +211 -14
  9. package/dist/extension-api.d.ts +19 -5
  10. package/dist/extension-api.d.ts.map +1 -1
  11. package/dist/external-source-poll.d.ts +18 -12
  12. package/dist/external-source-poll.d.ts.map +1 -1
  13. package/dist/flow.d.ts +118 -13
  14. package/dist/flow.d.ts.map +1 -1
  15. package/dist/index.d.ts +6 -4
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +647 -82
  18. package/dist/index.js.map +1 -1
  19. package/dist/integration-http.d.ts +4 -4
  20. package/dist/integration-http.d.ts.map +1 -1
  21. package/dist/json-data.d.ts +1 -1
  22. package/dist/json-data.d.ts.map +1 -1
  23. package/dist/mapped-turn.d.ts +185 -0
  24. package/dist/mapped-turn.d.ts.map +1 -0
  25. package/dist/pi-config-public.js +1 -1
  26. package/dist/pi-config.js +1 -1
  27. package/dist/repository-feedback.d.ts +32 -26
  28. package/dist/repository-feedback.d.ts.map +1 -1
  29. package/dist/repository-https.d.ts +1 -1
  30. package/dist/repository-https.d.ts.map +1 -1
  31. package/dist/repository-issue-watcher.d.ts +30 -25
  32. package/dist/repository-issue-watcher.d.ts.map +1 -1
  33. package/dist/repository-source-config.d.ts +29 -44
  34. package/dist/repository-source-config.d.ts.map +1 -1
  35. package/dist/subprocess-env.d.ts +1 -1
  36. package/dist/subprocess-env.d.ts.map +1 -1
  37. package/dist/tool-arguments.d.ts +3 -3
  38. package/dist/tool-arguments.d.ts.map +1 -1
  39. package/dist/turn-semantics.d.ts.map +1 -1
  40. package/dist/types.d.ts +15 -7
  41. package/dist/types.d.ts.map +1 -1
  42. package/package.json +6 -6
  43. package/src/core-capabilities.ts +2 -0
  44. package/src/define-process.ts +83 -0
  45. package/src/extension-api.ts +23 -5
  46. package/src/external-source-poll.ts +65 -11
  47. package/src/flow.ts +448 -31
  48. package/src/index.ts +38 -2
  49. package/src/integration-http.ts +3 -3
  50. package/src/json-data.ts +1 -1
  51. package/src/mapped-turn.ts +386 -0
  52. package/src/repository-feedback.ts +48 -20
  53. package/src/repository-https.ts +1 -1
  54. package/src/repository-issue-watcher.ts +48 -21
  55. package/src/repository-source-config.ts +66 -23
  56. package/src/subprocess-env.ts +1 -1
  57. package/src/tool-arguments.ts +3 -3
  58. package/src/turn-semantics.ts +76 -1
  59. package/src/types.ts +15 -7
  60. package/dist/chunk-I7U6HCLN.js.map +0 -1
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) {
@@ -1174,8 +1410,11 @@ function defineExternalActionSource(metadata) {
1174
1410
 
1175
1411
  // src/external-source-poll.ts
1176
1412
  function createExternalSourcePollReporter(sources, result, options = {}) {
1413
+ const isCurrent = (kind, armed) => sources.listArmed(kind).some((current2) => sameSubscription(armed, current2));
1414
+ const current = (armed) => options.currentKinds === void 0 || options.currentKinds.some((kind) => isCurrent(kind, armed));
1177
1415
  return {
1178
- /** @internal */
1416
+ isCurrent,
1417
+ /** @public */
1179
1418
  async poll(kind, read) {
1180
1419
  for (const armed of sources.listArmed(kind)) {
1181
1420
  try {
@@ -1187,8 +1426,9 @@ function createExternalSourcePollReporter(sources, result, options = {}) {
1187
1426
  }
1188
1427
  }
1189
1428
  },
1190
- /** @internal */
1429
+ /** @public */
1191
1430
  async fire(armed, event, mergeKey) {
1431
+ if (!current(armed)) return false;
1192
1432
  const fired = await sources.fire({
1193
1433
  instanceId: armed.instanceId,
1194
1434
  armingId: armed.id,
@@ -1200,9 +1440,9 @@ function createExternalSourcePollReporter(sources, result, options = {}) {
1200
1440
  else result.errors.push(`${armed.id}:fire_failed`);
1201
1441
  return fired.ok;
1202
1442
  },
1203
- /** @internal */
1443
+ /** @public */
1204
1444
  observe(armed, input) {
1205
- if (sources.observe && armed.generation)
1445
+ if (current(armed) && sources.observe && armed.generation)
1206
1446
  return sources.observe({
1207
1447
  instanceId: armed.instanceId,
1208
1448
  armingId: armed.id,
@@ -1212,6 +1452,9 @@ function createExternalSourcePollReporter(sources, result, options = {}) {
1212
1452
  }
1213
1453
  };
1214
1454
  }
1455
+ function sameSubscription(captured, current) {
1456
+ return current.id === captured.id && current.instanceId === captured.instanceId && current.generation === captured.generation && JSON.stringify(current.resolved) === JSON.stringify(captured.resolved);
1457
+ }
1215
1458
 
1216
1459
  // src/flow.ts
1217
1460
  import path2 from "path";
@@ -1694,13 +1937,17 @@ var ParameterizedOutcomeBuilder = class extends RouteAndEffectBuilder {
1694
1937
  });
1695
1938
  }
1696
1939
  /** @internal */
1697
- publishedMarkdownFields() {
1698
- return this.publishedMarkdownParameter ? {
1699
- /** @internal */
1700
- publishedProduct: this.publishedMarkdownParameter,
1701
- /** @internal */
1702
- turnResultMarkdownParameter: this.publishedMarkdownParameter
1703
- } : {};
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
+ };
1704
1951
  }
1705
1952
  /** @public */
1706
1953
  description(text) {
@@ -1803,6 +2050,10 @@ var ParameterizedOutcomeBuilder = class extends RouteAndEffectBuilder {
1803
2050
  array(name, options = {}) {
1804
2051
  return this.typedParameter(name, "array", options);
1805
2052
  }
2053
+ /** @public */
2054
+ requiredArray(name, options = {}) {
2055
+ return this.typedParameter(name, "array", this.withRequired(name, options));
2056
+ }
1806
2057
  };
1807
2058
  var OutcomeToolBuilder = class extends ParameterizedOutcomeBuilder {
1808
2059
  stateRouting;
@@ -1819,18 +2070,13 @@ var OutcomeToolBuilder = class extends ParameterizedOutcomeBuilder {
1819
2070
  }
1820
2071
  /** @internal */
1821
2072
  build() {
1822
- if (!this.outcomeDescription) {
1823
- throw new Error("LLM outcome tool must declare .description(...)");
1824
- }
2073
+ const parameters = this.buildParameterSpec("LLM outcome tool");
1825
2074
  if (this.stateRouting && this.hasRoute()) {
1826
2075
  throw new Error("State-routed outcome cannot declare another route");
1827
2076
  }
1828
2077
  const stateRouting = this.stateRouting;
1829
2078
  return {
1830
- description: this.outcomeDescription,
1831
- parameters: this.parameters,
1832
- ...this.summaryParameter ? { resultSummaryParameter: this.summaryParameter } : {},
1833
- ...this.publishedMarkdownFields(),
2079
+ ...parameters,
1834
2080
  ...stateRouting ? {
1835
2081
  branches: Object.fromEntries(
1836
2082
  Object.entries(stateRouting.branches).map(([branchId, turnId]) => [
@@ -1854,9 +2100,7 @@ var AutomaticOutcomeBuilder = class extends ParameterizedOutcomeBuilder {
1854
2100
  }
1855
2101
  /** @internal */
1856
2102
  build() {
1857
- if (!this.outcomeDescription) {
1858
- throw new Error("Automatic outcome must declare .description(...)");
1859
- }
2103
+ const parameters = this.buildParameterSpec("Automatic outcome");
1860
2104
  const configuredEffect = this.flowEffect ? wrapOutcomeCallback(this.flowEffect) : void 0;
1861
2105
  const effect = this.waits ? async (execution) => {
1862
2106
  const result = configuredEffect ? await configuredEffect(execution) : void 0;
@@ -1866,10 +2110,7 @@ var AutomaticOutcomeBuilder = class extends ParameterizedOutcomeBuilder {
1866
2110
  };
1867
2111
  } : configuredEffect;
1868
2112
  return {
1869
- description: this.outcomeDescription,
1870
- parameters: this.parameters,
1871
- ...this.summaryParameter ? { resultSummaryParameter: this.summaryParameter } : {},
1872
- ...this.publishedMarkdownFields(),
2113
+ ...parameters,
1873
2114
  ...this.buildRouteTarget(),
1874
2115
  ...effect ? { effect } : {}
1875
2116
  };
@@ -2028,10 +2269,90 @@ var LlmFlowBuilder = class extends DescribedTurnBuilder {
2028
2269
  publishedResult = null;
2029
2270
  endResult = null;
2030
2271
  outcomeToolBuilders = /* @__PURE__ */ new Map();
2272
+ mapped = null;
2031
2273
  /** @internal */
2032
2274
  get definition() {
2033
2275
  return this.buildDefinition();
2034
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
+ }
2035
2356
  /** @internal */
2036
2357
  modelPurpose(purpose) {
2037
2358
  this.modelPurposeValue = purpose;
@@ -2148,6 +2469,7 @@ var LlmFlowBuilder = class extends DescribedTurnBuilder {
2148
2469
  }
2149
2470
  /** @public */
2150
2471
  publish(productName) {
2472
+ this.assertNotMapped(".publish(...)");
2151
2473
  const normalized = normalizeProductName(productName);
2152
2474
  if (this.publishedResult) {
2153
2475
  throw new Error(`LLM turn '${this.turnId}' can publish only one product in flow v1`);
@@ -2161,6 +2483,7 @@ var LlmFlowBuilder = class extends DescribedTurnBuilder {
2161
2483
  }
2162
2484
  /** @public */
2163
2485
  end(outcomeId) {
2486
+ this.assertNotMapped(".end(...)");
2164
2487
  if (this.endResult) {
2165
2488
  throw new Error(`LLM turn '${this.turnId}' declares duplicate .end(...) completion`);
2166
2489
  }
@@ -2175,13 +2498,23 @@ var LlmFlowBuilder = class extends DescribedTurnBuilder {
2175
2498
  }
2176
2499
  /** @public */
2177
2500
  buildPrompt(fn) {
2178
- this.promptBuilder = (ctx) => fn(
2179
- createFlowPromptContext(ctx, [...this.consumedProductNames], [
2180
- ...this.optionalConsumedProductNames
2181
- ])
2182
- );
2501
+ this.promptBuilder = (ctx) => fn({
2502
+ ...createFlowPromptContext(
2503
+ ctx,
2504
+ [...this.consumedProductNames],
2505
+ [...this.optionalConsumedProductNames]
2506
+ ),
2507
+ ...this.mappedItemContext(ctx)
2508
+ });
2183
2509
  return this;
2184
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
+ }
2185
2518
  /** @public */
2186
2519
  prompt(prompt) {
2187
2520
  this.promptBuilder = prompt;
@@ -2189,6 +2522,7 @@ var LlmFlowBuilder = class extends DescribedTurnBuilder {
2189
2522
  }
2190
2523
  /** @public */
2191
2524
  outcomeTool(id, configure) {
2525
+ this.assertNotMapped("routed outcome tools");
2192
2526
  if (id.trim() === "") {
2193
2527
  throw new Error(`LLM turn '${this.turnId}' declares an empty outcome tool id`);
2194
2528
  }
@@ -2224,7 +2558,10 @@ var LlmFlowBuilder = class extends DescribedTurnBuilder {
2224
2558
  ...this.integrationToolResolver ? { resolveIntegrationTools: this.integrationToolResolver } : {},
2225
2559
  ...this.questionsEnabled ? { askQuestions: true } : {},
2226
2560
  ...preparation ? {
2227
- prepare: (ctx) => preparation(createFlowAutomaticRunContext(ctx))
2561
+ prepare: (ctx) => preparation({
2562
+ ...createFlowAutomaticRunContext(ctx),
2563
+ ...this.mappedItemContext(ctx)
2564
+ })
2228
2565
  } : {},
2229
2566
  completionMode: "turn_end",
2230
2567
  branchType: this.branchType,
@@ -2318,8 +2655,10 @@ var LlmFlowBuilder = class extends DescribedTurnBuilder {
2318
2655
  if (Object.keys(outcomes).length === 0 && !turnEnd) {
2319
2656
  throw new Error(`LLM turn '${this.turnId}' must declare a completion path`);
2320
2657
  }
2658
+ const forEach = this.buildMappedSpec();
2321
2659
  return {
2322
2660
  ...definition,
2661
+ ...forEach ? { forEach } : {},
2323
2662
  ...Object.keys(outcomes).length > 0 ? { outcomes } : {},
2324
2663
  ...turnEnd ? { turnEnd } : {},
2325
2664
  ...turnResultMarkdown ? { turnResultMarkdown } : {},
@@ -2330,6 +2669,169 @@ var LlmFlowBuilder = class extends DescribedTurnBuilder {
2330
2669
  };
2331
2670
  }
2332
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
+ };
2333
2835
  var ExternalActionTurnBuilder = class extends DescribedTurnBuilder {
2334
2836
  externalActionBuilders = /* @__PURE__ */ new Map();
2335
2837
  /** @public */
@@ -3030,7 +3532,7 @@ function createCapabilityAccessor(provided = []) {
3030
3532
 
3031
3533
  // src/integration-http.ts
3032
3534
  var IntegrationHttpError = class extends Error {
3033
- /** @internal */
3535
+ /** @public */
3034
3536
  constructor(status, message) {
3035
3537
  super(message);
3036
3538
  this.status = status;
@@ -3804,11 +4306,11 @@ function repositoryFeedbackBatch(unseen, config, now) {
3804
4306
  const latest = Math.max(...unseen.map((item) => Date.parse(item.createdAt) || 0));
3805
4307
  if (now - latest < config.quietPeriodMs) return null;
3806
4308
  const cursors = {
3807
- /** @internal */
4309
+ /** @public */
3808
4310
  conversationCursor: config.conversationCursor,
3809
- /** @internal */
4311
+ /** @public */
3810
4312
  reviewCursor: config.reviewCursor,
3811
- /** @internal */
4313
+ /** @public */
3812
4314
  inlineCursor: config.inlineCursor
3813
4315
  };
3814
4316
  for (const item of unseen) {
@@ -3816,19 +4318,19 @@ function repositoryFeedbackBatch(unseen, config, now) {
3816
4318
  cursors[key] = Math.max(cursors[key], item.id);
3817
4319
  }
3818
4320
  return {
3819
- /** @internal */
4321
+ /** @public */
3820
4322
  event: {
3821
- /** @internal */
4323
+ /** @public */
3822
4324
  feedbackIds: unseen.map(({ kind, id }) => ({
3823
- /** @internal */
4325
+ /** @public */
3824
4326
  kind,
3825
- /** @internal */
4327
+ /** @public */
3826
4328
  id
3827
4329
  })),
3828
- /** @internal */
4330
+ /** @public */
3829
4331
  cursors
3830
4332
  },
3831
- /** @internal */
4333
+ /** @public */
3832
4334
  mergeKey: `${cursors.conversationCursor}:${cursors.reviewCursor}:${cursors.inlineCursor}`
3833
4335
  };
3834
4336
  }
@@ -4050,24 +4552,24 @@ function parseRepositoryIssueWatcherConfig(raw, legacyType, distinctLabels = fal
4050
4552
  if (distinctLabels && parsed.labels.trigger === parsed.labels.done)
4051
4553
  throw new Error("Trigger and done labels must differ");
4052
4554
  return {
4053
- /** @internal */
4555
+ /** @public */
4054
4556
  config: parsed,
4055
- /** @internal */
4557
+ /** @public */
4056
4558
  enabled: config.enabled,
4057
- /** @internal */
4559
+ /** @public */
4058
4560
  launchModelConfig: parseProcessWatcherLaunchModelConfig(config.launch)
4059
4561
  };
4060
4562
  }
4061
4563
  function presentRepositoryIssueWatcherConfig(config) {
4062
4564
  return {
4063
- /** @internal */
4565
+ /** @public */
4064
4566
  targetSummary: `Profile ${config.profile} \xB7 trigger ${config.labels.trigger}`,
4065
- /** @internal */
4567
+ /** @public */
4066
4568
  details: [
4067
4569
  {
4068
- /** @internal */
4570
+ /** @public */
4069
4571
  label: "Profile",
4070
- /** @internal */
4572
+ /** @public */
4071
4573
  value: config.profile
4072
4574
  },
4073
4575
  { label: "Included repositories", value: config.repositories.include.join(", ") || "all" },
@@ -4111,19 +4613,19 @@ function parseRepositoryPullRequestConfig(value) {
4111
4613
  return null;
4112
4614
  const terminalOutcome = config.terminalOutcome === "merged" || config.terminalOutcome === "closed" ? config.terminalOutcome : void 0;
4113
4615
  return {
4114
- /** @internal */
4616
+ /** @public */
4115
4617
  profile: config.profile,
4116
- /** @internal */
4618
+ /** @public */
4117
4619
  owner: config.owner,
4118
- /** @internal */
4620
+ /** @public */
4119
4621
  repo: config.repo,
4120
- /** @internal */
4622
+ /** @public */
4121
4623
  prNumber: config.prNumber,
4122
- /** @internal */
4624
+ /** @public */
4123
4625
  pollInterval: typeof config.pollInterval === "string" ? config.pollInterval : "30s",
4124
- /** @internal */
4626
+ /** @public */
4125
4627
  terminalOutcome,
4126
- /** @internal */
4628
+ /** @public */
4127
4629
  disabled: config.disabled === true
4128
4630
  };
4129
4631
  }
@@ -4133,13 +4635,13 @@ function parseRepositoryFeedbackConfig(value) {
4133
4635
  if (!base) return null;
4134
4636
  return {
4135
4637
  ...base,
4136
- /** @internal */
4638
+ /** @public */
4137
4639
  conversationCursor: typeof config.conversationCursor === "number" ? config.conversationCursor : 0,
4138
- /** @internal */
4640
+ /** @public */
4139
4641
  reviewCursor: typeof config.reviewCursor === "number" ? config.reviewCursor : 0,
4140
- /** @internal */
4642
+ /** @public */
4141
4643
  inlineCursor: typeof config.inlineCursor === "number" ? config.inlineCursor : 0,
4142
- /** @internal */
4644
+ /** @public */
4143
4645
  quietPeriodMs: typeof config.quietPeriodMs === "number" ? config.quietPeriodMs : 12e4
4144
4646
  };
4145
4647
  }
@@ -4148,17 +4650,17 @@ function parseRepositoryIssueCancelledConfig(value) {
4148
4650
  if (typeof config.profile !== "string" || typeof config.owner !== "string" || typeof config.repo !== "string" || typeof config.issueNumber !== "number" || typeof config.triggerLabel !== "string")
4149
4651
  return null;
4150
4652
  return {
4151
- /** @internal */
4653
+ /** @public */
4152
4654
  profile: config.profile,
4153
- /** @internal */
4655
+ /** @public */
4154
4656
  owner: config.owner,
4155
- /** @internal */
4657
+ /** @public */
4156
4658
  repo: config.repo,
4157
- /** @internal */
4659
+ /** @public */
4158
4660
  issueNumber: config.issueNumber,
4159
- /** @internal */
4661
+ /** @public */
4160
4662
  triggerLabel: config.triggerLabel,
4161
- /** @internal */
4663
+ /** @public */
4162
4664
  pollInterval: typeof config.pollInterval === "string" ? config.pollInterval : "30s"
4163
4665
  };
4164
4666
  }
@@ -4311,7 +4813,7 @@ function validateOutcomeTurnResultContract(turnKindLabel, turnId, outcomes, turn
4311
4813
  return errors;
4312
4814
  }
4313
4815
  function isValidOutcomeToolArrayItemType(type) {
4314
- return type === "string" || type === "number" || type === "boolean" || type === "object";
4816
+ return type === "string" || type === "number" || type === "boolean" || type === "object" || type === "array";
4315
4817
  }
4316
4818
  function validateOutcomeToolParameters(turnKindLabel, turnId, outcomes) {
4317
4819
  const errors = [];
@@ -4468,6 +4970,61 @@ function validateLlmTurnDefinition(turnId, turnDef) {
4468
4970
  }
4469
4971
  }
4470
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
+ }
4471
5028
  return errors;
4472
5029
  }
4473
5030
  function validateAutomaticTurnDefinition(turnId, turnDef) {
@@ -4770,11 +5327,16 @@ export {
4770
5327
  HumanFlowBuilder,
4771
5328
  IntegrationHttpClient,
4772
5329
  IntegrationHttpError,
5330
+ MAPPED_COLLECT_TRIGGER,
4773
5331
  MARKDOWN_RESULT_TOOL_NAME,
5332
+ MappedCollectBuilder,
5333
+ MappedLlmFlowBuilder,
5334
+ MappedOutcomeBuilder,
4774
5335
  REQUIRED_MARKDOWN_RESULT_TURN_RESULT,
4775
5336
  RESERVED_INTEGRATION_TOOL_NAMES,
4776
5337
  RepositoryHttpClient,
4777
5338
  SafeLaunchPreparationError,
5339
+ SafeOutcomePlanningError,
4778
5340
  acceptedReviewHandoffAction,
4779
5341
  assertValidLlmTurnDefinition,
4780
5342
  atomicWriteUtf8,
@@ -4786,6 +5348,7 @@ export {
4786
5348
  builtinPiProvider,
4787
5349
  clearRepositoryGitHttpsHelpers,
4788
5350
  clearRepositoryGitSshWrappers,
5351
+ collectMappedResults,
4789
5352
  configuredPiProvider,
4790
5353
  coreHostCapabilities,
4791
5354
  createCapabilityAccessor,
@@ -4815,6 +5378,7 @@ export {
4815
5378
  filterProviderOptionsForDefinition,
4816
5379
  findUiLauncherById,
4817
5380
  flow,
5381
+ freezeMappedItems,
4818
5382
  getExternalActionArmingId,
4819
5383
  getExternalActionTransitionTrigger,
4820
5384
  getExternalSourceTransitionId,
@@ -4872,6 +5436,7 @@ export {
4872
5436
  validateProcessGraphProducts,
4873
5437
  validateProcessGraphTurnTransitions,
4874
5438
  validateToolCallRendererDefinition,
4875
- validateTurnDefinition
5439
+ validateTurnDefinition,
5440
+ yieldMappedItemResult
4876
5441
  };
4877
5442
  //# sourceMappingURL=index.js.map