@positronic/core 0.0.75 → 0.0.77

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 (53) hide show
  1. package/dist/src/dsl/brain-runner.js +7 -6
  2. package/dist/src/dsl/brain-state-machine.js +43 -14
  3. package/dist/src/dsl/builder/brain.js +98 -32
  4. package/dist/src/dsl/constants.js +2 -2
  5. package/dist/src/dsl/execution/event-stream.js +937 -358
  6. package/dist/src/dsl/iterate-result.js +161 -0
  7. package/dist/src/dsl/signal-validation.js +5 -5
  8. package/dist/src/index.js +1 -0
  9. package/dist/src/tools/index.js +0 -3
  10. package/dist/types/dsl/brain-runner.d.ts.map +1 -1
  11. package/dist/types/dsl/brain-state-machine.d.ts +11 -4
  12. package/dist/types/dsl/brain-state-machine.d.ts.map +1 -1
  13. package/dist/types/dsl/brain.d.ts +1 -1
  14. package/dist/types/dsl/brain.d.ts.map +1 -1
  15. package/dist/types/dsl/builder/brain.d.ts +66 -13
  16. package/dist/types/dsl/builder/brain.d.ts.map +1 -1
  17. package/dist/types/dsl/constants.d.ts +1 -1
  18. package/dist/types/dsl/create-brain.d.ts +14 -14
  19. package/dist/types/dsl/create-brain.d.ts.map +1 -1
  20. package/dist/types/dsl/definitions/blocks.d.ts +27 -6
  21. package/dist/types/dsl/definitions/blocks.d.ts.map +1 -1
  22. package/dist/types/dsl/definitions/events.d.ts +9 -6
  23. package/dist/types/dsl/definitions/events.d.ts.map +1 -1
  24. package/dist/types/dsl/definitions/run-params.d.ts +3 -1
  25. package/dist/types/dsl/definitions/run-params.d.ts.map +1 -1
  26. package/dist/types/dsl/duration.d.ts.map +1 -1
  27. package/dist/types/dsl/example-webhook.d.ts.map +1 -1
  28. package/dist/types/dsl/execution/event-stream.d.ts +19 -3
  29. package/dist/types/dsl/execution/event-stream.d.ts.map +1 -1
  30. package/dist/types/dsl/iterate-result.d.ts +13 -0
  31. package/dist/types/dsl/iterate-result.d.ts.map +1 -0
  32. package/dist/types/dsl/pages.d.ts.map +1 -1
  33. package/dist/types/dsl/signal-validation.d.ts.map +1 -1
  34. package/dist/types/dsl/types.d.ts +1 -3
  35. package/dist/types/dsl/types.d.ts.map +1 -1
  36. package/dist/types/dsl/webhook.d.ts +4 -0
  37. package/dist/types/dsl/webhook.d.ts.map +1 -1
  38. package/dist/types/index.d.ts +7 -5
  39. package/dist/types/index.d.ts.map +1 -1
  40. package/dist/types/store/index.d.ts +1 -1
  41. package/dist/types/store/index.d.ts.map +1 -1
  42. package/dist/types/store/types.d.ts +2 -2
  43. package/dist/types/store/types.d.ts.map +1 -1
  44. package/dist/types/tools/index.d.ts.map +1 -1
  45. package/dist/types/ui/generate-page-html.d.ts.map +1 -1
  46. package/dist/types/ui/generate-ui.d.ts.map +1 -1
  47. package/dist/types/ui/parse-form-data.d.ts.map +1 -1
  48. package/dist/types/ui/types.d.ts.map +1 -1
  49. package/dist/types/ui/validate-form.d.ts.map +1 -1
  50. package/dist/types/yaml/data-validator.d.ts.map +1 -1
  51. package/dist/types/yaml/parser.d.ts.map +1 -1
  52. package/dist/types/yaml/type-inference.d.ts.map +1 -1
  53. package/package.json +1 -1
@@ -166,35 +166,6 @@ function AsyncFromSyncIterator(s) {
166
166
  }
167
167
  }, new AsyncFromSyncIterator(s);
168
168
  }
169
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
170
- try {
171
- var info = gen[key](arg);
172
- var value = info.value;
173
- } catch (error) {
174
- reject(error);
175
- return;
176
- }
177
- if (info.done) {
178
- resolve(value);
179
- } else {
180
- Promise.resolve(value).then(_next, _throw);
181
- }
182
- }
183
- function _async_to_generator(fn) {
184
- return function() {
185
- var self = this, args = arguments;
186
- return new Promise(function(resolve, reject) {
187
- var gen = fn.apply(self, args);
188
- function _next(value) {
189
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
190
- }
191
- function _throw(err) {
192
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
193
- }
194
- _next(undefined);
195
- });
196
- };
197
- }
198
169
  function _await_async_generator(value) {
199
170
  return new _overload_yield(value, 0);
200
171
  }
@@ -465,6 +436,7 @@ import { z } from 'zod';
465
436
  import { v4 as uuidv4 } from 'uuid';
466
437
  import { STATUS, BRAIN_EVENTS } from '../constants.js';
467
438
  import { createPatch, applyPatches } from '../json-patch.js';
439
+ import { IterateResult } from '../iterate-result.js';
468
440
  import { generateUI } from '../../ui/generate-ui.js';
469
441
  import { generatePageHtml } from '../../ui/generate-page-html.js';
470
442
  import { createScopedMemory } from '../../memory/scoped-memory.js';
@@ -474,45 +446,6 @@ import { defaultDoneSchema } from '../../tools/index.js';
474
446
  var clone = function(value) {
475
447
  return structuredClone(value);
476
448
  };
477
- function createSemaphore(limit) {
478
- var running = 0;
479
- var queue = [];
480
- return {
481
- acquire: function acquire() {
482
- return _async_to_generator(function() {
483
- return _ts_generator(this, function(_state) {
484
- if (running < limit) {
485
- running++;
486
- return [
487
- 2,
488
- function() {
489
- running--;
490
- if (queue.length > 0) {
491
- running++;
492
- queue.shift()();
493
- }
494
- }
495
- ];
496
- }
497
- return [
498
- 2,
499
- new Promise(function(resolve) {
500
- queue.push(function() {
501
- return resolve(function() {
502
- running--;
503
- if (queue.length > 0) {
504
- running++;
505
- queue.shift()();
506
- }
507
- });
508
- });
509
- })
510
- ];
511
- });
512
- })();
513
- }
514
- };
515
- }
516
449
  export var BrainEventStream = /*#__PURE__*/ function() {
517
450
  "use strict";
518
451
  function BrainEventStream(params) {
@@ -534,6 +467,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
534
467
  _define_property(this, "resumeContext", void 0);
535
468
  _define_property(this, "components", void 0);
536
469
  _define_property(this, "defaultTools", void 0);
470
+ _define_property(this, "extraTools", void 0);
537
471
  _define_property(this, "signalProvider", void 0);
538
472
  _define_property(this, "memoryProvider", void 0);
539
473
  _define_property(this, "scopedMemory", void 0);
@@ -543,7 +477,8 @@ export var BrainEventStream = /*#__PURE__*/ function() {
543
477
  _define_property(this, "guards", new Map());
544
478
  _define_property(this, "waits", new Map());
545
479
  _define_property(this, "stopped", false);
546
- var blocks = params.blocks, title = params.title, description = params.description, providedBrainRunId = params.brainRunId, _params_options = params.options, options = _params_options === void 0 ? {} : _params_options, client = params.client, services = params.services, _params_resources = params.resources, resources = _params_resources === void 0 ? {} : _params_resources, pages = params.pages, env = params.env, components = params.components, defaultTools = params.defaultTools, signalProvider = params.signalProvider, memoryProvider = params.memoryProvider, store = params.store, currentUser = params.currentUser;
480
+ _define_property(this, "optionsSchema", void 0);
481
+ var blocks = params.blocks, title = params.title, description = params.description, providedBrainRunId = params.brainRunId, _params_options = params.options, options = _params_options === void 0 ? {} : _params_options, client = params.client, services = params.services, _params_resources = params.resources, resources = _params_resources === void 0 ? {} : _params_resources, pages = params.pages, env = params.env, components = params.components, defaultTools = params.defaultTools, extraTools = params.extraTools, signalProvider = params.signalProvider, memoryProvider = params.memoryProvider, store = params.store, currentUser = params.currentUser;
547
482
  // Store governor for per-step client resolution
548
483
  this.governor = params.governor;
549
484
  this.currentUser = currentUser;
@@ -562,9 +497,11 @@ export var BrainEventStream = /*#__PURE__*/ function() {
562
497
  this.resumeContext = resumeContext;
563
498
  this.components = components;
564
499
  this.defaultTools = defaultTools;
500
+ this.extraTools = extraTools;
565
501
  this.signalProvider = signalProvider;
566
502
  this.memoryProvider = memoryProvider;
567
503
  this.store = store;
504
+ this.optionsSchema = params.optionsSchema;
568
505
  // Create scoped memory if provider is configured
569
506
  if (memoryProvider) {
570
507
  this.scopedMemory = createScopedMemory(memoryProvider, title, this.currentUser.name);
@@ -611,7 +548,16 @@ export var BrainEventStream = /*#__PURE__*/ function() {
611
548
  if (!signalProvider && resumeContext.webhookResponse && !resumeContext.agentContext) {
612
549
  this.currentResponse = resumeContext.webhookResponse;
613
550
  }
614
- // Agent webhook response is handled via agentContext (checked in executeAgent)
551
+ // Agent webhook response is handled via agentContext (checked in executeAgent)
552
+ // Restore page context if available (from a preceding UI step)
553
+ if (resumeContext.currentPage) {
554
+ this.currentPage = {
555
+ url: resumeContext.currentPage.url,
556
+ webhook: _object_spread_props(_object_spread({}, resumeContext.currentPage.webhook), {
557
+ schema: z.record(z.unknown())
558
+ })
559
+ };
560
+ }
615
561
  } else {
616
562
  var _initialParams_initialState;
617
563
  // Fresh start: use initialState or empty object
@@ -685,6 +631,12 @@ export var BrainEventStream = /*#__PURE__*/ function() {
685
631
  ];
686
632
  case 3:
687
633
  _state.sent();
634
+ // Validate options after START so errors are visible in watch/history
635
+ if (this.optionsSchema) {
636
+ this.options = this.optionsSchema.parse(this.options);
637
+ } else if (this.options && Object.keys(this.options).length > 0) {
638
+ throw new Error("Brain '".concat(brainTitle, "' received options but no schema was defined. Use withOptionsSchema() to define a schema for options."));
639
+ }
688
640
  return [
689
641
  3,
690
642
  11
@@ -956,7 +908,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
956
908
  ];
957
909
  case 29:
958
910
  _state.sent();
959
- // Backend requested a stop (e.g. batch chunk pause for DO restart)
911
+ // Backend requested a stop (e.g. iterate item pause for DO restart)
960
912
  if (this.stopped) {
961
913
  return [
962
914
  2
@@ -1052,11 +1004,32 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1052
1004
  }).call(this);
1053
1005
  }
1054
1006
  },
1007
+ {
1008
+ key: "buildStepContext",
1009
+ value: function buildStepContext(step) {
1010
+ var _this_options;
1011
+ return _object_spread({
1012
+ state: this.currentState,
1013
+ options: (_this_options = this.options) !== null && _this_options !== void 0 ? _this_options : {},
1014
+ client: this.client,
1015
+ resources: this.resources,
1016
+ response: this.currentResponse,
1017
+ page: this.currentPage,
1018
+ pages: this.pages,
1019
+ env: this.env,
1020
+ memory: this.scopedMemory,
1021
+ store: this.store,
1022
+ currentUser: this.currentUser,
1023
+ brainRunId: this.brainRunId,
1024
+ stepId: step.id
1025
+ }, this.services);
1026
+ }
1027
+ },
1055
1028
  {
1056
1029
  key: "executeStep",
1057
1030
  value: function executeStep(step) {
1058
1031
  return _wrap_async_generator(function() {
1059
- var block, stepBlock, _this_resumeContext, brainBlock, initialState, innerResumeContext, patches, innerBrainPaused, _this_options, _this_options1, innerRun, _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, _value, event, err, _innerResumeContext_state, baseState, innerState, prevState, _, prevState1, stepBlock1, stepClient, _this_options2, result;
1032
+ var block, stepBlock, _this_resumeContext, brainBlock, initialState, innerResumeContext, patches, innerBrainPaused, _this_options, _this_options1, innerRun, _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, _value, event, err, _innerResumeContext_state, baseState, innerState, prevState, _, agentBlock, prevState1, prevState2, stepBlock1, stepClient, _this_options2, result;
1060
1033
  return _ts_generator(this, function(_state) {
1061
1034
  switch(_state.label){
1062
1035
  case 0:
@@ -1080,13 +1053,13 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1080
1053
  2
1081
1054
  ];
1082
1055
  case 2:
1083
- if (!stepBlock.batchConfig) return [
1056
+ if (!stepBlock.iterateConfig) return [
1084
1057
  3,
1085
1058
  4
1086
1059
  ];
1087
1060
  return [
1088
1061
  5,
1089
- _ts_values(_async_generator_delegate(_async_iterator(this.executeBatchPrompt(step))))
1062
+ _ts_values(_async_generator_delegate(_async_iterator(this.executeIteratePrompt(step))))
1090
1063
  ];
1091
1064
  case 3:
1092
1065
  _state.sent();
@@ -1096,9 +1069,23 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1096
1069
  case 4:
1097
1070
  if (!(block.type === 'brain')) return [
1098
1071
  3,
1099
- 20
1072
+ 22
1100
1073
  ];
1101
1074
  brainBlock = block;
1075
+ if (!brainBlock.iterateConfig) return [
1076
+ 3,
1077
+ 6
1078
+ ];
1079
+ return [
1080
+ 5,
1081
+ _ts_values(_async_generator_delegate(_async_iterator(this.executeIterateBrain(step))))
1082
+ ];
1083
+ case 5:
1084
+ _state.sent();
1085
+ return [
1086
+ 2
1087
+ ];
1088
+ case 6:
1102
1089
  initialState = typeof brainBlock.initialState === 'function' ? brainBlock.initialState(this.currentState) : brainBlock.initialState;
1103
1090
  // Check if we're resuming and if there's an inner resume context
1104
1091
  innerResumeContext = (_this_resumeContext = this.resumeContext) === null || _this_resumeContext === void 0 ? void 0 : _this_resumeContext.innerResumeContext;
@@ -1128,25 +1115,25 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1128
1115
  governor: this.governor
1129
1116
  });
1130
1117
  _iteratorAbruptCompletion = false, _didIteratorError = false;
1131
- _state.label = 5;
1132
- case 5:
1118
+ _state.label = 7;
1119
+ case 7:
1133
1120
  _state.trys.push([
1134
- 5,
1135
- 11,
1136
- 12,
1137
- 17
1121
+ 7,
1122
+ 13,
1123
+ 14,
1124
+ 19
1138
1125
  ]);
1139
1126
  _iterator = _async_iterator(innerRun);
1140
- _state.label = 6;
1141
- case 6:
1127
+ _state.label = 8;
1128
+ case 8:
1142
1129
  return [
1143
1130
  4,
1144
1131
  _await_async_generator(_iterator.next())
1145
1132
  ];
1146
- case 7:
1133
+ case 9:
1147
1134
  if (!(_iteratorAbruptCompletion = !(_step = _state.sent()).done)) return [
1148
1135
  3,
1149
- 10
1136
+ 12
1150
1137
  ];
1151
1138
  _value = _step.value;
1152
1139
  event = _value;
@@ -1154,7 +1141,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1154
1141
  4,
1155
1142
  event
1156
1143
  ];
1157
- case 8:
1144
+ case 10:
1158
1145
  _state.sent(); // Forward all inner brain events
1159
1146
  if (event.type === BRAIN_EVENTS.STEP_COMPLETE) {
1160
1147
  patches.push(event.patch);
@@ -1167,64 +1154,64 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1167
1154
  if (event.type === BRAIN_EVENTS.COMPLETE) {
1168
1155
  return [
1169
1156
  3,
1170
- 10
1157
+ 12
1171
1158
  ];
1172
1159
  }
1173
- _state.label = 9;
1174
- case 9:
1160
+ _state.label = 11;
1161
+ case 11:
1175
1162
  _iteratorAbruptCompletion = false;
1176
1163
  return [
1177
1164
  3,
1178
- 6
1165
+ 8
1179
1166
  ];
1180
- case 10:
1167
+ case 12:
1181
1168
  return [
1182
1169
  3,
1183
- 17
1170
+ 19
1184
1171
  ];
1185
- case 11:
1172
+ case 13:
1186
1173
  err = _state.sent();
1187
1174
  _didIteratorError = true;
1188
1175
  _iteratorError = err;
1189
1176
  return [
1190
1177
  3,
1191
- 17
1178
+ 19
1192
1179
  ];
1193
- case 12:
1180
+ case 14:
1194
1181
  _state.trys.push([
1195
- 12,
1182
+ 14,
1196
1183
  ,
1197
- 15,
1198
- 16
1184
+ 17,
1185
+ 18
1199
1186
  ]);
1200
1187
  if (!(_iteratorAbruptCompletion && _iterator.return != null)) return [
1201
1188
  3,
1202
- 14
1189
+ 16
1203
1190
  ];
1204
1191
  return [
1205
1192
  4,
1206
1193
  _await_async_generator(_iterator.return())
1207
1194
  ];
1208
- case 13:
1195
+ case 15:
1209
1196
  _state.sent();
1210
- _state.label = 14;
1211
- case 14:
1197
+ _state.label = 16;
1198
+ case 16:
1212
1199
  return [
1213
1200
  3,
1214
- 16
1201
+ 18
1215
1202
  ];
1216
- case 15:
1203
+ case 17:
1217
1204
  if (_didIteratorError) {
1218
1205
  throw _iteratorError;
1219
1206
  }
1220
1207
  return [
1221
1208
  7
1222
1209
  ];
1223
- case 16:
1210
+ case 18:
1224
1211
  return [
1225
1212
  7
1226
1213
  ];
1227
- case 17:
1214
+ case 19:
1228
1215
  // If inner brain paused for webhook, don't complete the outer brain step
1229
1216
  // The outer brain should also pause
1230
1217
  if (innerBrainPaused) {
@@ -1244,36 +1231,58 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1244
1231
  4,
1245
1232
  _await_async_generator(brainBlock.action(this.currentState, innerState, this.services))
1246
1233
  ];
1247
- case 18:
1234
+ case 20:
1248
1235
  _.currentState = _state.sent();
1249
1236
  return [
1250
1237
  5,
1251
1238
  _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
1252
1239
  ];
1253
- case 19:
1240
+ case 21:
1254
1241
  _state.sent();
1255
1242
  return [
1256
1243
  3,
1257
- 25
1244
+ 30
1258
1245
  ];
1259
- case 20:
1246
+ case 22:
1260
1247
  if (!(block.type === 'agent')) return [
1261
1248
  3,
1262
- 22
1249
+ 27
1250
+ ];
1251
+ agentBlock = block;
1252
+ if (!agentBlock.iterateConfig) return [
1253
+ 3,
1254
+ 24
1255
+ ];
1256
+ return [
1257
+ 5,
1258
+ _ts_values(_async_generator_delegate(_async_iterator(this.executeIterateAgent(step))))
1259
+ ];
1260
+ case 23:
1261
+ _state.sent();
1262
+ return [
1263
+ 2
1263
1264
  ];
1265
+ case 24:
1266
+ prevState1 = this.currentState;
1264
1267
  return [
1265
1268
  5,
1266
1269
  _ts_values(_async_generator_delegate(_async_iterator(this.executeAgent(step))))
1267
1270
  ];
1268
- case 21:
1271
+ case 25:
1272
+ _state.sent();
1273
+ return [
1274
+ 5,
1275
+ _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState1))))
1276
+ ];
1277
+ case 26:
1269
1278
  _state.sent();
1270
1279
  return [
1271
1280
  3,
1272
- 25
1281
+ 30
1273
1282
  ];
1274
- case 22:
1283
+ case 27:
1275
1284
  // Get previous state before action
1276
- prevState1 = this.currentState;
1285
+ prevState2 = this.currentState;
1277
1286
  stepBlock1 = block;
1278
1287
  // Resolve per-step client: if the step has an override, apply governor to it;
1279
1288
  // otherwise use the default (already-governed) client
@@ -1294,7 +1303,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1294
1303
  currentUser: this.currentUser
1295
1304
  }, this.services))))
1296
1305
  ];
1297
- case 23:
1306
+ case 28:
1298
1307
  result = _state.sent();
1299
1308
  // Extract state from result (handles promptResponse case)
1300
1309
  if (result && (typeof result === "undefined" ? "undefined" : _type_of(result)) === 'object' && 'promptResponse' in result) {
@@ -1304,9 +1313,9 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1304
1313
  }
1305
1314
  return [
1306
1315
  5,
1307
- _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState1))))
1316
+ _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState2))))
1308
1317
  ];
1309
- case 24:
1318
+ case 29:
1310
1319
  _state.sent();
1311
1320
  // Handle promptResponse - set currentResponse for next step
1312
1321
  if (result && (typeof result === "undefined" ? "undefined" : _type_of(result)) === 'object' && 'promptResponse' in result) {
@@ -1314,8 +1323,8 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1314
1323
  }
1315
1324
  // Reset currentPage after step consumes it (page is ephemeral)
1316
1325
  this.currentPage = undefined;
1317
- _state.label = 25;
1318
- case 25:
1326
+ _state.label = 30;
1327
+ case 30:
1319
1328
  return [
1320
1329
  2
1321
1330
  ];
@@ -1328,21 +1337,21 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1328
1337
  key: "executeAgent",
1329
1338
  value: function executeAgent(step) {
1330
1339
  return _wrap_async_generator(function() {
1331
- var _this_resumeContext, _this_resumeContext1, block, prevState, _this_defaultTools, defaultTools, _this_components, components, _this_options, config, _config_tools, mergedTools, _config_outputSchema, schema, name, responseMessages, initialMessages, agentContext, webhookResponse, _agentContext_stepId, effectiveStepId, _this_options1, _this_options2, userMessage, toolResultMessage, _this_options3, userMessage1, _config_prompt, prompt, _this_options4, totalTokens, iteration, _config_maxIterations, maxIterations, _response_responseMessages, signals, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, signal, userMessage2, _this_options5, err, _this_options6, toolsForClient, _iteratorNormalCompletion1, _didIteratorError1, _iteratorError1, _iterator1, _step1, _step_value, name1, toolDef, tool, description, componentList, systemPrompt, response, newAssistantMessage, _this_options7, tokensThisIteration, _this_options8, _this_options9, _this_options10, pendingWebhook, _iteratorNormalCompletion2, _didIteratorError2, _iteratorError2, _iterator2, _step2, toolCall, _this_options11, tool1, _this_options12, _this_options13, toolContext, toolResult, waitForResult, webhooks, _this_options14, placeholderMessage, _this_options15, toolResultMessage1, _this_options16, err, _this_options17, _this_options18;
1340
+ var _this_resumeContext, _this_resumeContext1, block, prevState, _this_defaultTools, _this_extraTools, allTools, _this_components, components, _this_options, config, _config_tools, mergedTools, _config_outputSchema, schema, name, responseMessages, initialMessages, agentContext, webhookResponse, _agentContext_stepId, effectiveStepId, _this_options1, _this_options2, userMessage, toolResultMessage, _this_options3, userMessage1, _config_prompt, prompt, _this_options4, totalTokens, iteration, _config_maxIterations, maxIterations, _response_responseMessages, signals, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, signal, userMessage2, _this_options5, err, _this_options6, toolsForClient, _iteratorNormalCompletion1, _didIteratorError1, _iteratorError1, _iterator1, _step1, _step_value, name1, toolDef, tool, description, componentList, systemPrompt, response, newAssistantMessage, _this_options7, tokensThisIteration, _this_options8, _this_options9, _this_options10, pendingWebhook, _iteratorNormalCompletion2, _didIteratorError2, _iteratorError2, _iterator2, _step2, toolCall, _this_options11, tool1, _this_options12, parsed, _this_options13, toolContext, toolResult, waitForResult, webhooks, _this_options14, placeholderMessage, _this_options15, toolResultMessage1, _this_options16, err, _this_options17, _this_options18;
1332
1341
  return _ts_generator(this, function(_state) {
1333
1342
  switch(_state.label){
1334
1343
  case 0:
1335
1344
  block = step.block;
1336
1345
  prevState = this.currentState;
1337
- // Get default tools and components for injection into configFn
1338
- defaultTools = (_this_defaultTools = this.defaultTools) !== null && _this_defaultTools !== void 0 ? _this_defaultTools : {};
1346
+ // Combine default tools and extra tools for injection into configFn
1347
+ allTools = _object_spread({}, (_this_defaultTools = this.defaultTools) !== null && _this_defaultTools !== void 0 ? _this_defaultTools : {}, (_this_extraTools = this.extraTools) !== null && _this_extraTools !== void 0 ? _this_extraTools : {});
1339
1348
  components = (_this_components = this.components) !== null && _this_components !== void 0 ? _this_components : {};
1340
1349
  return [
1341
1350
  4,
1342
1351
  _await_async_generator(block.configFn(_object_spread({
1343
1352
  state: this.currentState,
1344
1353
  options: (_this_options = this.options) !== null && _this_options !== void 0 ? _this_options : {},
1345
- tools: defaultTools,
1354
+ tools: allTools,
1346
1355
  components: components,
1347
1356
  client: this.client,
1348
1357
  resources: this.resources,
@@ -1359,8 +1368,8 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1359
1368
  config = _state.sent();
1360
1369
  // Reset currentPage after configFn consumes it (page is ephemeral)
1361
1370
  this.currentPage = undefined;
1362
- // Merge tools: step tools override defaults
1363
- mergedTools = _object_spread({}, defaultTools, (_config_tools = config.tools) !== null && _config_tools !== void 0 ? _config_tools : {});
1371
+ // Merge tools: step tools override defaults + extras
1372
+ mergedTools = _object_spread({}, allTools, (_config_tools = config.tools) !== null && _config_tools !== void 0 ? _config_tools : {});
1364
1373
  // Always generate a 'done' terminal tool for every agent
1365
1374
  // If outputSchema is provided, use that schema; otherwise use defaultDoneSchema
1366
1375
  if (config.outputSchema) {
@@ -1525,7 +1534,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1525
1534
  case 12:
1526
1535
  if (!true) return [
1527
1536
  3,
1528
- 60
1537
+ 55
1529
1538
  ];
1530
1539
  iteration++;
1531
1540
  if (!this.signalProvider) return [
@@ -1683,7 +1692,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1683
1692
  case 26:
1684
1693
  if (!(iteration > maxIterations)) return [
1685
1694
  3,
1686
- 29
1695
+ 28
1687
1696
  ];
1688
1697
  return [
1689
1698
  4,
@@ -1700,16 +1709,13 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1700
1709
  ];
1701
1710
  case 27:
1702
1711
  _state.sent();
1703
- return [
1704
- 5,
1705
- _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
1706
- ];
1707
- case 28:
1708
- _state.sent();
1712
+ if (config.outputSchema) {
1713
+ throw new Error("Agent hit iteration limit (".concat(maxIterations, ") without producing required '").concat(config.outputSchema.name, "' output"));
1714
+ }
1709
1715
  return [
1710
1716
  2
1711
1717
  ];
1712
- case 29:
1718
+ case 28:
1713
1719
  // Check if client supports generateText
1714
1720
  if (!this.client.generateText) {
1715
1721
  throw new Error('Client does not support generateText. Use a client that implements generateText for agent steps.');
@@ -1762,7 +1768,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1762
1768
  toolChoice: config.toolChoice
1763
1769
  }))
1764
1770
  ];
1765
- case 30:
1771
+ case 29:
1766
1772
  response = _state.sent();
1767
1773
  // Update responseMessages for next iteration (preserves providerOptions)
1768
1774
  responseMessages = response.responseMessages;
@@ -1770,7 +1776,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1770
1776
  newAssistantMessage = (_response_responseMessages = response.responseMessages) === null || _response_responseMessages === void 0 ? void 0 : _response_responseMessages.at(-1);
1771
1777
  if (!newAssistantMessage) return [
1772
1778
  3,
1773
- 32
1779
+ 31
1774
1780
  ];
1775
1781
  return [
1776
1782
  4,
@@ -1784,10 +1790,10 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1784
1790
  brainRunId: this.brainRunId
1785
1791
  }
1786
1792
  ];
1787
- case 31:
1793
+ case 30:
1788
1794
  _state.sent();
1789
- _state.label = 32;
1790
- case 32:
1795
+ _state.label = 31;
1796
+ case 31:
1791
1797
  // Track tokens
1792
1798
  tokensThisIteration = response.usage.totalTokens;
1793
1799
  totalTokens += tokensThisIteration;
@@ -1805,11 +1811,11 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1805
1811
  brainRunId: this.brainRunId
1806
1812
  }
1807
1813
  ];
1808
- case 33:
1814
+ case 32:
1809
1815
  _state.sent();
1810
1816
  if (!(config.maxTokens && totalTokens > config.maxTokens)) return [
1811
1817
  3,
1812
- 36
1818
+ 34
1813
1819
  ];
1814
1820
  return [
1815
1821
  4,
@@ -1823,21 +1829,18 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1823
1829
  brainRunId: this.brainRunId
1824
1830
  }
1825
1831
  ];
1826
- case 34:
1827
- _state.sent();
1828
- return [
1829
- 5,
1830
- _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
1831
- ];
1832
- case 35:
1832
+ case 33:
1833
1833
  _state.sent();
1834
+ if (config.outputSchema) {
1835
+ throw new Error("Agent hit token limit (".concat(config.maxTokens, ") without producing required '").concat(config.outputSchema.name, "' output"));
1836
+ }
1834
1837
  return [
1835
1838
  2
1836
1839
  ];
1837
- case 36:
1840
+ case 34:
1838
1841
  if (!response.text) return [
1839
1842
  3,
1840
- 38
1843
+ 36
1841
1844
  ];
1842
1845
  // Log assistant messages to console as fallback (users shouldn't rely on this)
1843
1846
  console.log("[Assistant] ".concat(response.text));
@@ -1852,42 +1855,34 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1852
1855
  brainRunId: this.brainRunId
1853
1856
  }
1854
1857
  ];
1855
- case 37:
1856
- _state.sent();
1857
- _state.label = 38;
1858
- case 38:
1859
- if (!(!response.toolCalls || response.toolCalls.length === 0)) return [
1860
- 3,
1861
- 40
1862
- ];
1863
- return [
1864
- 5,
1865
- _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
1866
- ];
1867
- case 39:
1858
+ case 35:
1868
1859
  _state.sent();
1869
- return [
1870
- 2
1871
- ];
1872
- case 40:
1860
+ _state.label = 36;
1861
+ case 36:
1862
+ // If no tool calls, agent is done
1863
+ if (!response.toolCalls || response.toolCalls.length === 0) {
1864
+ return [
1865
+ 2
1866
+ ];
1867
+ }
1873
1868
  // Track pending webhook if any tool returns waitFor
1874
1869
  // We process ALL tool calls first, then pause for webhook at the end
1875
1870
  pendingWebhook = null;
1876
1871
  _iteratorNormalCompletion2 = true, _didIteratorError2 = false, _iteratorError2 = undefined;
1877
- _state.label = 41;
1878
- case 41:
1872
+ _state.label = 37;
1873
+ case 37:
1879
1874
  _state.trys.push([
1880
- 41,
1881
- 54,
1882
- 55,
1883
- 56
1875
+ 37,
1876
+ 49,
1877
+ 50,
1878
+ 51
1884
1879
  ]);
1885
1880
  _iterator2 = response.toolCalls[Symbol.iterator]();
1886
- _state.label = 42;
1887
- case 42:
1881
+ _state.label = 38;
1882
+ case 38:
1888
1883
  if (!!(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done)) return [
1889
1884
  3,
1890
- 53
1885
+ 48
1891
1886
  ];
1892
1887
  toolCall = _step2.value;
1893
1888
  return [
@@ -1903,7 +1898,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1903
1898
  brainRunId: this.brainRunId
1904
1899
  }
1905
1900
  ];
1906
- case 43:
1901
+ case 39:
1907
1902
  _state.sent();
1908
1903
  tool1 = mergedTools[toolCall.toolName];
1909
1904
  if (!tool1) {
@@ -1911,7 +1906,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1911
1906
  }
1912
1907
  if (!tool1.terminal) return [
1913
1908
  3,
1914
- 46
1909
+ 41
1915
1910
  ];
1916
1911
  return [
1917
1912
  4,
@@ -1927,30 +1922,28 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1927
1922
  brainRunId: this.brainRunId
1928
1923
  }
1929
1924
  ];
1930
- case 44:
1925
+ case 40:
1931
1926
  _state.sent();
1932
1927
  // Merge terminal result into state
1933
1928
  // Only namespace under outputSchema.name when 'done' tool is called with outputSchema
1934
1929
  if (config.outputSchema && toolCall.toolName === 'done') {
1930
+ parsed = config.outputSchema.schema.safeParse(toolCall.args);
1931
+ if (!parsed.success) {
1932
+ throw new Error("Agent output does not match outputSchema '".concat(config.outputSchema.name, "': ").concat(parsed.error.message));
1933
+ }
1935
1934
  // Namespace result under outputSchema.name
1936
- this.currentState = _object_spread_props(_object_spread({}, this.currentState), _define_property({}, config.outputSchema.name, toolCall.args));
1935
+ this.currentState = _object_spread_props(_object_spread({}, this.currentState), _define_property({}, config.outputSchema.name, parsed.data));
1937
1936
  } else {
1938
1937
  // Default behavior: spread into state root (for other terminal tools)
1939
1938
  this.currentState = _object_spread({}, this.currentState, toolCall.args);
1940
1939
  }
1941
- return [
1942
- 5,
1943
- _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
1944
- ];
1945
- case 45:
1946
- _state.sent();
1947
1940
  return [
1948
1941
  2
1949
1942
  ];
1950
- case 46:
1943
+ case 41:
1951
1944
  if (!tool1.execute) return [
1952
1945
  3,
1953
- 52
1946
+ 47
1954
1947
  ];
1955
1948
  toolContext = {
1956
1949
  state: this.currentState,
@@ -1972,11 +1965,11 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1972
1965
  4,
1973
1966
  _await_async_generator(tool1.execute(toolCall.args, toolContext))
1974
1967
  ];
1975
- case 47:
1968
+ case 42:
1976
1969
  toolResult = _state.sent();
1977
1970
  if (!(toolResult && (typeof toolResult === "undefined" ? "undefined" : _type_of(toolResult)) === 'object' && 'waitFor' in toolResult)) return [
1978
1971
  3,
1979
- 49
1972
+ 44
1980
1973
  ];
1981
1974
  waitForResult = toolResult;
1982
1975
  // Normalize waitFor to array (supports single or multiple webhooks)
@@ -2015,7 +2008,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
2015
2008
  brainRunId: this.brainRunId
2016
2009
  }
2017
2010
  ];
2018
- case 48:
2011
+ case 43:
2019
2012
  _state.sent();
2020
2013
  // Add placeholder to responseMessages locally so the conversation stays valid
2021
2014
  // for any subsequent generateText calls in this execution.
@@ -2033,9 +2026,9 @@ export var BrainEventStream = /*#__PURE__*/ function() {
2033
2026
  // Continue processing other tool calls - don't return yet
2034
2027
  return [
2035
2028
  3,
2036
- 52
2029
+ 47
2037
2030
  ];
2038
- case 49:
2031
+ case 44:
2039
2032
  // Emit tool result event for debugging/visibility
2040
2033
  return [
2041
2034
  4,
@@ -2050,11 +2043,11 @@ export var BrainEventStream = /*#__PURE__*/ function() {
2050
2043
  brainRunId: this.brainRunId
2051
2044
  }
2052
2045
  ];
2053
- case 50:
2046
+ case 45:
2054
2047
  _state.sent();
2055
2048
  if (!(this.client.createToolResultMessage && responseMessages)) return [
2056
2049
  3,
2057
- 52
2050
+ 47
2058
2051
  ];
2059
2052
  toolResultMessage1 = this.client.createToolResultMessage(toolCall.toolCallId, toolCall.toolName, toolResult);
2060
2053
  responseMessages = _to_consumable_array(responseMessages).concat([
@@ -2073,29 +2066,29 @@ export var BrainEventStream = /*#__PURE__*/ function() {
2073
2066
  brainRunId: this.brainRunId
2074
2067
  }
2075
2068
  ];
2076
- case 51:
2069
+ case 46:
2077
2070
  _state.sent();
2078
- _state.label = 52;
2079
- case 52:
2071
+ _state.label = 47;
2072
+ case 47:
2080
2073
  _iteratorNormalCompletion2 = true;
2081
2074
  return [
2082
2075
  3,
2083
- 42
2076
+ 38
2084
2077
  ];
2085
- case 53:
2078
+ case 48:
2086
2079
  return [
2087
2080
  3,
2088
- 56
2081
+ 51
2089
2082
  ];
2090
- case 54:
2083
+ case 49:
2091
2084
  err = _state.sent();
2092
2085
  _didIteratorError2 = true;
2093
2086
  _iteratorError2 = err;
2094
2087
  return [
2095
2088
  3,
2096
- 56
2089
+ 51
2097
2090
  ];
2098
- case 55:
2091
+ case 50:
2099
2092
  try {
2100
2093
  if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
2101
2094
  _iterator2.return();
@@ -2108,10 +2101,10 @@ export var BrainEventStream = /*#__PURE__*/ function() {
2108
2101
  return [
2109
2102
  7
2110
2103
  ];
2111
- case 56:
2104
+ case 51:
2112
2105
  if (!pendingWebhook) return [
2113
2106
  3,
2114
- 59
2107
+ 54
2115
2108
  ];
2116
2109
  // Emit AGENT_WEBHOOK event
2117
2110
  return [
@@ -2127,7 +2120,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
2127
2120
  brainRunId: this.brainRunId
2128
2121
  }
2129
2122
  ];
2130
- case 57:
2123
+ case 52:
2131
2124
  _state.sent();
2132
2125
  // Emit WEBHOOK event with all webhooks (first response wins)
2133
2126
  return [
@@ -2142,17 +2135,17 @@ export var BrainEventStream = /*#__PURE__*/ function() {
2142
2135
  brainRunId: this.brainRunId
2143
2136
  })
2144
2137
  ];
2145
- case 58:
2138
+ case 53:
2146
2139
  _state.sent();
2147
2140
  return [
2148
2141
  2
2149
2142
  ];
2150
- case 59:
2143
+ case 54:
2151
2144
  return [
2152
2145
  3,
2153
2146
  12
2154
2147
  ];
2155
- case 60:
2148
+ case 55:
2156
2149
  return [
2157
2150
  2
2158
2151
  ];
@@ -2162,73 +2155,83 @@ export var BrainEventStream = /*#__PURE__*/ function() {
2162
2155
  }
2163
2156
  },
2164
2157
  {
2165
- key: "executeBatchPrompt",
2158
+ key: "executeIteratePrompt",
2166
2159
  value: /**
2167
- * Execute a batch prompt step in chunks, yielding one BATCH_CHUNK_COMPLETE
2168
- * event per chunk. Between chunks, checks for PAUSE/KILL signals so
2160
+ * Execute an iterate prompt step, yielding one ITERATE_ITEM_COMPLETE
2161
+ * event per item. Between items, checks for PAUSE/KILL signals so
2169
2162
  * Cloudflare backends can restart the DO to reclaim memory.
2170
- */ function executeBatchPrompt(step) {
2163
+ */ function executeIteratePrompt(step) {
2171
2164
  return _wrap_async_generator(function() {
2172
- var _this, _this_resumeContext, block, batchConfig, prevState, rawClient, client, items, totalItems, _batchConfig_concurrency, concurrency, semaphore, batchProgress, _batchProgress_processedCount, startIndex, results, chunkStart, signals, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, signal, _this_options, err, chunkEnd, chunk, chunkResults, i, _this_options1, finalResults;
2165
+ var _this_resumeContext, block, iterateConfig, prevState, rawClient, client, items, totalItems, iterateProgress, _iterateProgress_processedCount, startIndex, resultsMap, k, r, i, signals, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, signal, _this_options, err, item, result, _this_options1, promptText, response, error, fallback, _this_options2, finalResults;
2173
2166
  return _ts_generator(this, function(_state) {
2174
2167
  switch(_state.label){
2175
2168
  case 0:
2176
- _this = this;
2177
2169
  block = step.block;
2178
- batchConfig = block.batchConfig;
2170
+ iterateConfig = block.iterateConfig;
2179
2171
  prevState = this.currentState;
2180
- rawClient = batchConfig.client;
2172
+ rawClient = iterateConfig.client;
2181
2173
  client = rawClient ? this.governor ? this.governor(rawClient) : rawClient : this.client;
2182
- items = batchConfig.over(this.currentState);
2174
+ return [
2175
+ 4,
2176
+ _await_async_generator(iterateConfig.over(this.buildStepContext(step)))
2177
+ ];
2178
+ case 1:
2179
+ items = _state.sent();
2183
2180
  totalItems = items.length;
2184
- concurrency = (_batchConfig_concurrency = batchConfig.concurrency) !== null && _batchConfig_concurrency !== void 0 ? _batchConfig_concurrency : 10;
2185
- semaphore = createSemaphore(concurrency);
2186
2181
  // Resume support: pick up from where we left off
2187
- batchProgress = (_this_resumeContext = this.resumeContext) === null || _this_resumeContext === void 0 ? void 0 : _this_resumeContext.batchProgress;
2188
- startIndex = (_batchProgress_processedCount = batchProgress === null || batchProgress === void 0 ? void 0 : batchProgress.processedCount) !== null && _batchProgress_processedCount !== void 0 ? _batchProgress_processedCount : 0;
2189
- results = (batchProgress === null || batchProgress === void 0 ? void 0 : batchProgress.accumulatedResults) ? _to_consumable_array(batchProgress.accumulatedResults) : new Array(totalItems);
2190
- // Clear resumeContext after consuming batchProgress
2191
- if (batchProgress) {
2182
+ iterateProgress = (_this_resumeContext = this.resumeContext) === null || _this_resumeContext === void 0 ? void 0 : _this_resumeContext.iterateProgress;
2183
+ startIndex = (_iterateProgress_processedCount = iterateProgress === null || iterateProgress === void 0 ? void 0 : iterateProgress.processedCount) !== null && _iterateProgress_processedCount !== void 0 ? _iterateProgress_processedCount : 0;
2184
+ // Use a Map for results accumulation during iteration.
2185
+ resultsMap = new Map();
2186
+ if (iterateProgress === null || iterateProgress === void 0 ? void 0 : iterateProgress.accumulatedResults) {
2187
+ for(k = 0; k < iterateProgress.accumulatedResults.length; k++){
2188
+ r = iterateProgress.accumulatedResults[k];
2189
+ if (r != null) resultsMap.set(k, r);
2190
+ }
2191
+ }
2192
+ // Clear resumeContext after consuming iterateProgress
2193
+ if (iterateProgress) {
2192
2194
  this.resumeContext = undefined;
2193
2195
  }
2194
- chunkStart = startIndex;
2195
- _state.label = 1;
2196
- case 1:
2197
- if (!(chunkStart < totalItems)) return [
2196
+ i = startIndex;
2197
+ _state.label = 2;
2198
+ case 2:
2199
+ if (!(i < totalItems)) return [
2198
2200
  3,
2199
- 15
2201
+ 20
2200
2202
  ];
2201
2203
  if (!this.signalProvider) return [
2202
2204
  3,
2203
- 11
2205
+ 12
2204
2206
  ];
2205
2207
  return [
2206
2208
  4,
2207
2209
  _await_async_generator(this.signalProvider.getSignals('CONTROL'))
2208
2210
  ];
2209
- case 2:
2211
+ case 3:
2210
2212
  signals = _state.sent();
2211
2213
  _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2212
- _state.label = 3;
2213
- case 3:
2214
+ _state.label = 4;
2215
+ case 4:
2214
2216
  _state.trys.push([
2215
- 3,
2216
- 9,
2217
+ 4,
2217
2218
  10,
2218
- 11
2219
+ 11,
2220
+ 12
2219
2221
  ]);
2220
2222
  _iterator = signals[Symbol.iterator]();
2221
- _state.label = 4;
2222
- case 4:
2223
+ _state.label = 5;
2224
+ case 5:
2223
2225
  if (!!(_iteratorNormalCompletion = (_step = _iterator.next()).done)) return [
2224
2226
  3,
2225
- 8
2227
+ 9
2226
2228
  ];
2227
2229
  signal = _step.value;
2228
2230
  if (!(signal.type === 'KILL')) return [
2229
2231
  3,
2230
- 6
2232
+ 7
2231
2233
  ];
2234
+ this.stopped = true;
2232
2235
  return [
2233
2236
  4,
2234
2237
  {
@@ -2240,14 +2243,14 @@ export var BrainEventStream = /*#__PURE__*/ function() {
2240
2243
  options: (_this_options = this.options) !== null && _this_options !== void 0 ? _this_options : {}
2241
2244
  }
2242
2245
  ];
2243
- case 5:
2246
+ case 6:
2244
2247
  _state.sent();
2245
2248
  return [
2246
2249
  2
2247
2250
  ];
2248
- case 6:
2251
+ case 7:
2249
2252
  if (signal.type === 'PAUSE') {
2250
- // Don't yield PAUSED - pausing between batch chunks is a backend
2253
+ // Don't yield PAUSED - pausing between iterate items is a backend
2251
2254
  // implementation detail (e.g. Cloudflare DO restart for memory).
2252
2255
  // Just stop execution silently; the backend handles resume.
2253
2256
  this.stopped = true;
@@ -2255,27 +2258,27 @@ export var BrainEventStream = /*#__PURE__*/ function() {
2255
2258
  2
2256
2259
  ];
2257
2260
  }
2258
- _state.label = 7;
2259
- case 7:
2261
+ _state.label = 8;
2262
+ case 8:
2260
2263
  _iteratorNormalCompletion = true;
2261
2264
  return [
2262
2265
  3,
2263
- 4
2266
+ 5
2264
2267
  ];
2265
- case 8:
2268
+ case 9:
2266
2269
  return [
2267
2270
  3,
2268
- 11
2271
+ 12
2269
2272
  ];
2270
- case 9:
2273
+ case 10:
2271
2274
  err = _state.sent();
2272
2275
  _didIteratorError = true;
2273
2276
  _iteratorError = err;
2274
2277
  return [
2275
2278
  3,
2276
- 11
2279
+ 12
2277
2280
  ];
2278
- case 10:
2281
+ case 11:
2279
2282
  try {
2280
2283
  if (!_iteratorNormalCompletion && _iterator.return != null) {
2281
2284
  _iterator.return();
@@ -2288,123 +2291,685 @@ export var BrainEventStream = /*#__PURE__*/ function() {
2288
2291
  return [
2289
2292
  7
2290
2293
  ];
2291
- case 11:
2292
- chunkEnd = Math.min(chunkStart + concurrency, totalItems);
2293
- chunk = items.slice(chunkStart, chunkEnd);
2294
- return [
2295
- 4,
2296
- _await_async_generator(Promise.all(chunk.map(function(item) {
2297
- return _async_to_generator(function() {
2298
- var release, promptText, result, error, fallback;
2299
- return _ts_generator(this, function(_state) {
2300
- switch(_state.label){
2301
- case 0:
2302
- return [
2303
- 4,
2304
- semaphore.acquire()
2305
- ];
2306
- case 1:
2307
- release = _state.sent();
2308
- _state.label = 2;
2309
- case 2:
2310
- _state.trys.push([
2311
- 2,
2312
- 5,
2313
- 6,
2314
- 7
2315
- ]);
2316
- return [
2317
- 4,
2318
- batchConfig.template(item, this.resources)
2319
- ];
2320
- case 3:
2321
- promptText = _state.sent();
2322
- return [
2323
- 4,
2324
- client.generateObject({
2325
- schema: batchConfig.schema,
2326
- schemaName: batchConfig.schemaName,
2327
- prompt: promptText
2328
- })
2329
- ];
2330
- case 4:
2331
- result = _state.sent();
2332
- return [
2333
- 2,
2334
- [
2335
- item,
2336
- result.object
2337
- ]
2338
- ];
2339
- case 5:
2340
- error = _state.sent();
2341
- if (batchConfig.error) {
2342
- fallback = batchConfig.error(item, error);
2343
- return [
2344
- 2,
2345
- fallback !== null ? [
2346
- item,
2347
- fallback
2348
- ] : undefined
2349
- ];
2350
- }
2351
- throw error;
2352
- case 6:
2353
- release();
2354
- return [
2355
- 7
2356
- ];
2357
- case 7:
2358
- return [
2359
- 2
2360
- ];
2361
- }
2362
- });
2363
- }).call(_this);
2364
- })))
2365
- ];
2366
2294
  case 12:
2367
- chunkResults = _state.sent();
2368
- // Store chunk results at correct indices
2369
- for(i = 0; i < chunkResults.length; i++){
2370
- results[chunkStart + i] = chunkResults[i];
2295
+ item = items[i];
2296
+ result = void 0;
2297
+ _state.label = 13;
2298
+ case 13:
2299
+ _state.trys.push([
2300
+ 13,
2301
+ 16,
2302
+ ,
2303
+ 17
2304
+ ]);
2305
+ return [
2306
+ 4,
2307
+ _await_async_generator(iterateConfig.template({
2308
+ item: item,
2309
+ state: this.currentState,
2310
+ options: (_this_options1 = this.options) !== null && _this_options1 !== void 0 ? _this_options1 : {},
2311
+ resources: this.resources
2312
+ }))
2313
+ ];
2314
+ case 14:
2315
+ promptText = _state.sent();
2316
+ return [
2317
+ 4,
2318
+ _await_async_generator(client.generateObject({
2319
+ schema: iterateConfig.schema,
2320
+ schemaName: iterateConfig.schemaName,
2321
+ prompt: promptText
2322
+ }))
2323
+ ];
2324
+ case 15:
2325
+ response = _state.sent();
2326
+ result = [
2327
+ item,
2328
+ response.object
2329
+ ];
2330
+ return [
2331
+ 3,
2332
+ 17
2333
+ ];
2334
+ case 16:
2335
+ error = _state.sent();
2336
+ if (iterateConfig.error) {
2337
+ fallback = iterateConfig.error(item, error);
2338
+ result = fallback !== null ? [
2339
+ item,
2340
+ fallback
2341
+ ] : undefined;
2342
+ } else {
2343
+ throw error;
2344
+ }
2345
+ return [
2346
+ 3,
2347
+ 17
2348
+ ];
2349
+ case 17:
2350
+ if (result != null) {
2351
+ resultsMap.set(i, result);
2371
2352
  }
2372
- // Yield ONE event per chunk
2353
+ // Yield one event per item
2373
2354
  return [
2374
2355
  4,
2375
2356
  {
2376
- type: BRAIN_EVENTS.BATCH_CHUNK_COMPLETE,
2357
+ type: BRAIN_EVENTS.ITERATE_ITEM_COMPLETE,
2377
2358
  stepTitle: step.block.title,
2378
2359
  stepId: step.id,
2379
- chunkStartIndex: chunkStart,
2380
- processedCount: chunkEnd,
2360
+ itemIndex: i,
2361
+ item: item,
2362
+ result: result ? result[1] : undefined,
2363
+ processedCount: i + 1,
2381
2364
  totalItems: totalItems,
2382
- chunkResults: chunkResults,
2383
- schemaName: batchConfig.schemaName,
2384
- options: (_this_options1 = this.options) !== null && _this_options1 !== void 0 ? _this_options1 : {},
2385
- brainRunId: this.brainRunId
2365
+ schemaName: iterateConfig.schemaName,
2366
+ options: (_this_options2 = this.options) !== null && _this_options2 !== void 0 ? _this_options2 : {},
2367
+ brainRunId: this.brainRunId,
2368
+ canRelease: !!this.signalProvider
2386
2369
  }
2387
2370
  ];
2388
- case 13:
2371
+ case 18:
2372
+ _state.sent();
2373
+ _state.label = 19;
2374
+ case 19:
2375
+ i++;
2376
+ return [
2377
+ 3,
2378
+ 2
2379
+ ];
2380
+ case 20:
2381
+ // All items done - update state and complete step
2382
+ finalResults = new IterateResult(_to_consumable_array(resultsMap.values()));
2383
+ this.currentState = _object_spread_props(_object_spread({}, this.currentState), _define_property({}, iterateConfig.schemaName, finalResults));
2384
+ return [
2385
+ 5,
2386
+ _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
2387
+ ];
2388
+ case 21:
2389
+ _state.sent();
2390
+ return [
2391
+ 2
2392
+ ];
2393
+ }
2394
+ });
2395
+ }).call(this);
2396
+ }
2397
+ },
2398
+ {
2399
+ key: "executeIterateBrain",
2400
+ value: /**
2401
+ * Execute a nested brain iterate step. Runs the inner brain once per item
2402
+ * from the `over` list, collects [item, innerState] tuples under `outputKey`.
2403
+ */ function executeIterateBrain(step) {
2404
+ return _wrap_async_generator(function() {
2405
+ var _this_resumeContext, block, iterateConfig, prevState, items, totalItems, iterateProgress, _iterateProgress_processedCount, startIndex, resultsMap, k, r, i, signals, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, signal, _this_options, err, item, result, initialState, _this_options1, innerRun, patches, _iteratorAbruptCompletion, _didIteratorError1, _iteratorError1, _iterator1, _step1, _value, event, err1, innerState, error, fallback, _this_options2, finalResults, outputResults;
2406
+ return _ts_generator(this, function(_state) {
2407
+ switch(_state.label){
2408
+ case 0:
2409
+ block = step.block;
2410
+ iterateConfig = block.iterateConfig;
2411
+ prevState = this.currentState;
2412
+ return [
2413
+ 4,
2414
+ _await_async_generator(iterateConfig.over(this.buildStepContext(step)))
2415
+ ];
2416
+ case 1:
2417
+ items = _state.sent();
2418
+ totalItems = items.length;
2419
+ // Resume support
2420
+ iterateProgress = (_this_resumeContext = this.resumeContext) === null || _this_resumeContext === void 0 ? void 0 : _this_resumeContext.iterateProgress;
2421
+ startIndex = (_iterateProgress_processedCount = iterateProgress === null || iterateProgress === void 0 ? void 0 : iterateProgress.processedCount) !== null && _iterateProgress_processedCount !== void 0 ? _iterateProgress_processedCount : 0;
2422
+ // Use a Map for results accumulation during iteration.
2423
+ resultsMap = new Map();
2424
+ if (iterateProgress === null || iterateProgress === void 0 ? void 0 : iterateProgress.accumulatedResults) {
2425
+ for(k = 0; k < iterateProgress.accumulatedResults.length; k++){
2426
+ r = iterateProgress.accumulatedResults[k];
2427
+ if (r != null) resultsMap.set(k, r);
2428
+ }
2429
+ }
2430
+ if (iterateProgress) {
2431
+ this.resumeContext = undefined;
2432
+ }
2433
+ i = startIndex;
2434
+ _state.label = 2;
2435
+ case 2:
2436
+ if (!(i < totalItems)) return [
2437
+ 3,
2438
+ 31
2439
+ ];
2440
+ if (!this.signalProvider) return [
2441
+ 3,
2442
+ 12
2443
+ ];
2444
+ return [
2445
+ 4,
2446
+ _await_async_generator(this.signalProvider.getSignals('CONTROL'))
2447
+ ];
2448
+ case 3:
2449
+ signals = _state.sent();
2450
+ _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2451
+ _state.label = 4;
2452
+ case 4:
2453
+ _state.trys.push([
2454
+ 4,
2455
+ 10,
2456
+ 11,
2457
+ 12
2458
+ ]);
2459
+ _iterator = signals[Symbol.iterator]();
2460
+ _state.label = 5;
2461
+ case 5:
2462
+ if (!!(_iteratorNormalCompletion = (_step = _iterator.next()).done)) return [
2463
+ 3,
2464
+ 9
2465
+ ];
2466
+ signal = _step.value;
2467
+ if (!(signal.type === 'KILL')) return [
2468
+ 3,
2469
+ 7
2470
+ ];
2471
+ this.stopped = true;
2472
+ return [
2473
+ 4,
2474
+ {
2475
+ type: BRAIN_EVENTS.CANCELLED,
2476
+ status: STATUS.CANCELLED,
2477
+ brainTitle: this.title,
2478
+ brainDescription: this.description,
2479
+ brainRunId: this.brainRunId,
2480
+ options: (_this_options = this.options) !== null && _this_options !== void 0 ? _this_options : {}
2481
+ }
2482
+ ];
2483
+ case 6:
2389
2484
  _state.sent();
2485
+ return [
2486
+ 2
2487
+ ];
2488
+ case 7:
2489
+ if (signal.type === 'PAUSE') {
2490
+ this.stopped = true;
2491
+ return [
2492
+ 2
2493
+ ];
2494
+ }
2495
+ _state.label = 8;
2496
+ case 8:
2497
+ _iteratorNormalCompletion = true;
2498
+ return [
2499
+ 3,
2500
+ 5
2501
+ ];
2502
+ case 9:
2503
+ return [
2504
+ 3,
2505
+ 12
2506
+ ];
2507
+ case 10:
2508
+ err = _state.sent();
2509
+ _didIteratorError = true;
2510
+ _iteratorError = err;
2511
+ return [
2512
+ 3,
2513
+ 12
2514
+ ];
2515
+ case 11:
2516
+ try {
2517
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
2518
+ _iterator.return();
2519
+ }
2520
+ } finally{
2521
+ if (_didIteratorError) {
2522
+ throw _iteratorError;
2523
+ }
2524
+ }
2525
+ return [
2526
+ 7
2527
+ ];
2528
+ case 12:
2529
+ item = items[i];
2530
+ result = void 0;
2531
+ _state.label = 13;
2532
+ case 13:
2533
+ _state.trys.push([
2534
+ 13,
2535
+ 27,
2536
+ ,
2537
+ 28
2538
+ ]);
2539
+ initialState = iterateConfig.initialState(item, this.currentState);
2540
+ innerRun = block.innerBrain.run({
2541
+ resources: this.resources,
2542
+ client: this.client,
2543
+ currentUser: this.currentUser,
2544
+ initialState: initialState,
2545
+ options: (_this_options1 = this.options) !== null && _this_options1 !== void 0 ? _this_options1 : {},
2546
+ pages: this.pages,
2547
+ env: this.env,
2548
+ brainRunId: this.brainRunId,
2549
+ governor: this.governor
2550
+ });
2551
+ patches = [];
2552
+ _iteratorAbruptCompletion = false, _didIteratorError1 = false;
2390
2553
  _state.label = 14;
2391
2554
  case 14:
2392
- chunkStart += concurrency;
2555
+ _state.trys.push([
2556
+ 14,
2557
+ 20,
2558
+ 21,
2559
+ 26
2560
+ ]);
2561
+ _iterator1 = _async_iterator(innerRun);
2562
+ _state.label = 15;
2563
+ case 15:
2393
2564
  return [
2565
+ 4,
2566
+ _await_async_generator(_iterator1.next())
2567
+ ];
2568
+ case 16:
2569
+ if (!(_iteratorAbruptCompletion = !(_step1 = _state.sent()).done)) return [
2394
2570
  3,
2395
- 1
2571
+ 19
2572
+ ];
2573
+ _value = _step1.value;
2574
+ event = _value;
2575
+ // Throw on WEBHOOK — not supported in iterate (Phase 2)
2576
+ if (event.type === BRAIN_EVENTS.WEBHOOK) {
2577
+ throw new Error("Webhook/wait inside brain iterate is not supported. " + 'Step "'.concat(block.title, '" item ').concat(i, " triggered a webhook. ") + "Remove .wait() from the inner brain or process items outside of iterate.");
2578
+ }
2579
+ return [
2580
+ 4,
2581
+ event
2582
+ ];
2583
+ case 17:
2584
+ _state.sent(); // Forward all inner events
2585
+ if (event.type === BRAIN_EVENTS.STEP_COMPLETE) {
2586
+ patches.push(event.patch);
2587
+ }
2588
+ if (event.type === BRAIN_EVENTS.COMPLETE) {
2589
+ return [
2590
+ 3,
2591
+ 19
2592
+ ];
2593
+ }
2594
+ _state.label = 18;
2595
+ case 18:
2596
+ _iteratorAbruptCompletion = false;
2597
+ return [
2598
+ 3,
2599
+ 15
2600
+ ];
2601
+ case 19:
2602
+ return [
2603
+ 3,
2604
+ 26
2605
+ ];
2606
+ case 20:
2607
+ err1 = _state.sent();
2608
+ _didIteratorError1 = true;
2609
+ _iteratorError1 = err1;
2610
+ return [
2611
+ 3,
2612
+ 26
2613
+ ];
2614
+ case 21:
2615
+ _state.trys.push([
2616
+ 21,
2617
+ ,
2618
+ 24,
2619
+ 25
2620
+ ]);
2621
+ if (!(_iteratorAbruptCompletion && _iterator1.return != null)) return [
2622
+ 3,
2623
+ 23
2624
+ ];
2625
+ return [
2626
+ 4,
2627
+ _await_async_generator(_iterator1.return())
2628
+ ];
2629
+ case 22:
2630
+ _state.sent();
2631
+ _state.label = 23;
2632
+ case 23:
2633
+ return [
2634
+ 3,
2635
+ 25
2636
+ ];
2637
+ case 24:
2638
+ if (_didIteratorError1) {
2639
+ throw _iteratorError1;
2640
+ }
2641
+ return [
2642
+ 7
2643
+ ];
2644
+ case 25:
2645
+ return [
2646
+ 7
2647
+ ];
2648
+ case 26:
2649
+ innerState = applyPatches(initialState, patches);
2650
+ result = [
2651
+ item,
2652
+ innerState
2396
2653
  ];
2397
- case 15:
2398
- // All chunks done - update state and complete step
2399
- finalResults = results.filter(function(r) {
2400
- return r != null;
2401
- });
2402
- this.currentState = _object_spread_props(_object_spread({}, this.currentState), _define_property({}, batchConfig.schemaName, finalResults));
2654
+ return [
2655
+ 3,
2656
+ 28
2657
+ ];
2658
+ case 27:
2659
+ error = _state.sent();
2660
+ if (iterateConfig.error) {
2661
+ fallback = iterateConfig.error(item, error);
2662
+ result = fallback !== null ? [
2663
+ item,
2664
+ fallback
2665
+ ] : undefined;
2666
+ } else {
2667
+ throw error;
2668
+ }
2669
+ return [
2670
+ 3,
2671
+ 28
2672
+ ];
2673
+ case 28:
2674
+ if (result != null) {
2675
+ resultsMap.set(i, result);
2676
+ }
2677
+ return [
2678
+ 4,
2679
+ {
2680
+ type: BRAIN_EVENTS.ITERATE_ITEM_COMPLETE,
2681
+ stepTitle: step.block.title,
2682
+ stepId: step.id,
2683
+ itemIndex: i,
2684
+ item: item,
2685
+ result: result ? result[1] : undefined,
2686
+ processedCount: i + 1,
2687
+ totalItems: totalItems,
2688
+ schemaName: iterateConfig.outputKey,
2689
+ options: (_this_options2 = this.options) !== null && _this_options2 !== void 0 ? _this_options2 : {},
2690
+ brainRunId: this.brainRunId,
2691
+ canRelease: !!this.signalProvider
2692
+ }
2693
+ ];
2694
+ case 29:
2695
+ _state.sent();
2696
+ _state.label = 30;
2697
+ case 30:
2698
+ i++;
2699
+ return [
2700
+ 3,
2701
+ 2
2702
+ ];
2703
+ case 31:
2704
+ finalResults = _to_consumable_array(resultsMap.values());
2705
+ outputResults = new IterateResult(finalResults);
2706
+ this.currentState = _object_spread_props(_object_spread({}, this.currentState), _define_property({}, iterateConfig.outputKey, outputResults));
2403
2707
  return [
2404
2708
  5,
2405
2709
  _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
2406
2710
  ];
2407
- case 16:
2711
+ case 32:
2712
+ _state.sent();
2713
+ return [
2714
+ 2
2715
+ ];
2716
+ }
2717
+ });
2718
+ }).call(this);
2719
+ }
2720
+ },
2721
+ {
2722
+ key: "executeIterateAgent",
2723
+ value: /**
2724
+ * Execute an agent config iterate step. Runs the agent once per item
2725
+ * from the `over` list, collects [item, agentResult] tuples under `outputKey`.
2726
+ */ function executeIterateAgent(step) {
2727
+ return _wrap_async_generator(function() {
2728
+ var _this, _loop, _this_resumeContext, block, iterateConfig, prevState, items, totalItems, iterateProgress, _iterateProgress_processedCount, startIndex, resultsMap, k, r, i, _ret, finalResults;
2729
+ return _ts_generator(this, function(_state) {
2730
+ switch(_state.label){
2731
+ case 0:
2732
+ _loop = function(i) {
2733
+ var signals, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, signal, _this_options, err, item, result, savedState, itemConfigFn, tempBlock, tempStep, agentResult, error, fallback, _this_options1;
2734
+ return _ts_generator(this, function(_state) {
2735
+ switch(_state.label){
2736
+ case 0:
2737
+ if (!_this.signalProvider) return [
2738
+ 3,
2739
+ 10
2740
+ ];
2741
+ return [
2742
+ 4,
2743
+ _await_async_generator(_this.signalProvider.getSignals('CONTROL'))
2744
+ ];
2745
+ case 1:
2746
+ signals = _state.sent();
2747
+ _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2748
+ _state.label = 2;
2749
+ case 2:
2750
+ _state.trys.push([
2751
+ 2,
2752
+ 8,
2753
+ 9,
2754
+ 10
2755
+ ]);
2756
+ _iterator = signals[Symbol.iterator]();
2757
+ _state.label = 3;
2758
+ case 3:
2759
+ if (!!(_iteratorNormalCompletion = (_step = _iterator.next()).done)) return [
2760
+ 3,
2761
+ 7
2762
+ ];
2763
+ signal = _step.value;
2764
+ if (!(signal.type === 'KILL')) return [
2765
+ 3,
2766
+ 5
2767
+ ];
2768
+ _this.stopped = true;
2769
+ return [
2770
+ 4,
2771
+ {
2772
+ type: BRAIN_EVENTS.CANCELLED,
2773
+ status: STATUS.CANCELLED,
2774
+ brainTitle: _this.title,
2775
+ brainDescription: _this.description,
2776
+ brainRunId: _this.brainRunId,
2777
+ options: (_this_options = _this.options) !== null && _this_options !== void 0 ? _this_options : {}
2778
+ }
2779
+ ];
2780
+ case 4:
2781
+ _state.sent();
2782
+ return [
2783
+ 2,
2784
+ {
2785
+ v: void void 0
2786
+ }
2787
+ ];
2788
+ case 5:
2789
+ if (signal.type === 'PAUSE') {
2790
+ _this.stopped = true;
2791
+ return [
2792
+ 2,
2793
+ {
2794
+ v: void void 0
2795
+ }
2796
+ ];
2797
+ }
2798
+ _state.label = 6;
2799
+ case 6:
2800
+ _iteratorNormalCompletion = true;
2801
+ return [
2802
+ 3,
2803
+ 3
2804
+ ];
2805
+ case 7:
2806
+ return [
2807
+ 3,
2808
+ 10
2809
+ ];
2810
+ case 8:
2811
+ err = _state.sent();
2812
+ _didIteratorError = true;
2813
+ _iteratorError = err;
2814
+ return [
2815
+ 3,
2816
+ 10
2817
+ ];
2818
+ case 9:
2819
+ try {
2820
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
2821
+ _iterator.return();
2822
+ }
2823
+ } finally{
2824
+ if (_didIteratorError) {
2825
+ throw _iteratorError;
2826
+ }
2827
+ }
2828
+ return [
2829
+ 7
2830
+ ];
2831
+ case 10:
2832
+ item = items[i];
2833
+ result = void 0;
2834
+ _state.label = 11;
2835
+ case 11:
2836
+ _state.trys.push([
2837
+ 11,
2838
+ 13,
2839
+ ,
2840
+ 14
2841
+ ]);
2842
+ // Save outer state; agent will modify this.currentState
2843
+ savedState = _this.currentState;
2844
+ // Create a wrapper configFn that injects the item as the first argument
2845
+ itemConfigFn = function(params) {
2846
+ return block.configFn(item, params);
2847
+ };
2848
+ // Create a temporary agent block with the per-item configFn
2849
+ tempBlock = {
2850
+ type: 'agent',
2851
+ title: block.title,
2852
+ configFn: itemConfigFn
2853
+ };
2854
+ tempStep = new Step(tempBlock);
2855
+ return [
2856
+ 5,
2857
+ _ts_values(_async_generator_delegate(_async_iterator(_this.executeAgent(tempStep))))
2858
+ ];
2859
+ case 12:
2860
+ _state.sent();
2861
+ // Capture agent result from this.currentState, then restore outer state
2862
+ agentResult = _this.currentState;
2863
+ _this.currentState = savedState;
2864
+ result = [
2865
+ item,
2866
+ agentResult
2867
+ ];
2868
+ return [
2869
+ 3,
2870
+ 14
2871
+ ];
2872
+ case 13:
2873
+ error = _state.sent();
2874
+ if (iterateConfig.error) {
2875
+ fallback = iterateConfig.error(item, error);
2876
+ result = fallback !== null ? [
2877
+ item,
2878
+ fallback
2879
+ ] : undefined;
2880
+ } else {
2881
+ throw error;
2882
+ }
2883
+ return [
2884
+ 3,
2885
+ 14
2886
+ ];
2887
+ case 14:
2888
+ if (result != null) {
2889
+ resultsMap.set(i, result);
2890
+ }
2891
+ return [
2892
+ 4,
2893
+ {
2894
+ type: BRAIN_EVENTS.ITERATE_ITEM_COMPLETE,
2895
+ stepTitle: step.block.title,
2896
+ stepId: step.id,
2897
+ itemIndex: i,
2898
+ item: item,
2899
+ result: result ? result[1] : undefined,
2900
+ processedCount: i + 1,
2901
+ totalItems: totalItems,
2902
+ schemaName: iterateConfig.outputKey,
2903
+ options: (_this_options1 = _this.options) !== null && _this_options1 !== void 0 ? _this_options1 : {},
2904
+ brainRunId: _this.brainRunId,
2905
+ canRelease: !!_this.signalProvider
2906
+ }
2907
+ ];
2908
+ case 15:
2909
+ _state.sent();
2910
+ return [
2911
+ 2
2912
+ ];
2913
+ }
2914
+ });
2915
+ };
2916
+ block = step.block;
2917
+ iterateConfig = block.iterateConfig;
2918
+ prevState = this.currentState;
2919
+ return [
2920
+ 4,
2921
+ _await_async_generator(iterateConfig.over(this.buildStepContext(step)))
2922
+ ];
2923
+ case 1:
2924
+ items = _state.sent();
2925
+ totalItems = items.length;
2926
+ // Resume support
2927
+ iterateProgress = (_this_resumeContext = this.resumeContext) === null || _this_resumeContext === void 0 ? void 0 : _this_resumeContext.iterateProgress;
2928
+ startIndex = (_iterateProgress_processedCount = iterateProgress === null || iterateProgress === void 0 ? void 0 : iterateProgress.processedCount) !== null && _iterateProgress_processedCount !== void 0 ? _iterateProgress_processedCount : 0;
2929
+ // Use a Map for results accumulation during iteration.
2930
+ resultsMap = new Map();
2931
+ if (iterateProgress === null || iterateProgress === void 0 ? void 0 : iterateProgress.accumulatedResults) {
2932
+ for(k = 0; k < iterateProgress.accumulatedResults.length; k++){
2933
+ r = iterateProgress.accumulatedResults[k];
2934
+ if (r != null) resultsMap.set(k, r);
2935
+ }
2936
+ }
2937
+ if (iterateProgress) {
2938
+ this.resumeContext = undefined;
2939
+ }
2940
+ i = startIndex;
2941
+ _state.label = 2;
2942
+ case 2:
2943
+ if (!(i < totalItems)) return [
2944
+ 3,
2945
+ 5
2946
+ ];
2947
+ _this = this;
2948
+ return [
2949
+ 5,
2950
+ _ts_values(_loop(i))
2951
+ ];
2952
+ case 3:
2953
+ _ret = _state.sent();
2954
+ if (_type_of(_ret) === "object") return [
2955
+ 2,
2956
+ _ret.v
2957
+ ];
2958
+ _state.label = 4;
2959
+ case 4:
2960
+ i++;
2961
+ return [
2962
+ 3,
2963
+ 2
2964
+ ];
2965
+ case 5:
2966
+ finalResults = new IterateResult(_to_consumable_array(resultsMap.values()));
2967
+ this.currentState = _object_spread_props(_object_spread({}, this.currentState), _define_property({}, iterateConfig.outputKey, finalResults));
2968
+ return [
2969
+ 5,
2970
+ _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
2971
+ ];
2972
+ case 6:
2408
2973
  _state.sent();
2409
2974
  return [
2410
2975
  2
@@ -2421,7 +2986,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
2421
2986
  * Generates UI components, renders to HTML, creates page, and sets up webhook.
2422
2987
  */ function executeUIStep(step, stepBlock) {
2423
2988
  return _wrap_async_generator(function() {
2424
- var prevState, uiConfig, prompt, uiResult, placementCount, placementInfo, _uiResult_text, webhookIdentifier, formToken, formAction, html, page, _uiConfig_responseSchema, webhook;
2989
+ var prevState, uiConfig, _this_options, prompt, uiResult, placementCount, placementInfo, _uiResult_text, webhookIdentifier, formToken, formAction, html, page, _uiConfig_responseSchema, webhook;
2425
2990
  return _ts_generator(this, function(_state) {
2426
2991
  switch(_state.label){
2427
2992
  case 0:
@@ -2436,7 +3001,11 @@ export var BrainEventStream = /*#__PURE__*/ function() {
2436
3001
  uiConfig = stepBlock.uiConfig;
2437
3002
  return [
2438
3003
  4,
2439
- _await_async_generator(uiConfig.template(this.currentState, this.resources))
3004
+ _await_async_generator(uiConfig.template({
3005
+ state: this.currentState,
3006
+ options: (_this_options = this.options) !== null && _this_options !== void 0 ? _this_options : {},
3007
+ resources: this.resources
3008
+ }))
2440
3009
  ];
2441
3010
  case 1:
2442
3011
  prompt = _state.sent();
@@ -2504,7 +3073,14 @@ export var BrainEventStream = /*#__PURE__*/ function() {
2504
3073
  // The next step will receive the page object and can use waitFor
2505
3074
  return [
2506
3075
  5,
2507
- _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
3076
+ _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState, {
3077
+ url: page.url,
3078
+ webhook: {
3079
+ slug: webhook.slug,
3080
+ identifier: webhook.identifier,
3081
+ token: webhook.token
3082
+ }
3083
+ }))))
2508
3084
  ];
2509
3085
  case 4:
2510
3086
  _state.sent();
@@ -2761,7 +3337,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
2761
3337
  },
2762
3338
  {
2763
3339
  key: "completeStep",
2764
- value: function completeStep(step, prevState) {
3340
+ value: function completeStep(step, prevState, pageContext) {
2765
3341
  var patch, _this_options;
2766
3342
  return _ts_generator(this, function(_state) {
2767
3343
  switch(_state.label){
@@ -2772,15 +3348,18 @@ export var BrainEventStream = /*#__PURE__*/ function() {
2772
3348
  step.withPatch(patch);
2773
3349
  return [
2774
3350
  4,
2775
- {
3351
+ _object_spread_props(_object_spread({
2776
3352
  type: BRAIN_EVENTS.STEP_COMPLETE,
2777
3353
  status: STATUS.RUNNING,
2778
3354
  stepTitle: step.block.title,
2779
3355
  stepId: step.id,
2780
- patch: patch,
3356
+ patch: patch
3357
+ }, pageContext && {
3358
+ pageContext: pageContext
3359
+ }), {
2781
3360
  options: (_this_options = this.options) !== null && _this_options !== void 0 ? _this_options : {},
2782
3361
  brainRunId: this.brainRunId
2783
- }
3362
+ })
2784
3363
  ];
2785
3364
  case 1:
2786
3365
  _state.sent();